FangSen9000 Claude commited on
Commit ·
0a2e9f2
1
Parent(s): adbfc5d
Add One-to-All-Animation: Batch 1 - Small files and directories
Browse files- Added LICENSE, README.md, requirements.txt
- Added datasets/, benchmark/, video-generation/, examples/, assets/
- Total size: ~100MB
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- One-to-All-AnimationDeleted-1
- One-to-All-Animation/LICENSEAdded+201
- One-to-All-Animation/README.mdAdded+310
- One-to-All-Animation/assets/1.3b_examples/combined_video1.gifAdded
- One-to-All-Animation/assets/1.3b_examples/combined_video2.gifAdded
- One-to-All-Animation/assets/1.3b_examples/ref3_motion1_1.3b.gifAdded
- One-to-All-Animation/assets/1.3b_examples/ref3_motion2_1.3b.gifAdded
- One-to-All-Animation/assets/1.3b_examples/ref3_motion3_1.3b.gifAdded
- One-to-All-Animation/assets/14b_examples/ref_1_motion1.gifAdded
- One-to-All-Animation/assets/14b_examples/ref_1_motion2.gifAdded
- One-to-All-Animation/assets/14b_examples/ref_1_motion3.gifAdded
- One-to-All-Animation/assets/14b_examples/ref_2_motion1.gifAdded
- One-to-All-Animation/assets/14b_examples/ref_2_motion2.gifAdded
- One-to-All-Animation/assets/14b_examples/ref_2_motion3.gifAdded
- One-to-All-Animation/benchmark/DisCo/.gitignoreAdded+74
- One-to-All-Animation/benchmark/DisCo/LICENSEAdded+201
- One-to-All-Animation/benchmark/DisCo/PREPRO.mdAdded+107
- One-to-All-Animation/benchmark/DisCo/README.mdAdded+426
- One-to-All-Animation/benchmark/DisCo/agent.pyAdded+1302
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/DockerfileAdded+11
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/LICENSEAdded+201
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/README.mdAdded+163
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/__init__.pyAdded
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinB.cfg.pyAdded+43
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.pyAdded+43
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/datasets/__init__.pyAdded
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/datasets/transforms.pyAdded+311
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/__init__.pyAdded+15
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/__init__.pyAdded+1
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/backbone.pyAdded+221
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/position_encoding.pyAdded+186
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/swin_transformer.pyAdded+802
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/bertwarper.pyAdded+273
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn.hAdded+64
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.cppAdded+43
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.hAdded+35
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.cuAdded+156
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.hAdded+33
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_im2col_cuda.cuhAdded+1327
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/cuda_version.cuAdded+7
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/vision.cppAdded+58
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/fuse_modules.pyAdded+297
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/groundingdino.pyAdded+395
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/ms_deform_attn.pyAdded+413
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/transformer.pyAdded+959
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/transformer_vanilla.pyAdded+123
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/utils.pyAdded+268
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/__init__.pyAdded+18
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/registry.pyAdded+66
- One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/__init__.pyAdded+1
1Subproject commit fc608e58e3956f26aebf44a4387701f5d64ffd4a123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310<div align="center">
<h1> <br> One-to-All Animation: Alignment-Free <br> Character Animation and Image Pose Transfer</h1>
<p>Shijun Shi<sup>1*</sup>, Jing Xu<sup>2*</sup>, Zhihang Li<sup>3</sup>, Chunli Peng<sup>4</sup>, Xiaoda Yang<sup>5</sup>, Lijing Lu<sup>3</sup>, <br> Kai Hu<sup>1†</sup>, Jiangning Zhang<sup>5†</sup></p>
<p style="font-size: 0.9em; color: #666;"><sup>1</sup>Jiangnan University <sup>2</sup>University of Science and Technology of China <sup>3</sup>Chinese Academy of Sciences<br><sup>4</sup>Beijing University of Posts and Telecommunications <sup>5</sup>Zhejiang University</p>
<p style="font-size: 0.85em; color: #888;"><sup>*</sup>Equal contribution <sup>†</sup>Corresponding authors</p>
<p align="center"> <a href="https://ssj9596.github.io/one-to-all-animation-project/" target="_blank"> <img src="https://img.shields.io/badge/🌐%20Project%20Page-Visit%20Website-4285F4?style=for-the-badge&logoColor=white" height="30"/> </a> <a href="https://arxiv.org/abs/2511.22940" target="_blank"> <img src="https://img.shields.io/badge/📄%20arXiv-2511.22940-B31B1B?style=for-the-badge&logoColor=white" height="30"/> </a></p></div>
<br>
## 🌟 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
<br>
## 🔥 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.
<br>
## 🎭 Showcase
Our model can adapt a single reference image to various motion patterns, demonstrating flexible motion control capabilities.
#### 14B Model
<table align="center"> <tr> <th style="text-align: center;">Reference</th> <th style="text-align: center;">Motion 1</th> <th style="text-align: center;">Motion 2</th> <th style="text-align: center;">Motion 3</th> </tr> <tr> <td align="center" style="padding: 2px;"><img src="./examples/new_examples/1.png" height="250"/></td> <td align="center" style="padding: 2px;"><img src="assets/14b_examples/ref_1_motion1.gif" height="250"/></td> <td align="center" style="padding: 2px;"><img src="assets/14b_examples/ref_1_motion2.gif" height="250"/></td> <td align="center" style="padding: 2px;"><img src="assets/14b_examples/ref_1_motion3.gif" height="250"/></td> </tr> <tr> <td align="center" style="padding: 2px;"><img src="./examples/new_examples/2.png" height="250"/></td> <td align="center" style="padding: 2px;"><img src="assets/14b_examples/ref_2_motion1.gif" height="250"/></td> <td align="center" style="padding: 2px;"><img src="assets/14b_examples/ref_2_motion2.gif" height="250"/></td> <td align="center" style="padding: 2px;"><img src="assets/14b_examples/ref_2_motion3.gif" height="250"/></td> </tr></table>
<br>
#### 1.3B ModelThe 1.3 B model also delivers strong performance (from 1.3b_2 ckpt).
<table align="center"> <tr> <th style="text-align: center;">Reference</th> <th style="text-align: center;">Motion 1</th> <th style="text-align: center;">Motion 2</th> <th style="text-align: center;">Motion 3</th> </tr> <tr> <td align="center" style="padding: 2px;"><img src="./examples/new_examples/3.png" height="250"/></td> <td align="center" style="padding: 2px;"><img src="assets/1.3b_examples/ref3_motion1_1.3b.gif" height="250"/></td> <td align="center" style="padding: 2px;"><img src="assets/1.3b_examples/ref3_motion2_1.3b.gif" height="250"/></td> <td align="center" style="padding: 2px;"><img src="assets/1.3b_examples/ref3_motion3_1.3b.gif" height="250"/></td> </tr></table>
Also support longer video & out-of-domain cases <p align="center"> <img src="./assets/1.3b_examples/combined_video1.gif" height="250"/> <img src="./assets/1.3b_examples/combined_video2.gif" height="250"/></p>
<br>
## 🔧 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).
<br>
## ☕️ Quick Inference
We provide several examples in the [`examples`](./examples) folder. Run the following commands to try it out:
```bash# Step 1: Prepare model inputcd video-generationpython infer_preprocess.py
# Step 2: Run inference with your preferred modelpython inference_1.3b.py # For 1.3B model# orpython inference_14b.py # For 14B model```You can enter the script to modify the input path.
<br>
## 🎬 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/` <details> <summary>Manual Download Links</summary> - [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) </details>
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
<br>
## 📊 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 ```
<br>
## 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.
## 📝 CitationIf 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}}```## 📄 LicenseThis repository is released under the [Apache License 2.0](LICENSE).
## 📧 ContactIf you have any questions, please feel free to reach us at `ssj180123@gmail.com`1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374aux_dataazcopyvis_temp.amltconfig*.ptscripts/webvid_train_filelist.*scripts/webvid_val_filelist.*tool/ori.pngtool/gt.jpgsrc/taming-transformerssrc/clip.vscodexiyin_datasetstiktok_datasetsblob_dirblob.amltconfig
# Byte-compiled / optimized / DLL files__pycache__/*.py[cod] C extensions*.so
# Distribution / packagingbin/build/develop-eggs/dist/eggs/lib/lib64/parts/sdist/var/*.egg-info/.installed.cfg*.egg
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reports.tox/.coverage.cachenosetests.xmlcoverage.xml
# Translations*.mo
# Mr Developer.mr.developer.cfg.project.pydevproject
# Rope.ropeproject
# Django stuff:*.log*.pot
# Sphinx documentationdocs/_build/
# dirs/save_results/pretrain_model/command/cocoapidebug.sh123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107Here 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 weightswget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pthwget 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 weightswget -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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426# DisCo: Disentangled Control for Realistic Human Dance Generation
<a href='https://disco-dance.github.io/'><img src='https://img.shields.io/badge/Project-Page-Green'></a> <a href='https://arxiv.org/abs/2307.00040'><img src='https://img.shields.io/badge/Paper-Arxiv-red'></a> <a href='https://b9652ca65fb3fab63a.gradio.live/'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue'></a> [](https://colab.research.google.com/drive/1dErsSwSEdcAyP6V_mqayW0qdPuoHSz-j?usp=sharing) [](https://youtu.be/D_mPPjUCDjE) <a href='https://drive.google.com/file/d/1AlN3Thg46RlH5uhLK-ZAIivo-C8IJeif/view?usp=sharing/'><img src='https://img.shields.io/badge/Slides-GoogleDrive-yellow'></a>
[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")
<br><br/>
## :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:<p align="center"> <img src="figures/compare.png" width="90%" height="80%"></p><br><br/>
## 🎨 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!
<br><br/>
##### [[Online Gradio Demo]](https://b9652ca65fb3fab63a.gradio.live/) (Temporal)
<p align="center"> <img src="figures/demo.gif" width="90%" height="90%"></p>
<br><br/>
## 📝 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.
<br><br/>
## 🚀 Getting Started
### Installation
```sh## after py3.8 env initializationpip install --user torch==1.12.1+cu113 torchvision==0.13.1+cu113 -f https://download.pytorch.org/whl/torch_stable.htmlpip install --user progressbar psutil pymongo simplejson yacs boto3 pyyaml ete3 easydict deprecated future django orderedset python-magic datasets h5py omegaconf einops ipdbpip install --user --exists-action w -r requirements.txtpip install git+https://github.com/microsoft/azfuse.git
## for accelerationpip install --user deepspeed==0.6.3pip install -v -U git+https://github.com/facebookresearch/xformers.git@main#egg=xformers
## you may need to downgrade prototbuf to 3.20.xpip 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.
<br><br/>
### Human Attribute Pre-training
<p align="center"> <img src="figures/pretrain.gif" width="80%" height="80%"></p>
**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)**
<br><br/>
### Fine-tuning with Disentangled Control


<br><br/>
#### 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`.
<br><br/>#### 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`.]
```shellWANDB_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}
```shellbash 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)
<br><br/>
#### 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)
<br><br/>#### 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.```shellAZFUSE_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.
```shellbash 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)
<br><br/>
#### 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.
<br><br/>
### 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`.
```pythonAZFUSE_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```
<br><br/>## 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.
<br><br/>
## 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"
<br><br/>
## 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}}```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302from 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_wandbfrom utils.misc import humanbytesfrom utils.deepspeed import get_deepspeed_config, fp32_to_fp16import deepspeedfrom torch import nnimport torch.nn.functional as Ffrom utils.basic_utils import move_to_cudafrom utils.common import ensure_directoryfrom 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)1234567891011FROM pytorch/pytorch:1.13.1-cuda11.6-cudnn8-devel
COPY . /home/appuserWORKDIR /home/appuserRUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y# Below is for https://github.com/IDEA-Research/Grounded-Segment-Anything/issues/53ENV CUDA_HOME /usr/local/cuda-11.6/RUN python -m pip install -e segment_anythingRUN python -m pip install -e GroundingDINORUN pip install --upgrade diffusers[torch]RUN pip install opencv-python pycocotools matplotlib onnxruntime onnx ipykernel123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163# 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!
<details open><summary><font size="4">Description</font></summary><img src=".asset/hero_figure.png" alt="ODinW" width="100%"></details>
## 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.
```bashpip install -e .```
## Demo
```bashCUDA_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
<!-- insert a table --><table> <thead> <tr style="text-align: right;"> <th></th> <th>name</th> <th>backbone</th> <th>Data</th> <th>box AP on COCO</th> <th>Checkpoint</th> <th>Config</th> </tr> </thead> <tbody> <tr> <th>1</th> <td>GroundingDINO-T</td> <td>Swin-T</td> <td>O365,GoldG,Cap4M</td> <td>48.4 (zero-shot) / 57.2 (fine-tune)</td> <td><a href="https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth">Github link</a> | <a href="https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swint_ogc.pth">HF link</a></td> <td><a href="https://github.com/IDEA-Research/GroundingDINO/blob/main/groundingdino/config/GroundingDINO_SwinT_OGC.py">link</a></td> </tr> </tbody></table>
## Results
<details open><summary><font size="4">COCO Object Detection Results</font></summary><img src=".asset/COCO.png" alt="COCO" width="100%"></details>
<details open><summary><font size="4">ODinW Object Detection Results</font></summary><img src=".asset/ODinW.png" alt="ODinW" width="100%"></details>
<details open><summary><font size="4">Marrying Grounding DINO with <a href="https://github.com/Stability-AI/StableDiffusion">Stable Diffusion</a> for Image Editing</font></summary><img src=".asset/GD_SD.png" alt="GD_SD" width="100%"></details>
<details open><summary><font size="4">Marrying Grounding DINO with <a href="https://github.com/gligen/GLIGEN">GLIGEN</a> for more Detailed Image Editing</font></summary><img src=".asset/GD_GLIGEN.png" alt="GD_GLIGEN" width="100%"></details>
## 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}}```
12345678910111213141516171819202122232425262728293031323334353637383940414243batch_size = 1modelname = "groundingdino"backbone = "swin_B_384_22k"position_embedding = "sine"pe_temperatureH = 20pe_temperatureW = 20return_interm_indices = [1, 2, 3]backbone_freeze_keywords = Noneenc_layers = 6dec_layers = 6pre_norm = Falsedim_feedforward = 2048hidden_dim = 256dropout = 0.0nheads = 8num_queries = 900query_dim = 4num_patterns = 0num_feature_levels = 4enc_n_points = 4dec_n_points = 4two_stage_type = "standard"two_stage_bbox_embed_share = Falsetwo_stage_class_embed_share = Falsetransformer_activation = "relu"dec_pred_bbox_embed_share = Truedn_box_noise_scale = 1.0dn_label_noise_ratio = 0.5dn_label_coef = 1.0dn_bbox_coef = 1.0embed_init_tgt = Truedn_labelbook_size = 2000max_text_len = 256text_encoder_type = "bert-base-uncased"use_text_enhancer = Trueuse_fusion_layer = Trueuse_checkpoint = Trueuse_transformer_ckpt = Trueuse_text_cross_attention = Truetext_dropout = 0.0fusion_dropout = 0.0fusion_droppath = 0.1sub_sentence_present = True12345678910111213141516171819202122232425262728293031323334353637383940414243batch_size = 1modelname = "groundingdino"backbone = "swin_T_224_1k"position_embedding = "sine"pe_temperatureH = 20pe_temperatureW = 20return_interm_indices = [1, 2, 3]backbone_freeze_keywords = Noneenc_layers = 6dec_layers = 6pre_norm = Falsedim_feedforward = 2048hidden_dim = 256dropout = 0.0nheads = 8num_queries = 900query_dim = 4num_patterns = 0num_feature_levels = 4enc_n_points = 4dec_n_points = 4two_stage_type = "standard"two_stage_bbox_embed_share = Falsetwo_stage_class_embed_share = Falsetransformer_activation = "relu"dec_pred_bbox_embed_share = Truedn_box_noise_scale = 1.0dn_label_noise_ratio = 0.5dn_label_coef = 1.0dn_bbox_coef = 1.0embed_init_tgt = Truedn_labelbook_size = 2000max_text_len = 256text_encoder_type = "bert-base-uncased"use_text_enhancer = Trueuse_fusion_layer = Trueuse_checkpoint = Trueuse_transformer_ckpt = Trueuse_text_cross_attention = Truetext_dropout = 0.0fusion_dropout = 0.0fusion_droppath = 0.1sub_sentence_present = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved"""Transforms and data augmentation for both image + bbox."""import osimport random
import PILimport torchimport torchvision.transforms as Timport torchvision.transforms.functional as F
from groundingdino.util.box_ops import box_xyxy_to_cxcywhfrom 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_string123456789101112131415# ------------------------------------------------------------------------# 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_groundingdino1from .backbone import build_backbone123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221# ------------------------------------------------------------------------# 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 torchimport torch.nn.functional as Fimport torchvisionfrom torch import nnfrom torchvision.models._utils import IntermediateLayerGetter
from groundingdino.util.misc import NestedTensor, clean_state_dict, is_main_process
from .position_encoding import build_position_encodingfrom .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 model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186# ------------------------------------------------------------------------# 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 torchfrom 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_embedding123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802# ------------------------------------------------------------------------# 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 npimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.utils.checkpoint as checkpointfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273# ------------------------------------------------------------------------# 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 torchimport torch.nn.functional as Fimport torch.utils.checkpoint as checkpointfrom torch import Tensor, nnfrom torchvision.ops.boxes import nmsfrom transformers import BertConfig, BertModel, BertPreTrainedModelfrom 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_list12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364/*!*************************************************************************************************** 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::Tensorms_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<at::Tensor>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 groundingdino12345678910111213141516171819202122232425262728293031323334353637383940414243/*!*************************************************************************************************** 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 <vector>
#include <ATen/ATen.h>#include <ATen/cuda/CUDAContext.h>
namespace groundingdino {
at::Tensorms_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<at::Tensor>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 groundingdino1234567891011121314151617181920212223242526272829303132333435/*!*************************************************************************************************** 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 <torch/extension.h>
namespace groundingdino {
at::Tensorms_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<at::Tensor>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 groundingdino123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156/*!*************************************************************************************************** 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 <vector>#include "ms_deform_im2col_cuda.cuh"
#include <ATen/ATen.h>#include <ATen/cuda/CUDAContext.h>#include <cuda.h>#include <cuda_runtime.h>
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<scalar_t>() + n * im2col_step_ * per_value_size, spatial_shapes.data<int64_t>(), level_start_index.data<int64_t>(), sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size, attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size, batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point, columns.data<scalar_t>());
})); }
output = output.view({batch, num_query, num_heads*channels});
return output;}
std::vector<at::Tensor> 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<scalar_t>(), value.data<scalar_t>() + n * im2col_step_ * per_value_size, spatial_shapes.data<int64_t>(), level_start_index.data<int64_t>(), sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size, attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size, batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point, grad_value.data<scalar_t>() + n * im2col_step_ * per_value_size, grad_sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size, grad_attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size);
})); }
return { grad_value, grad_sampling_loc, grad_attn_weight };}
} // namespace groundingdino123456789101112131415161718192021222324252627282930313233/*!*************************************************************************************************** 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 <torch/extension.h>
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<at::Tensor> 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 groundingdino1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327/*!*************************************************************************** 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 <cstdio>#include <algorithm>#include <cstring>
#include <ATen/ATen.h>#include <ATen/cuda/CUDAContext.h>
#include <THC/THCAtomics.cuh>
#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 <typename scalar_t>__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 <typename scalar_t>__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 <typename scalar_t>__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 <typename scalar_t>__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 <typename scalar_t, unsigned int blockSize>__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 <typename scalar_t, unsigned int blockSize>__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 <typename scalar_t>__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 <typename scalar_t>__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 <typename scalar_t>__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 <typename scalar_t>__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 <typename scalar_t>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<scalar_t> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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 <typename scalar_t>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<scalar_t> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, num_threads*3*sizeof(scalar_t), stream>>>( 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<scalar_t> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 1> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 2> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 4> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 8> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 16> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 32> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 64> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 128> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 256> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 512> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t, 1024> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, 0, stream>>>( 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<scalar_t> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, num_threads*3*sizeof(scalar_t), stream>>>( 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<scalar_t> <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads, num_threads*3*sizeof(scalar_t), stream>>>( 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)); }
}1234567#include <cuda_runtime_api.h>
namespace groundingdino {int get_cudart_version() { return CUDART_VERSION;}} // namespace groundingdino12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
#include "MsDeformAttn/ms_deform_attn.h"
namespace groundingdino {
#ifdef WITH_CUDAextern 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.cppstd::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 groundingdino123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297# ------------------------------------------------------------------------# 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 torchimport torch.nn as nnimport torch.nn.functional as Ffrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395# ------------------------------------------------------------------------# 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 copyfrom typing import List
import torchimport torch.nn.functional as Ffrom torch import nnfrom torchvision.ops.boxes import nmsfrom transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast
from groundingdino.util import box_ops, get_tokenlizerfrom 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_posmapfrom groundingdino.util.visualizer import COCOVisualizerfrom groundingdino.util.vl_utils import create_positive_map_from_span
from ..registry import MODULE_BUILD_FUNCSfrom .backbone import build_backbonefrom .bertwarper import ( BertModelWarper, generate_masks_with_special_tokens, generate_masks_with_special_tokens_and_transfer_map,)from .transformer import build_transformerfrom .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 model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413# ------------------------------------------------------------------------# 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 mathimport warningsfrom typing import Optional
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.autograd import Functionfrom torch.autograd.function import once_differentiablefrom torch.nn.init import constant_, xavier_uniform_
try: from groundingdino import _Cexcept: warnings.warn("Failed to load custom C++ ops. Running on CPU mode Only!")
# helpersdef _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. <https://arxiv.org/pdf/2010.04159.pdf>`_.
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 _dummy123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959# ------------------------------------------------------------------------# 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 torchimport torch.utils.checkpoint as checkpointfrom torch import Tensor, nn
from groundingdino.util.misc import inverse_sigmoid
from .fuse_modules import BiAttentionBlockfrom .ms_deform_attn import MultiScaleDeformableAttention as MSDeformAttnfrom .transformer_vanilla import TransformerEncoderLayerfrom .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, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123# ------------------------------------------------------------------------# 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 torchimport torch.nn.functional as Ffrom 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 src123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268# ------------------------------------------------------------------------# 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 copyimport math
import torchimport torch.nn.functional as Ffrom 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_res123456789101112131415161718# ------------------------------------------------------------------------# 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 Reservedfrom .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 model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566# ------------------------------------------------------------------------# 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 inspectfrom 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")1# Copyright (c) Facebook, Inc. and its affiliates. All Rights ReservedOne-to-All-AnimationDeleted-1
One-to-All-Animation/LICENSEAdded+201
One-to-All-Animation/README.mdAdded+310
One-to-All-Animation/assets/1.3b_examples/combined_video1.gifAdded

Large File Pointer Details
- SHA256: 487ba3d6c6c1cecc9143ed3d8522b57aaf4b7b66f967183426c8f52c9e5f3994
- Pointer size: 132 Bytes
- Size of remote file: 4.24 MB
One-to-All-Animation/assets/1.3b_examples/combined_video2.gifAdded

Large File Pointer Details
- SHA256: c8ea42da6e9950a799be78d7858f7d1af3eb065bfd263b9f7dd0e473d23ce650
- Pointer size: 132 Bytes
- Size of remote file: 3.02 MB
One-to-All-Animation/assets/1.3b_examples/ref3_motion1_1.3b.gifAdded

Large File Pointer Details
- SHA256: ebc323fa945867c1bee235c9323464841ea0a0ed739ec1e41fe856c00fcf3246
- Pointer size: 132 Bytes
- Size of remote file: 4.05 MB
One-to-All-Animation/assets/1.3b_examples/ref3_motion2_1.3b.gifAdded

Large File Pointer Details
- SHA256: 96794e244c648f7056512afc5a768a1b0c0e5baa48e80155250e52d1191d4450
- Pointer size: 132 Bytes
- Size of remote file: 6.76 MB
One-to-All-Animation/assets/1.3b_examples/ref3_motion3_1.3b.gifAdded

Large File Pointer Details
- SHA256: 3349b0bf3532a26991ea1a3b884c156320c64b6f982bbaf727d9d5761800d4a5
- Pointer size: 132 Bytes
- Size of remote file: 4.97 MB
One-to-All-Animation/assets/14b_examples/ref_1_motion1.gifAdded

Large File Pointer Details
- SHA256: 8a5fcf5f2e35bcd10bfdaf31ff302a8dcd74c44bbb92db971d4b86f1c57c01c8
- Pointer size: 132 Bytes
- Size of remote file: 4.12 MB
One-to-All-Animation/assets/14b_examples/ref_1_motion2.gifAdded

Large File Pointer Details
- SHA256: c47bcde2ac8be5302d3ffa392dc21ba795212546afa44b8480ddb1670d26dab6
- Pointer size: 132 Bytes
- Size of remote file: 6.96 MB
One-to-All-Animation/assets/14b_examples/ref_1_motion3.gifAdded

Large File Pointer Details
- SHA256: 2b906b415cef7da4750dae4a8b24b0e119caaa640b089c1d4cc8d7a6cbf41c14
- Pointer size: 132 Bytes
- Size of remote file: 5.01 MB
One-to-All-Animation/assets/14b_examples/ref_2_motion1.gifAdded

Large File Pointer Details
- SHA256: 886d569704ddc2b2d8c078c9ba4c475dae36176a4d28220eb0e59e898fe76c6b
- Pointer size: 132 Bytes
- Size of remote file: 3.22 MB
One-to-All-Animation/assets/14b_examples/ref_2_motion2.gifAdded

Large File Pointer Details
- SHA256: 1a110deda30864c3da83620adb17a882938945650f241aa8853efb31063028da
- Pointer size: 132 Bytes
- Size of remote file: 5.42 MB
One-to-All-Animation/assets/14b_examples/ref_2_motion3.gifAdded

Large File Pointer Details
- SHA256: b624d7ab4e9d8fd1e755b20a37ab24522673003f62a3354184544ceb5ae0969d
- Pointer size: 132 Bytes
- Size of remote file: 3.83 MB
One-to-All-Animation/benchmark/DisCo/.gitignoreAdded+74
One-to-All-Animation/benchmark/DisCo/LICENSEAdded+201
One-to-All-Animation/benchmark/DisCo/PREPRO.mdAdded+107
One-to-All-Animation/benchmark/DisCo/README.mdAdded+426
One-to-All-Animation/benchmark/DisCo/agent.pyAdded+1302
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/DockerfileAdded+11
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/LICENSEAdded+201
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/README.mdAdded+163
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/__init__.pyAdded
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinB.cfg.pyAdded+43
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.pyAdded+43
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/datasets/__init__.pyAdded
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/datasets/transforms.pyAdded+311
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/__init__.pyAdded+15
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/__init__.pyAdded+1
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/backbone.pyAdded+221
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/position_encoding.pyAdded+186
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/swin_transformer.pyAdded+802
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/bertwarper.pyAdded+273
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn.hAdded+64
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.cppAdded+43
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.hAdded+35
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.cuAdded+156
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.hAdded+33
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_im2col_cuda.cuhAdded+1327
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/cuda_version.cuAdded+7
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/vision.cppAdded+58
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/fuse_modules.pyAdded+297
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/groundingdino.pyAdded+395
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/ms_deform_attn.pyAdded+413
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/transformer.pyAdded+959
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/transformer_vanilla.pyAdded+123
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/utils.pyAdded+268
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/__init__.pyAdded+18
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/registry.pyAdded+66
One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/__init__.pyAdded+1