diff --git a/OpenTAD/.gitignore b/OpenTAD/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0526a57a4963a7a67133f9b008c2bbcd9c121dae --- /dev/null +++ b/OpenTAD/.gitignore @@ -0,0 +1,123 @@ +# ignore folder +.vscode +.idea +dataset +/pretrained/ +/logs/ +/exps/ +/trash/ + +# ignore annotation +!/data/ +/data/* +!/data/*.sh + +dcgm +log +*.err +*.out +/wandb/ +build/ +dist/ + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +parts/ +sdist/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ \ No newline at end of file diff --git a/OpenTAD/LICENSE b/OpenTAD/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/OpenTAD/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/OpenTAD/README.md b/OpenTAD/README.md new file mode 100644 index 0000000000000000000000000000000000000000..89706cd2e15257d0b3df36ec549d6ffad11dc968 --- /dev/null +++ b/OpenTAD/README.md @@ -0,0 +1,121 @@ +# OpenTAD: An Open-Source Temporal Action Detection Toolbox. + +

+ + + + + + + + +

+ +OpenTAD is an open-source temporal action detection (TAD) toolbox based on PyTorch. + + +## πŸ₯³ What's New + +- A technical report of this library will be provided soon. +- 2024/03/28: The beta version v0.1.0 of OpenTAD is released. Any feedbacks and suggestions are welcome! + + +## πŸ“– Major Features + +- **Support SoTA TAD methods with modular design.** We decompose the TAD pipeline into different components, and implement them in a modular way. This design makes it easy to implement new methods and reproduce existing methods. +- **Support multiple TAD datasets.** We support 8 TAD datasets, including ActivityNet-1.3, THUMOS-14, HACS, Ego4D-MQ, Epic-Kitchens-100, FineAction, Multi-THUMOS, Charades datasets. +- **Support feature-based training and end-to-end training.** The feature-based training can easily be extended to end-to-end training with raw video input, and the video backbone can be easily replaced. +- **Release various pre-extracted features.** We release the feature extraction code, as well as many pre-extracted features on each dataset. + +## 🌟 Model Zoo + + + + + + + + + + + + + + + + + + +
+ One Stage + + Two Stage + + DETR + + End-to-End Training +
+ + + + + + + +
+ +The detailed configs, results, and pretrained models of each method can be found in above folders. + +## πŸ› οΈ Installation + +Please refer to [install.md](docs/en/install.md) for installation and data preparation. + + +## πŸš€ Usage + +Please refer to [usage.md](docs/en/usage.md) for details of training and evaluation scripts. + + +## πŸ“„ Updates +Please refer to [changelog.md](docs/en/changelog.md) for update details. + + +## 🀝 Roadmap + +All the things that need to be done in the future is in [roadmap.md](docs/en/roadmap.md). + + +## πŸ–ŠοΈ Citation + +**[Acknowledgement]** This repo is inspired by [OpenMMLab](https://github.com/open-mmlab) project, and we give our thanks to their contributors. + +If you think this repo is helpful, please cite us: + +```bibtex +@misc{2024opentad, + title={OpenTAD: An Open-Source Toolbox for Temporal Action Detection}, + author={Shuming Liu, Chen Zhao, Fatimah Zohra, Mattia Soldan, Carlos Hinojosa, Alejandro Pardo, Anthony Cioppa, Lama Alssum, Mengmeng Xu, Merey Ramazanova, Juan LeΓ³n AlcΓ‘zar, Silvio Giancola, Bernard Ghanem}, + howpublished = {\url{https://github.com/sming256/opentad}}, + year={2024} +} +``` + +If you have any questions, please contact: `shuming.liu@kaust.edu.sa`. \ No newline at end of file diff --git a/OpenTAD/configs/_base_/datasets/activitynet-1.3/e2e_resize_768_1x224x224.py b/OpenTAD/configs/_base_/datasets/activitynet-1.3/e2e_resize_768_1x224x224.py new file mode 100644 index 0000000000000000000000000000000000000000..26746dc1ebe54880e94430dd0421c19cdc7e7ffe --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/activitynet-1.3/e2e_resize_768_1x224x224.py @@ -0,0 +1,85 @@ +dataset_type = "AnetResizeDataset" +annotation_path = "data/activitynet-1.3/annotations/activity_net.v1-3.min.json" +class_map = "data/activitynet-1.3/annotations/category_idx.txt" +data_path = "data/activitynet-1.3/raw_data/Anet_videos_15fps_short256" +block_list = "data/activitynet-1.3/raw_data/Anet_videos_15fps_short256/missing_files.txt" + +resize_length = 768 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs"]), + dict(type="Collect", inputs="imgs", keys=["masks"]), + ], + ), +) + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], + ground_truth_filename=annotation_path, + blocked_videos="data/activitynet-1.3/annotations/blocked.json", +) diff --git a/OpenTAD/configs/_base_/datasets/activitynet-1.3/features_tsp_pad.py b/OpenTAD/configs/_base_/datasets/activitynet-1.3/features_tsp_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..b20d0367b4fb6134ca5da5cb4f9ff68b50e54799 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/activitynet-1.3/features_tsp_pad.py @@ -0,0 +1,82 @@ +dataset_type = "AnetPaddingDataset" +annotation_path = "data/activitynet-1.3/annotations/activity_net.v1-3.min.json" +class_map = "data/activitynet-1.3/annotations/category_idx.txt" +data_path = "data/activitynet-1.3/features/anet_tsp_npy_unresize/" +block_list = "data/activitynet-1.3/features/anet_tsp_npy_unresize/missing_files.txt" + +pad_len = 768 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + feature_stride=16, + sample_stride=1, # 1x16=16 + offset_frames=8, + fps=15, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy", prefix="v_"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=pad_len, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + feature_stride=16, + sample_stride=1, # 1x16=16 + offset_frames=8, + fps=15, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy", prefix="v_"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Padding", length=pad_len), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + feature_stride=16, + sample_stride=1, # 1x16=16 + offset_frames=8, + fps=15, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy", prefix="v_"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Padding", length=pad_len), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], + ground_truth_filename=annotation_path, + blocked_videos="data/activitynet-1.3/annotations/blocked.json", +) diff --git a/OpenTAD/configs/_base_/datasets/activitynet-1.3/features_tsp_resize.py b/OpenTAD/configs/_base_/datasets/activitynet-1.3/features_tsp_resize.py new file mode 100644 index 0000000000000000000000000000000000000000..bbcba26ee6e6931dcf587490c9b0374cb813a7e4 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/activitynet-1.3/features_tsp_resize.py @@ -0,0 +1,73 @@ +dataset_type = "AnetResizeDataset" +annotation_path = "data/activitynet-1.3/annotations/activity_net.v1-3.min.json" +class_map = "data/activitynet-1.3/annotations/category_idx.txt" +data_path = "data/activitynet-1.3/features/anet_tsp_npy_unresize/" +block_list = "data/activitynet-1.3/features/anet_tsp_npy_unresize/missing_files.txt" + +resize_length = 128 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy", prefix="v_"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy", prefix="v_"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy", prefix="v_"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], + ground_truth_filename=annotation_path, + blocked_videos="data/activitynet-1.3/annotations/blocked.json", +) diff --git a/OpenTAD/configs/_base_/datasets/activitynet-1.3/features_tsp_resize_trunc.py b/OpenTAD/configs/_base_/datasets/activitynet-1.3/features_tsp_resize_trunc.py new file mode 100644 index 0000000000000000000000000000000000000000..97eda82553bca00a79b262fa54d516d5d54fc409 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/activitynet-1.3/features_tsp_resize_trunc.py @@ -0,0 +1,74 @@ +dataset_type = "AnetResizeDataset" +annotation_path = "data/activitynet-1.3/annotations/activity_net.v1-3.min.json" +class_map = "data/activitynet-1.3/annotations/category_idx.txt" +data_path = "data/activitynet-1.3/features/anet_tsp_npy_unresize/" +block_list = "data/activitynet-1.3/features/anet_tsp_npy_unresize/missing_files.txt" + +resize_length = 192 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy", prefix="v_"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="RandomTrunc", trunc_len=resize_length, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy", prefix="v_"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="testing", # validation + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy", prefix="v_"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], + ground_truth_filename=annotation_path, + blocked_videos="data/activitynet-1.3/annotations/blocked.json", +) diff --git a/OpenTAD/configs/_base_/datasets/charades/features_i3d_pad.py b/OpenTAD/configs/_base_/datasets/charades/features_i3d_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..b04803418dccc561aa52b4b80f4fefe1bdaf495c --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/charades/features_i3d_pad.py @@ -0,0 +1,82 @@ +dataset_type = "EpicKitchensPaddingDataset" +annotation_path = "data/charades/annotations/charades.json" +class_map = "data/charades/annotations/category_idx.txt" +data_path = "data/charades/features/i3d_charades_finetuned_stride8/" +block_list = data_path + "missing_files.txt" + +trunc_len = 768 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # dataloader setting + fps=24, + feature_stride=8, + sample_stride=1, + offset_frames=0, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=trunc_len, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="testing", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # dataloader setting + fps=24, + feature_stride=8, + sample_stride=1, + offset_frames=0, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Padding", length=trunc_len), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="testing", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # dataloader setting + fps=24, + feature_stride=8, + sample_stride=1, + offset_frames=0, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Padding", length=trunc_len), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="testing", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/charades/features_vgg_rgb_pad.py b/OpenTAD/configs/_base_/datasets/charades/features_vgg_rgb_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..7116ffe7939d27f000d158fbf2d9ee58cc1a922f --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/charades/features_vgg_rgb_pad.py @@ -0,0 +1,82 @@ +dataset_type = "EpicKitchensPaddingDataset" +annotation_path = "data/charades/annotations/charades.json" +class_map = "data/charades/annotations/category_idx.txt" +data_path = "data/charades/features/Charades_v1_features_vgg_rgb_stride4/" +block_list = data_path + "missing_files.txt" + +trunc_len = 1200 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # dataloader setting + fps=24, + feature_stride=4, + sample_stride=1, + offset_frames=0, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=trunc_len, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="testing", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # dataloader setting + fps=24, + feature_stride=4, + sample_stride=1, + offset_frames=0, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Padding", length=trunc_len), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="testing", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # dataloader setting + fps=24, + feature_stride=4, + sample_stride=1, + offset_frames=0, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Padding", length=trunc_len), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="testing", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/ego4d_mq/e2e_train_trunc_test_sw.py b/OpenTAD/configs/_base_/datasets/ego4d_mq/e2e_train_trunc_test_sw.py new file mode 100644 index 0000000000000000000000000000000000000000..20ee9095b867a5c01dff47f7974441f872767fcd --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/ego4d_mq/e2e_train_trunc_test_sw.py @@ -0,0 +1,101 @@ +annotation_path = "data/ego4d/annotations/ego4d_v2_220429.json" +class_map = "data/ego4d/annotations/category_idx.txt" +data_path = "data/ego4d/raw_data/MQ_data/mq_videos_short320/" +block_list = None + +window_size = 900 +# size 900 is enough for all ego4d mq videos +dataset = dict( + train=dict( + type="Ego4DPaddingDataset", + ann_file=annotation_path, + subset_name="train", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + # dataloader setting + feature_stride=16, + sample_stride=1, + offset_frames=8, # after resizing, the offset is 8 frames + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict( + type="LoadFrames", + num_clips=1, + method="random_trunc", + trunc_len=window_size, + trunc_thresh=0.3, + crop_ratio=[0.9, 1.0], + ), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 256)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(224, 224), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type="Ego4DSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # dataloader setting + window_size=window_size, + feature_stride=16, + sample_stride=1, + offset_frames=8, # after resizing, the offset is 8 frames + window_overlap_ratio=0, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type="Ego4DSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # dataloader setting + window_size=window_size, + feature_stride=16, + sample_stride=1, + offset_frames=8, # after resizing, the offset is 8 frames + window_overlap_ratio=0, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="val", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/ego4d_mq/features_internvideo_train_trunc_test_sw.py b/OpenTAD/configs/_base_/datasets/ego4d_mq/features_internvideo_train_trunc_test_sw.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c65f380a3b5ef1d41ec099ad9414a29555432a --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/ego4d_mq/features_internvideo_train_trunc_test_sw.py @@ -0,0 +1,82 @@ +annotation_path = "data/ego4d/annotations/ego4d_v2_220429.json" +class_map = "data/ego4d/annotations/category_idx.txt" +data_path = "data/ego4d/features/zoo_project/videomae_large_internvideo_img224_stride16_len16_interval1_ego4d/" +block_list = None + +window_size = 900 +# size 900 is enough for all ego4d mq videos +dataset = dict( + train=dict( + type="Ego4DPaddingDataset", + ann_file=annotation_path, + subset_name="train", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + # dataloader setting + feature_stride=16, + sample_stride=1, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=window_size, trunc_thresh=0.3, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type="Ego4DSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # dataloader setting + window_size=window_size, + feature_stride=16, + sample_stride=1, + offset_frames=8, + window_overlap_ratio=0, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type="Ego4DSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # dataloader setting + window_size=window_size, + feature_stride=16, + sample_stride=1, + offset_frames=8, + window_overlap_ratio=0, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="val", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/ego4d_mq/features_slowfast_trunc.py b/OpenTAD/configs/_base_/datasets/ego4d_mq/features_slowfast_trunc.py new file mode 100644 index 0000000000000000000000000000000000000000..9638abc79fd445bd046048ed55841a7dd1944cfe --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/ego4d_mq/features_slowfast_trunc.py @@ -0,0 +1,77 @@ +dataset_type = "Ego4DPaddingDataset" +annotation_path = "data/ego4d/annotations/ego4d_v2_220429_feature.json" +class_map = "data/ego4d/annotations/category_idx.txt" +data_path = "data/ego4d/features/mq_slowfast/" +block_list = None + +trunc_len = 1024 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="train", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + # thumos dataloader setting + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=trunc_len, trunc_thresh=0.3, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # thumos dataloader setting + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="val", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/epic_kitchens-100/e2e_noun_train_trunc_test_sw.py b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/e2e_noun_train_trunc_test_sw.py new file mode 100644 index 0000000000000000000000000000000000000000..1d4b731a4067a39c1bcc8ff52bf9d9fabfe1ee11 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/e2e_noun_train_trunc_test_sw.py @@ -0,0 +1,104 @@ +annotation_path = "data/epic_kitchens-100/annotations/epic_kitchens_noun.json" +class_map = "data/epic_kitchens-100/annotations/category_idx_noun.txt" +data_path = "data/epic_kitchens-100/raw_data/epic_kitchens_100_30fps_512x288/" +block_list = None + +window_size = 768 + +dataset = dict( + train=dict( + type="EpicKitchensPaddingDataset", + ann_file=annotation_path, + subset_name="train", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + # epic-kitchens dataloader setting + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=8, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict( + type="LoadFrames", + num_clips=1, + method="random_trunc", + trunc_len=window_size, + trunc_thresh=0.3, + crop_ratio=[0.9, 1.0], + ), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 256)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(224, 224), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type="EpicKitchensSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # dataloader setting + window_size=window_size, + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=8, + window_overlap_ratio=0.25, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type="EpicKitchensSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # epic-kitchens dataloader setting + window_size=window_size, + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=8, + window_overlap_ratio=0.5, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="val", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/epic_kitchens-100/e2e_verb_train_trunc_test_sw.py b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/e2e_verb_train_trunc_test_sw.py new file mode 100644 index 0000000000000000000000000000000000000000..251af66890a29254fec2edc0f9c65f7cdf71c851 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/e2e_verb_train_trunc_test_sw.py @@ -0,0 +1,104 @@ +annotation_path = "data/epic_kitchens-100/annotations/epic_kitchens_verb.json" +class_map = "data/epic_kitchens-100/annotations/category_idx_verb.txt" +data_path = "data/epic_kitchens-100/raw_data/epic_kitchens_100_30fps_512x288/" +block_list = None + +window_size = 768 + +dataset = dict( + train=dict( + type="EpicKitchensPaddingDataset", + ann_file=annotation_path, + subset_name="train", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + # epic-kitchens dataloader setting + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=8, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict( + type="LoadFrames", + num_clips=1, + method="random_trunc", + trunc_len=window_size, + trunc_thresh=0.3, + crop_ratio=[0.9, 1.0], + ), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 256)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(224, 224), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type="EpicKitchensSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # dataloader setting + window_size=window_size, + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=8, + window_overlap_ratio=0.25, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type="EpicKitchensSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # epic-kitchens dataloader setting + window_size=window_size, + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=8, + window_overlap_ratio=0.5, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="val", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_noun.py b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_noun.py new file mode 100644 index 0000000000000000000000000000000000000000..210e9e13fd77447614a94dc33dd0da7b5d91745b --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_noun.py @@ -0,0 +1,80 @@ +dataset_type = "EpicKitchensPaddingDataset" +annotation_path = "data/epic_kitchens-100/annotations/epic_kitchens_noun.json" +class_map = "data/epic_kitchens-100/annotations/category_idx_noun.txt" +data_path = "data/epic_kitchens-100/features/slowfast_fps30_stride16_clip32/" +block_list = data_path + "missing_files.txt" + +trunc_len = 2304 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="train", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + # epic-kitchens dataloader setting + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=trunc_len, trunc_thresh=0.3, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # epic-kitchens dataloader setting + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # epic-kitchens dataloader setting + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="val", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_noun_train_trunc_test_sw.py b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_noun_train_trunc_test_sw.py new file mode 100644 index 0000000000000000000000000000000000000000..e9eea5f8b02b55568aba1beea20373cc0969d409 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_noun_train_trunc_test_sw.py @@ -0,0 +1,85 @@ +annotation_path = "data/epic_kitchens-100/annotations/epic_kitchens_noun.json" +class_map = "data/epic_kitchens-100/annotations/category_idx_noun.txt" +data_path = "data/epic_kitchens-100/features/slowfast_fps30_stride16_clip32/" +block_list = data_path + "missing_files.txt" + +window_size = 2304 + +dataset = dict( + train=dict( + type="EpicKitchensPaddingDataset", + ann_file=annotation_path, + subset_name="train", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + # epic-kitchens dataloader setting + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=window_size, trunc_thresh=0.3, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type="EpicKitchensSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # dataloader setting + window_size=window_size, + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + window_overlap_ratio=0.25, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type="EpicKitchensSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # epic-kitchens dataloader setting + window_size=window_size, + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + window_overlap_ratio=0.5, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="val", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_verb.py b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_verb.py new file mode 100644 index 0000000000000000000000000000000000000000..e788b400913cdd6caa2720d229f02cd733962376 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_verb.py @@ -0,0 +1,80 @@ +dataset_type = "EpicKitchensPaddingDataset" +annotation_path = "data/epic_kitchens-100/annotations/epic_kitchens_verb.json" +class_map = "data/epic_kitchens-100/annotations/category_idx_verb.txt" +data_path = "data/epic_kitchens-100/features/slowfast_fps30_stride16_clip32/" +block_list = data_path + "missing_files.txt" + +trunc_len = 2304 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="train", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + # epic-kitchens dataloader setting + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=trunc_len, trunc_thresh=0.3, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # epic-kitchens dataloader setting + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # epic-kitchens dataloader setting + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="val", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_verb_train_trunc_test_sw.py b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_verb_train_trunc_test_sw.py new file mode 100644 index 0000000000000000000000000000000000000000..515c0d4e2ed98d3850b724424971de871be62fcf --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/epic_kitchens-100/features_slowfast_verb_train_trunc_test_sw.py @@ -0,0 +1,85 @@ +annotation_path = "data/epic_kitchens-100/annotations/epic_kitchens_verb.json" +class_map = "data/epic_kitchens-100/annotations/category_idx_verb.txt" +data_path = "data/epic_kitchens-100/features/slowfast_fps30_stride16_clip32/" +block_list = data_path + "missing_files.txt" + +window_size = 2304 + +dataset = dict( + train=dict( + type="EpicKitchensPaddingDataset", + ann_file=annotation_path, + subset_name="train", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + # epic-kitchens dataloader setting + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=window_size, trunc_thresh=0.3, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type="EpicKitchensSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # dataloader setting + window_size=window_size, + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + window_overlap_ratio=0.25, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type="EpicKitchensSlidingDataset", + ann_file=annotation_path, + subset_name="val", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # epic-kitchens dataloader setting + window_size=window_size, + fps=30, + feature_stride=16, + sample_stride=1, + offset_frames=16, + window_overlap_ratio=0.5, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="val", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/fineaction/features_internvideo_pad.py b/OpenTAD/configs/_base_/datasets/fineaction/features_internvideo_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..04c7337a07535124eddea45e32ffbee715f430fd --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/fineaction/features_internvideo_pad.py @@ -0,0 +1,79 @@ +dataset_type = "AnetPaddingDataset" +annotation_path = "data/fineaction/annotations/annotations_gt.json" +class_map = "data/fineaction/annotations/category_idx.txt" +data_path = "data/fineaction/features/intervideo_mae_huge_k700_stride16_len16_fineaction/" +block_list = data_path + "missing_files.txt" + +pad_len = 2304 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + feature_stride=16, + sample_stride=1, + offset_frames=8, + fps=30, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=pad_len, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + feature_stride=16, + sample_stride=1, + offset_frames=8, + fps=30, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Padding", length=pad_len), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + feature_stride=16, + sample_stride=1, + offset_frames=8, + fps=30, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Padding", length=pad_len), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/fineaction/features_internvideo_resize_trunc.py b/OpenTAD/configs/_base_/datasets/fineaction/features_internvideo_resize_trunc.py new file mode 100644 index 0000000000000000000000000000000000000000..a2880adf726408dcb064be7b98c88d67af8e1d15 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/fineaction/features_internvideo_resize_trunc.py @@ -0,0 +1,73 @@ +dataset_type = "AnetResizeDataset" +annotation_path = "data/fineaction/annotations/annotations_gt.json" +class_map = "data/fineaction/annotations/category_idx.txt" +data_path = "data/fineaction/features/intervideo_mae_huge_k700_stride16_len16_fineaction/" +block_list = "data/fineaction/features/intervideo_mae_huge_k700_stride16_len16_fineaction/missing_files.txt" + +resize_length = 192 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="RandomTrunc", trunc_len=resize_length, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/hacs-1.1.1/features_slowfast_pad.py b/OpenTAD/configs/_base_/datasets/hacs-1.1.1/features_slowfast_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..5447f65946331b5a038339e0290b43c98964aa0e --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/hacs-1.1.1/features_slowfast_pad.py @@ -0,0 +1,79 @@ +dataset_type = "AnetPaddingDataset" +annotation_path = "data/hacs-1.1.1/annotations/HACS_segments_v1.1.1.json" +class_map = "data/hacs-1.1.1/annotations/category_idx.txt" +data_path = "data/hacs-1.1.1/features/slowfast101_15fps_stride8_len32_hacs/" +block_list = data_path + "missing_files.txt" + +pad_len = 960 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + feature_stride=8, + sample_stride=1, # 1x8=8 + offset_frames=16, + fps=15, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=pad_len, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + feature_stride=8, + sample_stride=1, # 1x8=8 + offset_frames=16, + fps=15, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Padding", length=pad_len), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + feature_stride=8, + sample_stride=1, # 1x8=8 + offset_frames=16, + fps=15, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Padding", length=pad_len), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/hacs-1.1.1/features_slowfast_resize.py b/OpenTAD/configs/_base_/datasets/hacs-1.1.1/features_slowfast_resize.py new file mode 100644 index 0000000000000000000000000000000000000000..dc795ecd15837ca49da5364c76e1ebac219a8e3b --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/hacs-1.1.1/features_slowfast_resize.py @@ -0,0 +1,73 @@ +dataset_type = "AnetResizeDataset" +annotation_path = "data/hacs-1.1.1/annotations/HACS_segments_v1.1.1.json" +class_map = "data/hacs-1.1.1/annotations/category_idx.txt" +data_path = "data/hacs-1.1.1/features/slowfast101_15fps_stride8_len32_hacs/" +block_list = data_path + "missing_files.txt" + +resize_length = 224 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + resize_length=resize_length, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/multithumos/features_i3d_pad.py b/OpenTAD/configs/_base_/datasets/multithumos/features_i3d_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..95878ec4e874354e77da14c252da29667b1a09e9 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/multithumos/features_i3d_pad.py @@ -0,0 +1,77 @@ +dataset_type = "ThumosPaddingDataset" +annotation_path = "data/multithumos/annotations/multithumos_anno.json" +class_map = "data/multithumos/annotations/category_idx.txt" +data_path = "data/thumos-14/features/i3d_actionformer_stride4_thumos/" +block_list = data_path + "missing_files.txt" + +trunc_len = 2304 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=trunc_len, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/multithumos/features_i3d_rgb_pad.py b/OpenTAD/configs/_base_/datasets/multithumos/features_i3d_rgb_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..69b3e29f4ef3d4ad94cfcdad65908ae76f2deedf --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/multithumos/features_i3d_rgb_pad.py @@ -0,0 +1,80 @@ +dataset_type = "ThumosPaddingDataset" +annotation_path = "data/multithumos/annotations/multithumos_anno.json" +class_map = "data/multithumos/annotations/category_idx.txt" +data_path = "data/thumos-14/features/i3d_actionformer_stride4_thumos/" +block_list = data_path + "missing_files.txt" + +trunc_len = 2304 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ChannelReduction", in_channels=2048, index=[0, 1024]), # only use rgb features + dict(type="RandomTrunc", trunc_len=trunc_len, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ChannelReduction", in_channels=2048, index=[0, 1024]), # only use rgb features + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="ChannelReduction", in_channels=2048, index=[0, 1024]), # only use rgb features + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/thumos-14/e2e_sw_256x224x224.py b/OpenTAD/configs/_base_/datasets/thumos-14/e2e_sw_256x224x224.py new file mode 100644 index 0000000000000000000000000000000000000000..88e0f5a8618bf65a3ced5085c9747d886f354819 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/thumos-14/e2e_sw_256x224x224.py @@ -0,0 +1,96 @@ +dataset_type = "ThumosSlidingDataset" +annotation_path = "data/thumos-14/annotations/thumos_14_anno.json" +class_map = "data/thumos-14/annotations/category_idx.txt" +data_path = "data/thumos-14/raw_data/video" +block_list = None + +window_size = 256 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.25, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 256)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(224, 224), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.25, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.5, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs"]), + dict(type="Collect", inputs="imgs", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.3, 0.4, 0.5, 0.6, 0.7], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/thumos-14/e2e_train_trunc_test_sw_256x224x224.py b/OpenTAD/configs/_base_/datasets/thumos-14/e2e_train_trunc_test_sw_256x224x224.py new file mode 100644 index 0000000000000000000000000000000000000000..5584874fe79e99bf1c6a57e908fa38af5193499d --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/thumos-14/e2e_train_trunc_test_sw_256x224x224.py @@ -0,0 +1,100 @@ +annotation_path = "data/thumos-14/annotations/thumos_14_anno.json" +class_map = "data/thumos-14/annotations/category_idx.txt" +data_path = "data/thumos-14/raw_data/video" +block_list = None + +window_size = 256 + +dataset = dict( + train=dict( + type="ThumosPaddingDataset", + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict( + type="LoadFrames", + num_clips=1, + method="random_trunc", + trunc_len=window_size, + trunc_thresh=0.5, + crop_ratio=[0.9, 1.0], + ), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 256)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(224, 224), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type="ThumosSlidingDataset", + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.25, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type="ThumosSlidingDataset", + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.5, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window"), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs"]), + dict(type="Collect", inputs="imgs", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.3, 0.4, 0.5, 0.6, 0.7], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/thumos-14/features_i3d_pad.py b/OpenTAD/configs/_base_/datasets/thumos-14/features_i3d_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..89f08f1d8bc161f16f65892a575fda44ea757530 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/thumos-14/features_i3d_pad.py @@ -0,0 +1,77 @@ +dataset_type = "ThumosPaddingDataset" +annotation_path = "data/thumos-14/annotations/thumos_14_anno.json" +class_map = "data/thumos-14/annotations/category_idx.txt" +data_path = "data/thumos-14/features/i3d_actionformer_stride4_thumos/" +block_list = data_path + "missing_files.txt" + +trunc_len = 2304 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=trunc_len, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.3, 0.4, 0.5, 0.6, 0.7], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/thumos-14/features_i3d_sw.py b/OpenTAD/configs/_base_/datasets/thumos-14/features_i3d_sw.py new file mode 100644 index 0000000000000000000000000000000000000000..15f6a989d127cf5103ca0a8c9b903ac7a8dc3d18 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/thumos-14/features_i3d_sw.py @@ -0,0 +1,85 @@ +dataset_type = "ThumosSlidingDataset" +annotation_path = "data/thumos-14/annotations/thumos_14_anno.json" +class_map = "data/thumos-14/annotations/category_idx.txt" +data_path = "data/thumos-14/features/i3d_actionformer_stride4_thumos/" +block_list = data_path + "missing_files.txt" + +window_size = 256 + +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.25, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.25, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.5, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.3, 0.4, 0.5, 0.6, 0.7], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/thumos-14/features_i3d_train_trunc_test_sw.py b/OpenTAD/configs/_base_/datasets/thumos-14/features_i3d_train_trunc_test_sw.py new file mode 100644 index 0000000000000000000000000000000000000000..5d030ffc778b2eed639c67a861f8f6bf4677e84b --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/thumos-14/features_i3d_train_trunc_test_sw.py @@ -0,0 +1,82 @@ +annotation_path = "data/thumos-14/annotations/thumos_14_anno.json" +class_map = "data/thumos-14/annotations/category_idx.txt" +data_path = "data/thumos-14/features/i3d_actionformer_stride4_thumos/" +block_list = data_path + "missing_files.txt" + +window_size = 2304 + +dataset = dict( + train=dict( + type="ThumosPaddingDataset", + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=window_size, trunc_thresh=0.75, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type="ThumosSlidingDataset", + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + window_size=window_size, + offset_frames=8, + window_overlap_ratio=0.25, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type="ThumosSlidingDataset", + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # thumos dataloader setting + feature_stride=4, + sample_stride=1, # 1x4=4 + window_size=window_size, + offset_frames=8, + window_overlap_ratio=0.5, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.3, 0.4, 0.5, 0.6, 0.7], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/datasets/thumos-14/features_tsn_sw.py b/OpenTAD/configs/_base_/datasets/thumos-14/features_tsn_sw.py new file mode 100644 index 0000000000000000000000000000000000000000..c4bfadd1dc32eddcddaf79ec8af6b77daca83f20 --- /dev/null +++ b/OpenTAD/configs/_base_/datasets/thumos-14/features_tsn_sw.py @@ -0,0 +1,81 @@ +dataset_type = "ThumosSlidingDataset" +annotation_path = "data/thumos-14/annotations/thumos_14_anno.json" +class_map = "data/thumos-14/annotations/category_idx.txt" +data_path = "data/thumos-14/features/tsn_gtad_stride1_thumos" +block_list = "data/thumos-14/features/tsn_gtad_stride1_thumos/missing_files.txt" + +window_size = 128 +dataset = dict( + train=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="training", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=1, + sample_stride=5, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.25, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + # thumos dataloader setting + feature_stride=1, + sample_stride=5, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.25, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + type=dataset_type, + ann_file=annotation_path, + subset_name="validation", + block_list=block_list, + class_map=class_map, + data_path=data_path, + filter_gt=False, + test_mode=True, + # thumos dataloader setting + feature_stride=1, + sample_stride=5, # 1x4=4 + window_size=window_size, + window_overlap_ratio=0.5, + pipeline=[ + dict(type="LoadFeats", feat_format="npy"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="SlidingWindowTrunc", with_mask=True), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +evaluation = dict( + type="mAP", + subset="validation", + tiou_thresholds=[0.3, 0.4, 0.5, 0.6, 0.7], + ground_truth_filename=annotation_path, +) diff --git a/OpenTAD/configs/_base_/models/actionformer.py b/OpenTAD/configs/_base_/models/actionformer.py new file mode 100644 index 0000000000000000000000000000000000000000..975a23cac09402d4b361205487897cb5ab80dc04 --- /dev/null +++ b/OpenTAD/configs/_base_/models/actionformer.py @@ -0,0 +1,43 @@ +model = dict( + type="ActionFormer", + projection=dict( + type="Conv1DTransformerProj", + in_channels=2048, + out_channels=512, + arch=(2, 2, 5), # layers in embed / stem / branch + conv_cfg=dict(kernel_size=3, proj_pdrop=0.0), + norm_cfg=dict(type="LN"), + attn_cfg=dict(n_head=4, n_mha_win_size=19), + path_pdrop=0.1, + use_abs_pe=False, + max_seq_len=2304, + ), + neck=dict( + type="FPNIdentity", + in_channels=512, + out_channels=512, + num_levels=6, + ), + rpn_head=dict( + type="ActionFormerHead", + num_classes=20, + in_channels=512, + feat_channels=512, + num_convs=2, + cls_prior_prob=0.01, + prior_generator=dict( + type="PointGenerator", + strides=[1, 2, 4, 8, 16, 32], + regression_range=[(0, 4), (4, 8), (8, 16), (16, 32), (32, 64), (64, 10000)], + ), + loss_normalizer=100, + loss_normalizer_momentum=0.9, + center_sample="radius", + center_sample_radius=1.5, + label_smoothing=0.0, + loss=dict( + cls_loss=dict(type="FocalLoss"), + reg_loss=dict(type="DIOULoss"), + ), + ), +) diff --git a/OpenTAD/configs/_base_/models/afsd.py b/OpenTAD/configs/_base_/models/afsd.py new file mode 100644 index 0000000000000000000000000000000000000000..f467548307b66c443da08635d229e3cc8856c766 --- /dev/null +++ b/OpenTAD/configs/_base_/models/afsd.py @@ -0,0 +1,30 @@ +model = dict( + type="AFSD", + neck=dict( + type="AFSDNeck", + in_channels=2048, + out_channels=512, + frame_num=768, # 96*8 + layer_num=6, + ), + rpn_head=dict( + type="AFSDCoarseHead", + in_channels=512, + out_channels=512, + frame_num=768, # 96*8 + fpn_strides=[4, 8, 16, 32, 64, 128], + num_classes=2, + layer_num=6, + feat_t=768 // 8, + ), + roi_head=dict( + type="AFSDRefineHead", + in_channels=512, + num_classes=2, + # for loss + overlap_thresh=0.6, + loc_weight=1.0, + loc_bounded=True, + use_smooth_l1=True, + ), +) diff --git a/OpenTAD/configs/_base_/models/bmn.py b/OpenTAD/configs/_base_/models/bmn.py new file mode 100644 index 0000000000000000000000000000000000000000..875010b9a7513ce68446209337b1c00e81d00fa4 --- /dev/null +++ b/OpenTAD/configs/_base_/models/bmn.py @@ -0,0 +1,41 @@ +model = dict( + type="BMN", + projection=dict( + type="ConvSingleProj", + in_channels=400, + out_channels=256, + num_convs=2, + conv_cfg=dict(groups=4), + ), + rpn_head=dict( + type="TemporalEvaluationHead", # tem + in_channels=256, + num_classes=2, + conv_cfg=dict(groups=4), + loss=dict(pos_thresh=0.5, gt_type=["startness", "endness"]), + ), + roi_head=dict( + type="StandardProposalMapHead", + proposal_generator=dict(type="DenseProposalMap", tscale=128, dscale=128), + proposal_roi_extractor=dict( + type="BMNExtractor", + in_channels=256, + roi_channels=512, + out_channels=128, + tscale=128, + dscale=128, + prop_extend_ratio=0.5, + ), + proposal_head=dict( + type="PEMHead", # FC_head + in_channels=128, + feat_channels=128, + num_convs=2, + num_classes=2, + loss=dict( + cls_loss=dict(type="BalancedBCELoss", pos_thresh=0.9), + reg_loss=dict(type="BalancedL2Loss", high_thresh=0.7, low_thresh=0.3, weight=5.0), + ), + ), + ), +) diff --git a/OpenTAD/configs/_base_/models/etad.py b/OpenTAD/configs/_base_/models/etad.py new file mode 100644 index 0000000000000000000000000000000000000000..1bfbc35f3fdd837933fe36d2a44730baa09d2ed4 --- /dev/null +++ b/OpenTAD/configs/_base_/models/etad.py @@ -0,0 +1,60 @@ +model = dict( + type="ETAD", + projection=dict( + type="ConvSingleProj", + in_channels=400, + out_channels=256, + num_convs=1, + conv_cfg=dict(groups=4), + norm_cfg=dict(type="GN", num_groups=16), + ), + neck=dict( + type="LSTMNeck", + in_channels=256, + out_channels=256, + conv_cfg=dict(groups=4), + norm_cfg=dict(type="GN", num_groups=16), + ), + rpn_head=dict( + type="TemporalEvaluationHead", # tem + in_channels=256, + num_classes=2, + shared=True, + conv_cfg=dict(groups=4), + loss=dict(pos_thresh=0.5, gt_type=["startness", "endness"]), + ), + roi_head=dict( + type="ETADRoIHead", + stages=dict( + number=3, + loss_weight=[1, 1, 1], + pos_iou_thresh=[0.7, 0.8, 0.9], + ), + proposal_generator=dict( + type="ProposalMapSampling", + tscale=128, + dscale=128, + sampling_ratio=0.06, + strategy="random", + ), + proposal_roi_extractor=dict( + type="ROIAlignExtractor", + roi_size=16, + extend_ratio=0.5, + base_stride=1, + ), + proposal_head=dict( + type="ETADHead", + in_channels=256, + roi_size=16, + feat_channels=512, + fcs_num=3, + fcs_channels=128, + loss=dict( + cls_weight=1.0, + reg_weight=5.0, + boundary_weight=10.0, + ), + ), + ), +) diff --git a/OpenTAD/configs/_base_/models/gtad.py b/OpenTAD/configs/_base_/models/gtad.py new file mode 100644 index 0000000000000000000000000000000000000000..753c39cc77a4e174bdfcf5a0efb44270fbffd86f --- /dev/null +++ b/OpenTAD/configs/_base_/models/gtad.py @@ -0,0 +1,46 @@ +model = dict( + type="GTAD", + projection=dict( + type="ConvSingleProj", + num_convs=1, + in_channels=400, + out_channels=256, + conv_cfg=dict(groups=4), + ), + neck=dict( + type="GCNeXt", + in_channels=256, + out_channels=256, + k=3, + groups=32, + ), + rpn_head=dict( + type="GCNextTemporalEvaluationHead", + in_channels=256, + num_classes=2, + loss=dict(pos_thresh=0.5, gt_type=["startness", "endness"]), + ), + roi_head=dict( + type="StandardProposalMapHead", + proposal_generator=dict(type="DenseProposalMap", tscale=100, dscale=100), + proposal_roi_extractor=dict( + type="GTADExtractor", + in_channels=256, + out_channels=512, + tscale=100, + dscale=100, + ), + proposal_head=dict( + type="PEMHead", # FC_head + in_channels=512, + feat_channels=128, + num_convs=3, + num_classes=2, + kernel_size=1, + loss=dict( + cls_loss=dict(type="BalancedBCELoss", pos_thresh=0.9), + reg_loss=dict(type="BalancedL2Loss", high_thresh=0.7, low_thresh=0.3, weight=5.0), + ), + ), + ), +) diff --git a/OpenTAD/configs/_base_/models/tadtr.py b/OpenTAD/configs/_base_/models/tadtr.py new file mode 100644 index 0000000000000000000000000000000000000000..b2286b1171718b38fd83c91fe55aeb407bbba7c4 --- /dev/null +++ b/OpenTAD/configs/_base_/models/tadtr.py @@ -0,0 +1,73 @@ +model = dict( + type="TadTR", # Done + projection=dict( + type="ConvSingleProj", + in_channels=2048, + out_channels=256, + num_convs=1, + conv_cfg=dict(kernel_size=1, padding=0), + norm_cfg=dict(type="GN", num_groups=32), + act_cfg=None, + ), + transformer=dict( + type="TadTRTransformer", + num_proposals=40, + num_classes=20, + with_act_reg=True, + roi_size=16, + roi_extend_ratio=0.25, + aux_loss=True, + position_embedding=dict( + type="PositionEmbeddingSine", + num_pos_feats=256, + temperature=10000, + offset=-0.5, + normalize=True, + ), + encoder=dict( + type="DeformableDETREncoder", + embed_dim=256, + num_heads=8, + num_points=4, + attn_dropout=0.1, + ffn_dim=1024, + ffn_dropout=0.1, + num_layers=4, + num_feature_levels=1, + post_norm=False, + ), + decoder=dict( + type="DeformableDETRDecoder", + embed_dim=256, + num_heads=8, + num_points=4, + attn_dropout=0.1, + ffn_dim=1024, + ffn_dropout=0.1, + num_layers=4, + num_feature_levels=1, + return_intermediate=True, + ), + loss=dict( + type="TadTRSetCriterion", + num_classes=20, + matcher=dict( + type="HungarianMatcher", + cost_class=6.0, + cost_bbox=5.0, + cost_giou=2.0, + cost_class_type="focal_loss_cost", # ce_cost, focal_loss_cost + iou_type="iou", + use_multi_class=False, + ), + loss_class_type="focal_loss", # ce_loss, focal_loss + weight_dict=dict( + loss_class=2.0, + loss_bbox=5.0, + loss_iou=2.0, + loss_actionness=4.0, + ), + use_multi_class=False, + ), + ), +) diff --git a/OpenTAD/configs/_base_/models/temporalmaxer.py b/OpenTAD/configs/_base_/models/temporalmaxer.py new file mode 100644 index 0000000000000000000000000000000000000000..40fd5043c0064083209d21b5894d9a3eb3ed348c --- /dev/null +++ b/OpenTAD/configs/_base_/models/temporalmaxer.py @@ -0,0 +1,44 @@ +model = dict( + type="TemporalMaxer", + projection=dict( + type="TemporalMaxerProj", + in_channels=2048, + out_channels=512, + arch=(2, 0, 5), # feature projection layers, downsampling layer + conv_cfg=dict(kernel_size=3), + norm_cfg=dict(type="LN"), + ), + neck=dict( + type="FPNIdentity", + in_channels=512, + out_channels=512, + num_levels=6, + ), + rpn_head=dict( + type="TemporalMaxerHead", + num_classes=20, + in_channels=512, + feat_channels=512, + num_convs=2, + cls_prior_prob=0.01, + prior_generator=dict( + type="PointGenerator", + strides=[1, 2, 4, 8, 16, 32], + regression_range=[(0, 4), (4, 8), (8, 16), (16, 32), (32, 64), (64, 10000)], + ), + loss_normalizer=100, + loss_normalizer_momentum=0.9, + loss=dict( + cls_loss=dict(type="FocalLoss"), + reg_loss=dict(type="DIOULoss"), + ), + assigner=dict( + type="AnchorFreeSimOTAAssigner", + iou_weight=2, + cls_weight=1.0, + center_radius=1.5, + keep_percent=1.0, + confuse_weight=0.0, + ), + ), +) diff --git a/OpenTAD/configs/_base_/models/tridet.py b/OpenTAD/configs/_base_/models/tridet.py new file mode 100644 index 0000000000000000000000000000000000000000..0f85fbd94a60ff6e76218055f003ce7eed13f5d4 --- /dev/null +++ b/OpenTAD/configs/_base_/models/tridet.py @@ -0,0 +1,52 @@ +model = dict( + type="TriDet", + projection=dict( + type="TriDetProj", + in_channels=2048, + out_channels=512, + sgp_mlp_dim=768, + arch=(2, 2, 5), # layers in embed / stem / branch + downsample_type="max", + sgp_win_size=[1, 1, 1, 1, 1, 1], + k=5, + init_conv_vars=0, + conv_cfg=dict(kernel_size=3), + norm_cfg=dict(type="LN"), + path_pdrop=0.1, + use_abs_pe=False, + max_seq_len=2304, + input_noise=0.0, + ), + neck=dict( + type="FPNIdentity", + in_channels=512, + out_channels=512, + num_levels=6, + ), + rpn_head=dict( + type="TriDetHead", + num_classes=20, + in_channels=512, + feat_channels=512, + num_convs=2, + cls_prior_prob=0.01, + prior_generator=dict( + type="PointGenerator", + strides=[1, 2, 4, 8, 16, 32], + regression_range=[(0, 4), (4, 8), (8, 16), (16, 32), (32, 64), (64, 10000)], + ), + loss_normalizer=100, + loss_normalizer_momentum=0.9, + center_sample="radius", + center_sample_radius=1.5, + label_smoothing=0.0, + boundary_kernel_size=3, + iou_weight_power=0.2, + num_bins=16, + loss=dict( + cls_loss=dict(type="FocalLoss"), + reg_loss=dict(type="DIOULoss"), + iou_rate=dict(type="GIOULoss"), + ), + ), +) diff --git a/OpenTAD/configs/_base_/models/tsi.py b/OpenTAD/configs/_base_/models/tsi.py new file mode 100644 index 0000000000000000000000000000000000000000..dd05a9f8b963d719f4d1aab9915331257bd30dd1 --- /dev/null +++ b/OpenTAD/configs/_base_/models/tsi.py @@ -0,0 +1,39 @@ +model = dict( + type="TSI", + projection=dict( + type="ConvSingleProj", + in_channels=400, + out_channels=256, + num_convs=2, + conv_cfg=dict(groups=4), + ), + rpn_head=dict( + type="LocalGlobalTemporalEvaluationHead", + in_channels=256, + loss=dict(pos_thresh=0.5), + ), + roi_head=dict( + type="StandardProposalMapHead", + proposal_generator=dict(type="DenseProposalMap", tscale=128, dscale=128), + proposal_roi_extractor=dict( + type="BMNExtractor", + in_channels=256, + roi_channels=512, + out_channels=128, + tscale=128, + dscale=128, + prop_extend_ratio=0.5, + ), + proposal_head=dict( + type="TSIHead", # modified on PEMHead + in_channels=128, + feat_channels=128, + num_convs=2, + num_classes=2, + loss=dict( + cls_loss=dict(type="ScaleInvariantLoss", pos_thresh=0.9), + reg_loss=dict(type="BalancedL2Loss", high_thresh=0.7, low_thresh=0.3, weight=5.0), + ), + ), + ), +) diff --git a/OpenTAD/configs/_base_/models/videomambasuite.py b/OpenTAD/configs/_base_/models/videomambasuite.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef519cb246b3250323cf3030467a4106e8e4e89 --- /dev/null +++ b/OpenTAD/configs/_base_/models/videomambasuite.py @@ -0,0 +1,42 @@ +model = dict( + type="VideoMambaSuite", + projection=dict( + type="MambaProj", + in_channels=2048, + out_channels=512, + arch=(2, 2, 5), # layers in embed / stem / branch + conv_cfg=dict(kernel_size=3), + norm_cfg=dict(type="LN"), + use_abs_pe=False, + max_seq_len=2304, + mamba_cfg=dict(kernel_size=4, drop_path_rate=0.3, use_mamba_type="dbm"), + ), + neck=dict( + type="FPNIdentity", + in_channels=512, + out_channels=512, + num_levels=6, + ), + rpn_head=dict( + type="ActionFormerHead", + num_classes=20, + in_channels=512, + feat_channels=512, + num_convs=2, + cls_prior_prob=0.01, + prior_generator=dict( + type="PointGenerator", + strides=[1, 2, 4, 8, 16, 32], + regression_range=[(0, 4), (4, 8), (8, 16), (16, 32), (32, 64), (64, 10000)], + ), + loss_normalizer=100, + loss_normalizer_momentum=0.9, + center_sample="radius", + center_sample_radius=1.5, + label_smoothing=0.0, + loss=dict( + cls_loss=dict(type="FocalLoss"), + reg_loss=dict(type="DIOULoss"), + ), + ), +) diff --git a/OpenTAD/configs/_base_/models/vsgn.py b/OpenTAD/configs/_base_/models/vsgn.py new file mode 100644 index 0000000000000000000000000000000000000000..0e403f472fa04b27ac89a8a9b0a4c478afaa2c45 --- /dev/null +++ b/OpenTAD/configs/_base_/models/vsgn.py @@ -0,0 +1,43 @@ +tscale = 256 +model = dict( + type="VSGN", + projection=dict( + type="VSGNPyramidProj", + in_channels=2048, + out_channels=256, + pyramid_levels=[2, 4, 8, 16, 32], + ), + neck=dict( + type="VSGNFPN", + in_channels=256, + out_channels=256, + num_levels=5, + ), + rpn_head=dict( + type="VSGNRPNHead", + in_channels=256, + num_layers=4, + num_classes=1, + iou_thr=0.6, + anchor_generator=dict( + pyramid_levels=[2, 4, 8, 16, 32], + tscale=tscale, + anchor_scale=[7, 7.5], + ), + tem_head=dict( + type="TemporalEvaluationHead", + in_channels=256, + num_classes=3, + loss=dict(pos_thresh=0.5, gt_type=["startness", "endness", "actionness"]), + ), + loss_cls=dict(type="BalancedCEloss"), # CE for THUMOS, Sigmoid for ANET + loss_loc=dict(type="GIoULoss"), # this is only a placeholder + ), + roi_head=dict( + type="VSGNRoIHead", + in_channels=256, + iou_thr=0.7, + roi_extractor=dict(type="CornerExtractor", beta=8.0, base_stride=2, tscale=tscale), + loss_loc=dict(type="GIoULoss"), # this is only a placeholder + ), +) diff --git a/OpenTAD/configs/actionformer/README.md b/OpenTAD/configs/actionformer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0fa1ada60f1078ca3b79f46ceba3493cfa1b4cca --- /dev/null +++ b/OpenTAD/configs/actionformer/README.md @@ -0,0 +1,104 @@ +# ActionFormer + +> [ActionFormer: Localizing Moments of Actions with Transformers](https://arxiv.org/abs/2202.07925) +> Chen-Lin Zhang, Jianxin Wu, Yin Li + + + +## Abstract + +Self-attention based Transformer models have demonstrated impressive results for image classification and object detection, and more recently for video understanding. Inspired by this success, we investigate the application of Transformer networks for temporal action localization in videos. To this end, we present ActionFormer -- a simple yet powerful model to identify actions in time and recognize their categories in a single shot, without using action proposals or relying on pre-defined anchor windows. ActionFormer combines a multiscale feature representation with local self-attention, and uses a light-weighted decoder to classify every moment in time and estimate the corresponding action boundaries. We show that this orchestrated design results in major improvements upon prior works. Without bells and whistles, ActionFormer achieves 71.0% mAP at tIoU=0.5 on THUMOS14, outperforming the best prior model by 14.1 absolute percentage points. Further, ActionFormer demonstrates strong results on ActivityNet 1.3 (36.6% average mAP) and EPIC-Kitchens 100 (+13.5% average mAP over prior works). + +## Results and Models + +**ActivityNet-1.3** with CUHK classifier. + +| Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :------: | :-----: | :------: | :------: | :------: | :-------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| TSP | 55.08 | 38.27 | 8.91 | 37.07 | [config](anet_tsp.py) | [model](https://drive.google.com/file/d/1loC72F4U79jWfoRL9SB2rdk3xykBKqHN/view?usp=sharing) \| [log](https://drive.google.com/file/d/1YveGerbI1es51t2Ii7WZDgPlJy3lGBLf/view?usp=sharing) | + +**THUMOS-14** + +| Features | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :---------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| I3D | 83.78 | 80.06 | 73.16 | 60.46 | 44.72 | 68.44 | [config](thumos_i3d.py) | [model](https://drive.google.com/file/d/17oP-fMOjw6wwnaQWTlikWwoZoSkiIFkt/view?usp=sharing) \| [log](https://drive.google.com/file/d/1WJe98mKoXaP2X9Th-gKC8rw0JeKxfJkq/view?usp=sharing) | + +**HACS** + +| Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :------: | :-----: | :------: | :------: | :------: | :------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| SlowFast | 56.18 | 37.97 | 11.05 | 37.71 | [config](hacs_slowfast.py) | [model](https://drive.google.com/file/d/1IdxR5lyfXzk5wjl-8YDcH0Nw2BEDwzWz/view?usp=sharing) \| [log](https://drive.google.com/file/d/1Eu2O9IKuR8XLeZ37OxCq7NjSUKPE-3Zw/view?usp=sharing) | + +**Epic-Kitchens-100** + +| Subset | Features | mAP@0.1 | mAP@0.2 | mAP@0.3 | mAP@0.4 | mAP@0.5 | ave. mAP | Config | Download | +| :----: | :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :--------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| Noun | SlowFast | 25.78 | 24.73 | 22.83 | 20.84 | 17.45 | 22.33 | [config](epic_kitchens_slowfast_noun.py) | [model](https://drive.google.com/file/d/1RckzXf5W8oD_ARZw5dyYo03ZKVrU1n9-/view?usp=sharing) \| [log](https://drive.google.com/file/d/18dVA27hWRBjM8lp4S12DscCkNJBqFrWp/view?usp=sharing) | +| Verb | SlowFast | 27.68 | 26.79 | 25.62 | 24.06 | 20.48 | 24.93 | [config](epic_kitchens_slowfast_verb.py) | [model](https://drive.google.com/file/d/1-RLtnku727Fh39rihyGVxLCU5klTIvbn/view?usp=sharing) \| [log](https://drive.google.com/file/d/1w18Ccyi22ZHgM0ECx6rAKOXqFoO9L0Iq/view?usp=sharing) | + + +**MultiTHUMOS** + +| Features | mAP@0.2 | mAP@0.5 | mAP@0.7 | ave. mAP (0.1:0.9:0.1) | Config | Download | +| :------------: | :-----: | :-----: | :-----: | :--------------------: | :------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| I3D (rgb) | 53.50 | 39.04 | 19.69 | 34.01 | [config](multithumos_i3d_rgb.py) | [model](https://drive.google.com/file/d/1ufrZRt9uVu6_IJXPa-JdRK05vsc0UQXO/view?usp=sharing) \| [log](https://drive.google.com/file/d/1PGrIRfWOHPIofDdSNRQX4UglzBWvlVhO/view?usp=sharing) | +| I3D (rgb+flow) | 60.16 | 44.99 | 24.55 | 39.18 | [config](multithumos_i3d.py) | [model](https://drive.google.com/file/d/1rBOoxuUR3tlzyQmWZGUtPXmsKUT7yLFm/view?usp=sharing) \| [log](https://drive.google.com/file/d/1-h_9g0HppsqnrvirVNoiZSTTuSWmmRxC/view?usp=sharing) | + +**Charades** + +| Features | mAP@0.2 | mAP@0.5 | mAP@0.7 | ave. mAP (0.1:0.9:0.1) | Config | Download | +| :-------: | :-----: | :-----: | :-----: | :--------------------: | :---------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| I3D (rgb) | 29.42 | 21.76 | 12.78 | 19.39 | [config](charades_i3d_rgb.py) | [model](https://drive.google.com/file/d/1EFCNke077m4JC_6OMJZXEnaKW2UAgFpA/view?usp=sharing) \| [log](https://drive.google.com/file/d/1CuwGJ9m2YtvnKHsq9slkgtANoNEmbqVP/view?usp=sharing) | + +**FineAction** with InternVideo classifier + +| Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :---------------: | :-----: | :------: | :------: | :------: | :----------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| VideoMAE_H_K700 | 29.44 | 19.46 | 5.06 | 19.32 | [config](fineaction_videomae_h.py) | [model](https://drive.google.com/file/d/1uNQufJMf9U6Igv6w4J70xiEVqYUKteTE/view?usp=sharing) \| [log](https://drive.google.com/file/d/1VAQbtZuvRiTk8oFS7EIF9ilOKm1165u-/view?usp=sharing) | +| VideoMAEv2_g_K710 | 29.85 | 19.72 | 5.17 | 19.62 | [config](fineaction_videomaev2_g.py) | [model](https://drive.google.com/file/d/1o7HdsZIR-JufAGHD6cq-xRRIEX3IMlyY/view?usp=sharing) \| [log](https://drive.google.com/file/d/1QenPC5OV9gI62wKkgbrdYyJpLSxP5awp/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train ActionFormer on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/actionformer/anet_tsp.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test ActionFormer on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/actionformer/anet_tsp.py --checkpoint exps/anet/actionformer_tsp/gpu1_id0/checkpoint/epoch_14.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + +## Citation + +```latex +@inproceedings{zhang2022actionformer, + title={Actionformer: Localizing moments of actions with transformers}, + author={Zhang, Chen-Lin and Wu, Jianxin and Li, Yin}, + booktitle={Computer Vision--ECCV 2022: 17th European Conference, Tel Aviv, Israel, October 23--27, 2022, Proceedings, Part IV}, + pages={492--510}, + year={2022}, + organization={Springer} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/actionformer/anet_tsp.py b/OpenTAD/configs/actionformer/anet_tsp.py new file mode 100644 index 0000000000000000000000000000000000000000..97ff4aebac0a3a53449c55ff37c78de65d0c7248 --- /dev/null +++ b/OpenTAD/configs/actionformer/anet_tsp.py @@ -0,0 +1,64 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize_trunc.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +model = dict( + projection=dict( + in_channels=512, + out_channels=256, + attn_cfg=dict(n_mha_win_size=[7, 7, 7, 7, 7, -1]), + use_abs_pe=True, + max_seq_len=192, + input_pdrop=0.2, + ), + neck=dict(in_channels=256, out_channels=256), + rpn_head=dict( + in_channels=256, + feat_channels=256, + num_classes=1, + label_smoothing=0.1, + loss_weight=2.0, + loss_normalizer=200, + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=15) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.75, + max_seg_num=100, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=False, + voting_thresh=0.9, # set 0 to disable + ), + #external_cls=dict( + # type="CUHKANETClassifier", + # path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + # topk=2, + #), + save_dict=True, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=7, +) + +work_dir = "exps/anet/actionformer_tsp" diff --git a/OpenTAD/configs/actionformer/charades_i3d_rgb.py b/OpenTAD/configs/actionformer/charades_i3d_rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..e98be044316d247a02fa40089ef476664e12711c --- /dev/null +++ b/OpenTAD/configs/actionformer/charades_i3d_rgb.py @@ -0,0 +1,46 @@ +_base_ = [ + "../_base_/datasets/charades/features_i3d_pad.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +model = dict( + projection=dict(in_channels=1024), + rpn_head=dict(num_classes=157), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=15) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=8000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=8000, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=5, + end_epoch=10, +) + +work_dir = "exps/charades/actionformer_i3d_rgb" diff --git a/OpenTAD/configs/actionformer/ego4d_egovlp.py b/OpenTAD/configs/actionformer/ego4d_egovlp.py new file mode 100644 index 0000000000000000000000000000000000000000..b96174cc332e659a3f77a205bee8af40d0f2d1cc --- /dev/null +++ b/OpenTAD/configs/actionformer/ego4d_egovlp.py @@ -0,0 +1,16 @@ +_base_ = ["ego4d_slowfast.py"] + +data_path = "data/ego4d/features/mq_egovlp/" +dataset = dict( + train=dict(data_path=data_path, offset_frames=8), + val=dict(data_path=data_path, offset_frames=8), + test=dict(data_path=data_path, offset_frames=8), +) + +model = dict( + projection=dict(in_channels=256, out_channels=384), + neck=dict(in_channels=384, out_channels=384), + rpn_head=dict(in_channels=384, feat_channels=384), +) + +work_dir = "exps/ego4d/actionformer_egovlp" diff --git a/OpenTAD/configs/actionformer/ego4d_internvideo.py b/OpenTAD/configs/actionformer/ego4d_internvideo.py new file mode 100644 index 0000000000000000000000000000000000000000..1a975e9066f92980349f87612afe44321c704130 --- /dev/null +++ b/OpenTAD/configs/actionformer/ego4d_internvideo.py @@ -0,0 +1,5 @@ +_base_ = ["ego4d_slowfast.py"] + +model = dict(projection=dict(in_channels=1024)) + +work_dir = "exps/ego4d/actionformer_internvideo" diff --git a/OpenTAD/configs/actionformer/ego4d_slowfast.py b/OpenTAD/configs/actionformer/ego4d_slowfast.py new file mode 100644 index 0000000000000000000000000000000000000000..2582dac64f25d9a36886e3de66ed3ce23a1d50b3 --- /dev/null +++ b/OpenTAD/configs/actionformer/ego4d_slowfast.py @@ -0,0 +1,58 @@ +_base_ = [ + "../_base_/models/actionformer.py", # model config + "../_base_/datasets/ego4d_mq/features_slowfast_trunc.py", # dataset config +] + +model = dict( + projection=dict( + in_channels=2304, + arch=(2, 2, 7), + use_abs_pe=True, + max_seq_len=1024, + conv_cfg=dict(proj_pdrop=0.1), + attn_cfg=dict(n_mha_win_size=9), + ), + neck=dict(type="FPNIdentity", num_levels=8), + rpn_head=dict( + num_classes=110, + prior_generator=dict( + strides=[1, 2, 4, 8, 16, 32, 64, 128], + regression_range=[(0, 4), (2, 8), (4, 16), (8, 32), (16, 64), (32, 128), (64, 256), (128, 10000)], + ), + ), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=15) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=5000, + nms=dict( + use_soft_nms=True, + sigma=0.9, + max_seg_num=2000, + min_score=0.001, + multiclass=True, + voting_thresh=0.95, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=8, +) + +work_dir = "exps/ego4d/actionformer_slowfast" diff --git a/OpenTAD/configs/actionformer/epic_kitchens_slowfast_noun.py b/OpenTAD/configs/actionformer/epic_kitchens_slowfast_noun.py new file mode 100644 index 0000000000000000000000000000000000000000..50eb9d039dc6f3e3895faf86af6e9d0f4da85661 --- /dev/null +++ b/OpenTAD/configs/actionformer/epic_kitchens_slowfast_noun.py @@ -0,0 +1,56 @@ +_base_ = [ + "../_base_/datasets/epic_kitchens-100/features_slowfast_noun.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +model = dict( + projection=dict( + in_channels=2304, + attn_cfg=dict(n_mha_win_size=9), + ), + rpn_head=dict( + num_classes=293, # total 300, but 7 classes are empty + prior_generator=dict( + strides=[1, 2, 4, 8, 16, 32], + regression_range=[(0, 4), (2, 8), (4, 16), (8, 32), (16, 64), (32, 10000)], + ), + label_smoothing=0.1, + loss_normalizer=250, + ), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=20) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=5000, + nms=dict( + use_soft_nms=True, + sigma=0.4, + max_seg_num=2000, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=True, + voting_thresh=0.75, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=15, +) + +work_dir = "exps/epic_kitchens/actionformer_slowfast_noun" diff --git a/OpenTAD/configs/actionformer/epic_kitchens_slowfast_verb.py b/OpenTAD/configs/actionformer/epic_kitchens_slowfast_verb.py new file mode 100644 index 0000000000000000000000000000000000000000..0f108c9036da5d7db0290bd20a40df146c647eb4 --- /dev/null +++ b/OpenTAD/configs/actionformer/epic_kitchens_slowfast_verb.py @@ -0,0 +1,55 @@ +_base_ = [ + "../_base_/datasets/epic_kitchens-100/features_slowfast_verb.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +model = dict( + projection=dict( + in_channels=2304, + attn_cfg=dict(n_mha_win_size=9), + ), + rpn_head=dict( + num_classes=97, + prior_generator=dict( + strides=[1, 2, 4, 8, 16, 32], + regression_range=[(0, 4), (2, 8), (4, 16), (8, 32), (16, 64), (32, 10000)], + ), + loss_normalizer=250, + ), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=20) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=5000, + nms=dict( + use_soft_nms=True, + sigma=0.4, + max_seg_num=2000, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=True, + voting_thresh=0.75, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=15, +) + +work_dir = "exps/epic_kitchens/actionformer_slowfast_verb" diff --git a/OpenTAD/configs/actionformer/fineaction_videomae_h.py b/OpenTAD/configs/actionformer/fineaction_videomae_h.py new file mode 100644 index 0000000000000000000000000000000000000000..eaa06bc0c4695e0a0fe29ffcbbbef2c1c887b74e --- /dev/null +++ b/OpenTAD/configs/actionformer/fineaction_videomae_h.py @@ -0,0 +1,63 @@ +_base_ = [ + "../_base_/datasets/fineaction/features_internvideo_resize_trunc.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +model = dict( + projection=dict( + in_channels=1280, + out_channels=256, + attn_cfg=dict(n_mha_win_size=[7, 7, 7, 7, 7, -1]), + use_abs_pe=True, + max_seq_len=192, + ), + neck=dict(in_channels=256, out_channels=256), + rpn_head=dict( + in_channels=256, + feat_channels=256, + num_classes=1, + label_smoothing=0.1, + loss_weight=2.0, + loss_normalizer=200, + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=20) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.75, + max_seg_num=100, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=False, + voting_thresh=0.9, # set 0 to disable + ), + external_cls=dict( + type="StandardClassifier", + path="./data/fineaction/classifiers/new_swinB_1x1x256_views2x3_max_label_avg_prob.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=10, +) + +work_dir = "exps/fineaction/actionformer_videomae_h" diff --git a/OpenTAD/configs/actionformer/fineaction_videomaev2_g.py b/OpenTAD/configs/actionformer/fineaction_videomaev2_g.py new file mode 100644 index 0000000000000000000000000000000000000000..926c1034bd3ef313dff776b9ad6e82398b95c611 --- /dev/null +++ b/OpenTAD/configs/actionformer/fineaction_videomaev2_g.py @@ -0,0 +1,71 @@ +_base_ = [ + "../_base_/datasets/fineaction/features_internvideo_resize_trunc.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +data_path = "data/fineaction/features/fineaction_mae_g/" +block_list = data_path + "missing_files.txt" +dataset = dict( + train=dict(data_path=data_path, block_list=block_list), + val=dict(data_path=data_path, block_list=block_list), + test=dict(data_path=data_path, block_list=block_list), +) + +model = dict( + projection=dict( + in_channels=1408, + out_channels=256, + attn_cfg=dict(n_mha_win_size=[7, 7, 7, 7, 7, -1]), + use_abs_pe=True, + max_seq_len=192, + ), + neck=dict(in_channels=256, out_channels=256), + rpn_head=dict( + in_channels=256, + feat_channels=256, + num_classes=1, + label_smoothing=0.1, + loss_weight=2.0, + loss_normalizer=200, + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=15) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.75, + max_seg_num=100, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=False, + voting_thresh=0.9, # set 0 to disable + ), + external_cls=dict( + type="StandardClassifier", + path="./data/fineaction/classifiers/new_swinB_1x1x256_views2x3_max_label_avg_prob.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=7, +) + +work_dir = "exps/fineaction/actionformer_videomaev2_g" diff --git a/OpenTAD/configs/actionformer/hacs_slowfast.py b/OpenTAD/configs/actionformer/hacs_slowfast.py new file mode 100644 index 0000000000000000000000000000000000000000..1d139a6865f6ff653fc14e08d0870c3d3927d3d2 --- /dev/null +++ b/OpenTAD/configs/actionformer/hacs_slowfast.py @@ -0,0 +1,67 @@ +_base_ = [ + "../_base_/datasets/hacs-1.1.1/features_slowfast_pad.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +dataset = dict( + train=dict(class_agnostic=True), + val=dict(class_agnostic=True), + test=dict(class_agnostic=True), +) + +model = dict( + projection=dict( + in_channels=2304, + out_channels=256, + attn_cfg=dict(n_mha_win_size=[13, 13, 13, 13, 13, -1]), + max_seq_len=960, + use_abs_pe=True, + input_pdrop=0.1, + ), + neck=dict(in_channels=256, out_channels=256), + rpn_head=dict( + in_channels=256, + feat_channels=256, + num_classes=1, + label_smoothing=0.1, + loss_normalizer=400, + ), +) +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1.0, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=0.03, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=15) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.75, + max_seg_num=100, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + external_cls=dict( + type="TCANetHACSClassifier", + path="data/hacs-1.1.1/classifiers/validation94.32.json", + topk=3, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=8, +) + +work_dir = "exps/hacs/actionformer_slowfast" diff --git a/OpenTAD/configs/actionformer/multithumos_i3d.py b/OpenTAD/configs/actionformer/multithumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..478075046abfe0729b364bed7a2ae32b5331fc07 --- /dev/null +++ b/OpenTAD/configs/actionformer/multithumos_i3d.py @@ -0,0 +1,46 @@ +_base_ = [ + "../_base_/datasets/multithumos/features_i3d_pad.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +model = dict( + projection=dict(in_channels=2048, arch=(3, 0, 5)), + rpn_head=dict(num_classes=65), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=65) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=8000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=8000, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=20, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=35, + end_epoch=45, +) + +work_dir = "exps/multithumos/actionformer_i3d" diff --git a/OpenTAD/configs/actionformer/multithumos_i3d_rgb.py b/OpenTAD/configs/actionformer/multithumos_i3d_rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..fd68016c2dc55fafe745254d9ef0747855f7da1c --- /dev/null +++ b/OpenTAD/configs/actionformer/multithumos_i3d_rgb.py @@ -0,0 +1,46 @@ +_base_ = [ + "../_base_/datasets/multithumos/features_i3d_rgb_pad.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +model = dict( + projection=dict(in_channels=1024, arch=(3, 0, 5)), + rpn_head=dict(num_classes=65), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=65) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=8000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=8000, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=20, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=35, + end_epoch=45, +) + +work_dir = "exps/multithumos/actionformer_i3d_rgb" diff --git a/OpenTAD/configs/actionformer/thumos_i3d.py b/OpenTAD/configs/actionformer/thumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..cb394d0060b4e6f69e22eb9e344a3e1c791ac8ec --- /dev/null +++ b/OpenTAD/configs/actionformer/thumos_i3d.py @@ -0,0 +1,41 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_i3d_pad.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +model = dict(projection=dict(in_channels=2048, input_pdrop=0.2)) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=35) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=2000, + iou_threshold=0.1, # does not matter when use soft nms + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=20, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=30, +) + +work_dir = "exps/thumos/actionformer_i3d" diff --git a/OpenTAD/configs/adatad/README.md b/OpenTAD/configs/adatad/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e355cddc7f9c56d88a774fc75b6c10fbe3f78497 --- /dev/null +++ b/OpenTAD/configs/adatad/README.md @@ -0,0 +1,14 @@ +# AdaTAD + +> [End-to-End Temporal Action Detection with 1B Parameters Across 1000 Frames](https://arxiv.org/abs/2311.17241) +> Shuming Liu, Chen-Lin Zhang, Chen Zhao, Bernard Ghanem + + + +## Abstract + +Recently, temporal action detection (TAD) has seen significant performance improvement with end-to-end training. However, due to the memory bottleneck, only models with limited scales and limited data volumes can afford end-to-end training, which inevitably restricts TAD performance. In this paper, we reduce the memory consumption for end-to-end training, and manage to scale up the TAD backbone to 1 billion parameters and the input video to 1,536 frames, leading to significant detection performance. The key to our approach lies in our proposed temporal-informative adapter (TIA), which is a novel lightweight module that reduces training memory. Using TIA, we free the humongous backbone from learning to adapt to the TAD task by only updating the parameters in TIA. TIA also leads to better TAD representation by temporally aggregating context from adjacent frames throughout the backbone. We evaluate our model across four representative datasets. Owing to our efficient design, we are able to train end-to-end on VideoMAEv2-giant and achieve 75.4% mAP on THUMOS14, being the first end-to-end model to outperform the best feature-based methods. + +## Results and Models + +Code and pretrained models will be released soon! diff --git a/OpenTAD/configs/afsd/README.md b/OpenTAD/configs/afsd/README.md new file mode 100644 index 0000000000000000000000000000000000000000..467790a44219031717bb25e0445016f78e5781ab --- /dev/null +++ b/OpenTAD/configs/afsd/README.md @@ -0,0 +1,72 @@ +# AFSD + +> [Learning Salient Boundary Feature for Anchor-free Temporal Action Localization](https://arxiv.org/abs/2103.13137) +> Chuming Lin, Chengming Xu, Donghao Luo, Yabiao Wang, Ying Tai, Chengjie Wang, Jilin Li, Feiyue Huang, Yanwei Fu + + + +## Abstract + +Temporal action localization is an important yet challenging task in video understanding. Typically, such a task aims at inferring both the action category and localization of the start and end frame for each action instance in a long, untrimmed video.While most current models achieve good results by using pre-defined anchors and numerous actionness, such methods could be bothered with both large number of outputs and heavy tuning of locations and sizes corresponding to different anchors. Instead, anchor-free methods is lighter, getting rid of redundant hyper-parameters, but gains few attention. In this paper, we propose the first purely anchor-free temporal localization method, which is both efficient and effective. Our model includes (i) an end-to-end trainable basic predictor, (ii) a saliency-based refinement module to gather more valuable boundary features for each proposal with a novel boundary pooling, and (iii) several consistency constraints to make sure our model can find the accurate boundary given arbitrary proposals. Extensive experiments show that our method beats all anchor-based and actionness-guided methods with a remarkable margin on THUMOS14, achieving state-of-the-art results, and comparable ones on ActivityNet v1.3. + +## Results and Models + +**ActivityNet-1.3** with CUHK classifier. + +| E2E | Setting | GPUs | mAP@0.5 | mAP@0.75 | mAP@0.95 | Average mAP | Config | Download | +| :---: | :---------------: | :---: | :-----: | :------: | :------: | :---------: | :---------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| False | Feature-TSP | 1 | 54.44 | 36.72 | 8.69 | 36.10 | [config](anet_tsp.py) | [model](https://drive.google.com/file/d/1wha6AM-FuSR9zxZAo4LiTiSNFIyXo-Em/view?usp=sharing) \| [log](https://drive.google.com/file/d/1pW8o6YH4ek33Fkq4EpsS_i2J1EQ-y9tS/view?usp=sharing) | +| True | I3D-R50-768x96x96 | 4 | 52.77 | 35.01 | 7.74 | 34.57 | [config](anet_i3d_r50_768x96x96_lr1e-5_bs16.py) | [model](https://drive.google.com/file/d/1lJT0nm3GHCxTt-SYLlke_nd3oufuILmo/view?usp=sharing) \| [log](https://drive.google.com/file/d/1pER_OyZ0N5cfr2z0LglZE9Xh1PCx8plL/view?usp=sharing) | + + +**THUMOS14** +| E2E | Setting | GPUs | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | Average mAP | Config | Download | +| :---: | :---------------: | :---: | :-----: | :-----: | :-----: | :-----: | :-----: | :---------: | :------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| False | Feature-I3D | 1 | 73.20 | 68.45 | 60.16 | 46.74 | 31.24 | 55.96 | [config](thumos_i3d.py) | [model](https://drive.google.com/file/d/1j_GIAY8QOeasuXiGw56WJ5jzRqQYnYw7/view?usp=sharing) \| [log](https://drive.google.com/file/d/1JCtl56tDJCCMVeVUaYFFTuLfp_fj3X5b/view?usp=sharing) | +| True | I3D-R50-256x96x96 | 1 | 3.88 | 48.81 | 41.36 | 31.70 | 21.03 | 39.36 | [config](thumos_i3d_r50_256x96x96_lr1e-5.py) | [model](https://drive.google.com/file/d/1ad4l6l0fYngEkX0H3xgQaSmhkYjVcmxw/view?usp=sharing) \| [log](https://drive.google.com/file/d/1zhts1Uh6eqxQfxcmVa6atWY5HsORBOyM/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train AFSD on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/afsd/anet_tsp.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test AFSD on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/afsd/anet_tsp.py --checkpoint exps/anet/afsd_tsp_96/gpu1_id0/checkpoint/epoch_9.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + +## Citation + +```latex +@InProceedings{Lin_2021_CVPR, + author = {Lin, Chuming and Xu, Chengming and Luo, Donghao and Wang, Yabiao and Tai, Ying and Wang, Chengjie and Li, Jilin and Huang, Feiyue and Fu, Yanwei}, + title = {Learning Salient Boundary Feature for Anchor-free Temporal Action Localization}, + booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, + month = {June}, + year = {2021}, + pages = {3320-3329} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/afsd/anet_i3d_r50_768x96x96_lr1e-5_bs16.py b/OpenTAD/configs/afsd/anet_i3d_r50_768x96x96_lr1e-5_bs16.py new file mode 100644 index 0000000000000000000000000000000000000000..4485a85bef190de577b9c2820a98948b068de496 --- /dev/null +++ b/OpenTAD/configs/afsd/anet_i3d_r50_768x96x96_lr1e-5_bs16.py @@ -0,0 +1,133 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/e2e_resize_768_1x224x224.py", # dataset config + "../_base_/models/afsd.py", # model config +] + +resize_length = 96 +dataset = dict( + train=dict( + resize_length=resize_length, + block_list=None, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize", scale_factor=8), # load 96x8=768 frames + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 109)), + dict(type="mmaction.RandomCrop", size=96), + dict(type="mmaction.Flip", flip_ratio=0.5, direction="horizontal"), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + resize_length=resize_length, + block_list=None, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize", scale_factor=8), # load 96x8=768 frames + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 96)), + dict(type="mmaction.CenterCrop", crop_size=96), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + resize_length=resize_length, + block_list=None, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize", scale_factor=8), # load 96x8=768 frames + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 96)), + dict(type="mmaction.CenterCrop", crop_size=96), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs"]), + dict(type="Collect", inputs="imgs", keys=["masks"]), + ], + ), +) + +model = dict( + backbone=dict( + type="mmaction.Recognizer3D", + backbone=dict( + type="mmaction.ResNet3d", + pretrained2d=True, + pretrained="torchvision://resnet50", + depth=50, + conv1_kernel=(5, 7, 7), + conv1_stride_t=2, + pool1_stride_t=2, + conv_cfg=dict(type="Conv3d"), + norm_eval=False, + inflate=((1, 1, 1), (1, 0, 1, 0), (1, 0, 1, 0, 1, 0), (0, 1, 0)), + zero_init_residual=False, + ), + data_preprocessor=dict( + type="mmaction.ActionDataPreprocessor", + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + format_shape="NCTHW", + ), + custom=dict( + pretrain="https://download.openmmlab.com/mmaction/v1.0/recognition/i3d/i3d_imagenet-pretrained-r50_8xb8-dense-32x2x1-100e_kinetics400-rgb/i3d_imagenet-pretrained-r50_8xb8-dense-32x2x1-100e_kinetics400-rgb_20220812-9f46003f.pth", + # input video shape is [bs,1,3,768,96,96], after the backbone, the feature shape is [bs,1,2048,96,3,3] + post_processing_pipeline=[ + dict(type="Reduce", keys=["feats"], ops="b n c t h w -> b c t h w", reduction="mean"), + ], + # the post_processing pipeline will reduce the feature to [bs,2048,96,3,3] + norm_eval=True, # set all norm layers to eval mode, default is True + freeze_backbone=False, # whether to freeze the backbone, default is False + ), + ), + neck=dict(type="AFSDNeck", in_channels=2048, e2e=True), +) + +solver = dict( + train=dict(batch_size=16, num_workers=8), + val=dict(batch_size=16, num_workers=8), + test=dict(batch_size=16, num_workers=8), + clip_grad_norm=1, +) + +optimizer = dict( + type="AdamW", + lr=5e-4, + weight_decay=1e-4, + backbone=dict(lr=1e-5, weight_decay=1e-4), +) +scheduler = dict(type="LinearWarmupMultiStepLR", warmup_epoch=1, milestones=[5], gamma=0.1, max_epoch=15) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.85, + max_seg_num=100, + min_score=0.001, + multiclass=False, + voting_thresh=0.9, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=100, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=5, +) + +work_dir = "exps/anet/afsd_anet_i3d_768x96x96_bs16" diff --git a/OpenTAD/configs/afsd/anet_tsp.py b/OpenTAD/configs/afsd/anet_tsp.py new file mode 100644 index 0000000000000000000000000000000000000000..8e3abb1f1e4ad602a4c93b159dc5ddf96250c104 --- /dev/null +++ b/OpenTAD/configs/afsd/anet_tsp.py @@ -0,0 +1,50 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize.py", # dataset config + "../_base_/models/afsd.py", # model config +] + +dataset = dict( + train=dict(resize_length=96), + val=dict(resize_length=96), + test=dict(resize_length=96), +) + +model = dict(neck=dict(in_channels=512)) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=1e-4) +scheduler = dict(type="LinearWarmupMultiStepLR", warmup_epoch=1, milestones=[5], gamma=0.1, max_epoch=10) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.85, + max_seg_num=100, + min_score=0.001, + multiclass=False, + voting_thresh=0.9, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=5, +) + +work_dir = "exps/anet/afsd_anet_tsp_96" diff --git a/OpenTAD/configs/afsd/thumos_i3d.py b/OpenTAD/configs/afsd/thumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..28bc2cf142eefb9595572165fa90c1341c6a2a48 --- /dev/null +++ b/OpenTAD/configs/afsd/thumos_i3d.py @@ -0,0 +1,48 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_i3d_sw.py", + "../_base_/models/afsd.py", +] + +dataset = dict( + train=dict(sample_stride=3, window_size=64, window_overlap_ratio=0.875), + val=dict(sample_stride=3, window_size=64, window_overlap_ratio=0.5), + test=dict(sample_stride=3, window_size=64, window_overlap_ratio=0.5), +) + +model = dict( + neck=dict(in_channels=2048, frame_num=256), + rpn_head=dict(frame_num=256, feat_t=256 // 4, num_classes=21, fpn_strides=[1, 1, 1, 1, 1, 1]), + roi_head=dict(num_classes=21, overlap_thresh=0.5, loc_weight=10, loc_bounded=False, use_smooth_l1=False), +) + +solver = dict( + train=dict(batch_size=1, num_workers=4), + val=dict(batch_size=1, num_workers=4), + test=dict(batch_size=1, num_workers=4), + clip_grad_norm=0.1, +) + +optimizer = dict(type="AdamW", lr=1e-5, weight_decay=1e-3) +scheduler = dict(type="MultiStepLR", milestones=[16], gamma=0.1, max_epoch=16) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=2000, + min_score=0.01, + multiclass=True, + voting_thresh=0.95, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=2000, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, +) + +work_dir = "exps/thumos/afsd_i3d" diff --git a/OpenTAD/configs/afsd/thumos_i3d_r50_256x96x96_lr1e-5.py b/OpenTAD/configs/afsd/thumos_i3d_r50_256x96x96_lr1e-5.py new file mode 100644 index 0000000000000000000000000000000000000000..3f4d22034a5f43d4a56fec91026a09cc0a366edd --- /dev/null +++ b/OpenTAD/configs/afsd/thumos_i3d_r50_256x96x96_lr1e-5.py @@ -0,0 +1,137 @@ +_base_ = [ + "../_base_/datasets/thumos-14/e2e_sw_256x224x224.py", + "../_base_/models/afsd.py", +] + +window_size = 64 +dataset = dict( + train=dict( + feature_stride=12, + sample_stride=1, + window_size=window_size, + window_overlap_ratio=0.875, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window", scale_factor=4), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 109)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(96, 96), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + feature_stride=12, + sample_stride=1, + window_size=window_size, + window_overlap_ratio=0.5, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window", scale_factor=4), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 96)), + dict(type="mmaction.CenterCrop", crop_size=96), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + feature_stride=12, + sample_stride=1, + window_size=window_size, + window_overlap_ratio=0.5, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window", scale_factor=4), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 96)), + dict(type="mmaction.CenterCrop", crop_size=96), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs"]), + dict(type="Collect", inputs="imgs", keys=["masks"]), + ], + ), +) + +model = dict( + backbone=dict( + type="mmaction.Recognizer3D", + backbone=dict( + type="mmaction.ResNet3d", + pretrained2d=True, + pretrained="torchvision://resnet50", + depth=50, + conv1_kernel=(5, 7, 7), + conv1_stride_t=2, + pool1_stride_t=2, + conv_cfg=dict(type="Conv3d"), + norm_eval=False, + inflate=((1, 1, 1), (1, 0, 1, 0), (1, 0, 1, 0, 1, 0), (0, 1, 0)), + zero_init_residual=False, + ), + data_preprocessor=dict( + type="mmaction.ActionDataPreprocessor", + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + format_shape="NCTHW", + ), + custom=dict( + pretrain="https://download.openmmlab.com/mmaction/v1.0/recognition/i3d/i3d_imagenet-pretrained-r50_8xb8-dense-32x2x1-100e_kinetics400-rgb/i3d_imagenet-pretrained-r50_8xb8-dense-32x2x1-100e_kinetics400-rgb_20220812-9f46003f.pth", + # input video shape is [bs,1,3,768,96,96], after the backbone, the feature shape is [bs,1,2048,96,3,3] + post_processing_pipeline=[ + dict(type="Reduce", keys=["feats"], ops="b n c t h w -> b c t h w", reduction="mean"), + dict(type="Interpolate", keys=["feats"], size=(window_size, 3, 3), mode="trilinear"), + ], + # the post_processing pipeline will reduce the feature to [bs,2048,96,3,3] + norm_eval=True, # set all norm layers to eval mode, default is True + freeze_backbone=False, # whether to freeze the backbone, default is False + ), + ), + neck=dict(type="AFSDNeck", in_channels=2048, e2e=True, frame_num=256), + rpn_head=dict(frame_num=256, feat_t=256 // 4, num_classes=21, fpn_strides=[1, 1, 1, 1, 1, 1]), + roi_head=dict(num_classes=21, overlap_thresh=0.5, loc_weight=10, loc_bounded=False, use_smooth_l1=False), +) + +solver = dict( + train=dict(batch_size=1, num_workers=1), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=0.1, +) + +optimizer = dict( + type="AdamW", + lr=1e-5, + weight_decay=1e-3, + backbone=dict(lr=1e-5, weight_decay=1e-3), +) +scheduler = dict(type="MultiStepLR", milestones=[16], gamma=0.1, max_epoch=16) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=2000, + min_score=0.01, + multiclass=True, + voting_thresh=0.95, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=2000, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, +) + +work_dir = "exps/thumos/afsd_i3d_256x96x96" diff --git a/OpenTAD/configs/bmn/README.md b/OpenTAD/configs/bmn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e64df589343af0cea8b1835b6cbf4c04d6edbf43 --- /dev/null +++ b/OpenTAD/configs/bmn/README.md @@ -0,0 +1,92 @@ +# BMN + +> [BMN: Boundary-Matching Network for Temporal Action Proposal Generation](https://arxiv.org/abs/1907.09702) +> Tianwei Lin, Xiao Liu, Xin Li, Errui Ding, Shilei Wen + + + +## Abstract + +Temporal action proposal generation is an challenging and promising task which aims to locate temporal regions in real-world videos where action or event may occur. Current bottom-up proposal generation methods can generate proposals with precise boundary, but cannot efficiently generate adequately reliable confidence scores for retrieving proposals. To address these difficulties, we introduce the Boundary-Matching (BM) mechanism to evaluate confidence scores of densely distributed proposals, which denote a proposal as a matching pair of starting and ending boundaries and combine all densely distributed BM pairs into the BM confidence map. Based on BM mechanism, we propose an effective, efficient and end-to-end proposal generation method, named Boundary-Matching Network (BMN), which generates proposals with precise temporal boundaries as well as reliable confidence scores simultaneously. The two-branches of BMN are jointly trained in an unified framework. We conduct experiments on two challenging datasets: THUMOS-14 and ActivityNet-1.3, where BMN shows significant performance improvement with remarkable efficiency and generalizability. Further, combining with existing action classifier, BMN can achieve state-of-the-art temporal action detection performance. + +## Results and Models + +**ActivityNet-1.3** with CUHK classifier. + +| Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :------: | :-----: | :------: | :------: | :------: | :-------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| TSN | 50.97 | 34.98 | 8.35 | 34.21 | [config](anet_tsn.py) | [model](https://drive.google.com/file/d/1yWu05_BS2RuHnItIpFvKVieiYOGWbzNj/view?usp=sharing) \| [log](https://drive.google.com/file/d/1KtICNUOt_IVEWfSXqZ-6R_msKm40AaTU/view?usp=sharing) | +| TSP | 52.90 | 37.30 | 9.67 | 36.40 | [config](anet_tsp.py) | [model](https://drive.google.com/file/d/1sQQble7270Ja5Nx8kR5tApeJGGS42t6M/view?usp=sharing) \| [log](https://drive.google.com/file/d/1sxXjeIzEt0Nx_YZNj_tCcAsN9_TJe6xU/view?usp=sharing) | + +Use above checkpoints to evaluate the recall performance: + +| Features | AR@1 | AR@5 | AR@10 | AR@100 | AUC | Config | Download | +| :------: | :---: | :---: | :---: | :----: | :---: | :--------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| TSN | 33.58 | 49.16 | 56.53 | 75.34 | 67.23 | [config](anet_tsn_recall.py) | [model](https://drive.google.com/file/d/1yWu05_BS2RuHnItIpFvKVieiYOGWbzNj/view?usp=sharing) \| [log](https://drive.google.com/file/d/1xT6T7s8tNcuVgItWXyF2gI2cCU6T993O/view?usp=sharing) | +| TSP | 34.14 | 51.35 | 58.44 | 76.24 | 68.47 | [config](anet_tsp_recall.py) | [model](https://drive.google.com/file/d/1sQQble7270Ja5Nx8kR5tApeJGGS42t6M/view?usp=sharing) \| [log](https://drive.google.com/file/d/12Q5vhXaH_YQoAxqtWFAzePAb5MfGGJ1Z/view?usp=sharing) | + + +**THUMOS-14** with UtrimmedNet classifier. + +| Features | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :---------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| TSN | 60.51 | 56.03 | 47.56 | 38.23 | 28.64 | 46.19 | [config](thumos_tsn.py) | [model](https://drive.google.com/file/d/14GANupLwRE4dAesyafeU4aGx-8c38ogd/view?usp=sharing) \| [log](https://drive.google.com/file/d/1DeDCLezP4rRZwq7ppPG5coA2ol0fSvkZ/view?usp=sharing) | +| I3D | 64.99 | 60.70 | 54.54 | 44.11 | 34.16 | 51.70 | [config](thumos_i3d.py) | [model](https://drive.google.com/file/d/1aPl_jNOlbcr7Qc2DzNM10dRiMDfcSJ7V/view?usp=sharing) \| [log](https://drive.google.com/file/d/1TJGylck9Zhqew5IECeDjqwLNO8Zkq0QD/view?usp=sharing) | + +**HACS** with TCANet classifier. + +| Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :------: | :-----: | :------: | :------: | :------: | :----------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| SlowFast | 52.64 | 36.18 | 11.46 | 35.78 | [config](hacs_slowfast_192.py) | [model](https://drive.google.com/file/d/1gLOmyu-zLi7Gpph2czH9bgiJCKyeUvsm/view?usp=sharing) \| [log](https://drive.google.com/file/d/1fMm1sjNtbgWNIcFmdRSpnvKfiXOmsLQ2/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train BMN on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/bmn/anet_tsp.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test BMN on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/bmn/anet_tsp.py --checkpoint exps/anet/bmn_tsp_128/gpu1_id0/checkpoint/epoch_9.pth +``` + +To test the recal performance: + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/bmn/anet_tsp_recall.py --checkpoint exps/anet/bmn_tsp_128/gpu1_id0/checkpoint/epoch_9.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + + +## Citation + +```latex +@inproceedings{lin2019bmn, + title={Bmn: Boundary-matching network for temporal action proposal generation}, + author={Lin, Tianwei and Liu, Xiao and Li, Xin and Ding, Errui and Wen, Shilei}, + booktitle={Proceedings of the IEEE/CVF international conference on computer vision}, + pages={3889--3898}, + year={2019} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/bmn/anet_tsn.py b/OpenTAD/configs/bmn/anet_tsn.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a4e56a166f4a75fffd10854647d8a3cefd7278 --- /dev/null +++ b/OpenTAD/configs/bmn/anet_tsn.py @@ -0,0 +1,50 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize.py", # dataset config + "../_base_/models/bmn.py", # model config +] + +data_path = "data/activitynet-1.3/features/anet_tsn_npy_unresize/" +block_list = "data/activitynet-1.3/features/anet_tsn_npy_unresize/missing_files.txt" +dataset = dict( + train=dict(data_path=data_path, block_list=block_list), + val=dict(data_path=data_path, block_list=block_list), + test=dict(data_path=data_path, block_list=block_list), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-3, weight_decay=1e-4, paramwise=True) +scheduler = dict(type="MultiStepLR", milestones=[7], gamma=0.1, max_epoch=10) + +inference = dict(test_epoch=7, load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=100, + min_score=0.01, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=7, +) + +work_dir = "exps/anet/bmn_tsn_128" diff --git a/OpenTAD/configs/bmn/anet_tsn_recall.py b/OpenTAD/configs/bmn/anet_tsn_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..8e9bc7d4c3187ff519e1c76946c9901a4a7b05ee --- /dev/null +++ b/OpenTAD/configs/bmn/anet_tsn_recall.py @@ -0,0 +1,28 @@ +_base_ = ["anet_tsn.py"] + +evaluation = dict( + type="Recall", + subset="validation", + topk=[1, 5, 10, 100], + max_avg_nr_proposals=100, + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], +) + +post_processing = dict( + score_type="iou*s*e", + proposal=True, + nms=dict( + use_soft_nms=True, + sigma=0.4, + max_seg_num=100, + iou_threshold=0, # does not matter when use soft nms + min_score=0, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + method=3, + t1=0.5, + t2=0.4, + ), + external_cls=dict(_delete_=True, type="PseudoClassifier"), + save_dict=False, +) diff --git a/OpenTAD/configs/bmn/anet_tsp.py b/OpenTAD/configs/bmn/anet_tsp.py new file mode 100644 index 0000000000000000000000000000000000000000..e81ecc5315e55233c0b95c1145c1a5b075360049 --- /dev/null +++ b/OpenTAD/configs/bmn/anet_tsp.py @@ -0,0 +1,44 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize.py", # dataset config + "../_base_/models/bmn.py", # model config +] + +model = dict(projection=dict(in_channels=512)) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-3, weight_decay=1e-4, paramwise=True) +scheduler = dict(type="MultiStepLR", milestones=[7], gamma=0.1, max_epoch=10) + +inference = dict(test_epoch=7, load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=100, + min_score=0.01, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=7, +) + +work_dir = "exps/anet/bmn_tsp_128" diff --git a/OpenTAD/configs/bmn/anet_tsp_recall.py b/OpenTAD/configs/bmn/anet_tsp_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..4976444e032278f426093aba2e608bb0f325dc94 --- /dev/null +++ b/OpenTAD/configs/bmn/anet_tsp_recall.py @@ -0,0 +1,28 @@ +_base_ = ["anet_tsp.py"] + +evaluation = dict( + type="Recall", + subset="validation", + topk=[1, 5, 10, 100], + max_avg_nr_proposals=100, + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], +) + +post_processing = dict( + score_type="iou*s*e", + proposal=True, + nms=dict( + use_soft_nms=True, + sigma=0.4, + max_seg_num=100, + iou_threshold=0, # does not matter when use soft nms + min_score=0, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + method=3, + t1=0.5, + t2=0.4, + ), + external_cls=dict(_delete_=True, type="PseudoClassifier"), + save_dict=False, +) diff --git a/OpenTAD/configs/bmn/hacs_slowfast_192.py b/OpenTAD/configs/bmn/hacs_slowfast_192.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5bb8bf0a519aaa888b28f4cc833d7db0b8d232 --- /dev/null +++ b/OpenTAD/configs/bmn/hacs_slowfast_192.py @@ -0,0 +1,72 @@ +_base_ = [ + "../_base_/datasets/hacs-1.1.1/features_slowfast_resize.py", # dataset config + "../_base_/models/bmn.py", # model config +] + +tscale = 192 +dataset = dict( + train=dict(resize_length=tscale), + val=dict(resize_length=tscale), + test=dict(resize_length=tscale), +) + +model = dict( + projection=dict(in_channels=2304), + roi_head=dict( + proposal_generator=dict(tscale=tscale, dscale=tscale), + proposal_roi_extractor=dict(tscale=tscale, dscale=tscale), + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict( + type="Adam", + lr=4e-4, + weight_decay=1e-4, +) +scheduler = dict( + type="MultiStepLR", + milestones=[5], + gamma=0.1, + max_epoch=6, +) + + +inference = dict( + test_epoch=5, + load_from_raw_predictions=False, + save_raw_prediction=False, +) + +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=100, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="TCANetHACSClassifier", + path="data/hacs-1.1.1/classifiers/validation94.32.json", + topk=3, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, +) + +work_dir = "exps/hacs/bmn_slowfast_192" diff --git a/OpenTAD/configs/bmn/thumos_i3d.py b/OpenTAD/configs/bmn/thumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..f0039be65cc1e2396cb63a6f9bbb6aa7f596fb51 --- /dev/null +++ b/OpenTAD/configs/bmn/thumos_i3d.py @@ -0,0 +1,68 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_i3d_sw.py", # dataset config + "../_base_/models/bmn.py", # model config +] + +window_size = 128 +dataset = dict( + train=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + val=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + test=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ), +) + +model = dict( + projection=dict(in_channels=2048), + roi_head=dict( + proposal_generator=dict(dscale=64, tscale=128), + proposal_roi_extractor=dict(dscale=64, tscale=128), + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-4, weight_decay=1e-4, paramwise=True) +scheduler = dict(type="MultiStepLR", milestones=[5], gamma=0.1, max_epoch=8) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.3, + max_seg_num=200, + min_score=0.0001, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="UntrimmedNetTHUMOSClassifier", + path="data/thumos-14/classifiers/uNet_test.npy", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=5, +) + +work_dir = "exps/thumos/bmn_i3d_sw128" diff --git a/OpenTAD/configs/bmn/thumos_tsn.py b/OpenTAD/configs/bmn/thumos_tsn.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd3237c79aaa3d90f839fe3b3408fec0480a125 --- /dev/null +++ b/OpenTAD/configs/bmn/thumos_tsn.py @@ -0,0 +1,74 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_tsn_sw.py", # dataset config + "../_base_/models/bmn.py", # model config +] + +window_size = 128 +dataset = dict( + train=dict( + feature_stride=1, + sample_stride=5, + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + val=dict( + feature_stride=1, + sample_stride=5, + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + test=dict( + feature_stride=1, + sample_stride=5, + window_size=window_size, + window_overlap_ratio=0.5, + ), +) + +model = dict( + projection=dict(in_channels=2048), + roi_head=dict( + proposal_generator=dict(dscale=64, tscale=128), + proposal_roi_extractor=dict(dscale=64, tscale=128), + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-4, weight_decay=1e-4, paramwise=True) +scheduler = dict(type="MultiStepLR", milestones=[5], gamma=0.1, max_epoch=8) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.3, + max_seg_num=200, + min_score=0.0001, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="UntrimmedNetTHUMOSClassifier", + path="data/thumos-14/classifiers/uNet_test.npy", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=5, +) + +work_dir = "exps/thumos/bmn_tsn_sw128" diff --git a/OpenTAD/configs/etad/README.md b/OpenTAD/configs/etad/README.md new file mode 100644 index 0000000000000000000000000000000000000000..40cc554a7cff71e35562caedef00b47f27b968d2 --- /dev/null +++ b/OpenTAD/configs/etad/README.md @@ -0,0 +1,69 @@ +# ETAD + +> [ETAD: Training Action Detection End to End on a Laptop](https://arxiv.org/abs/2205.07134) +> Shuming Liu, Mengmeng Xu, Chen Zhao, Xu Zhao, Bernard Ghanem + + + +## Abstract + +Temporal action detection (TAD) with end-to-end training often suffers from the pain of huge demand for computing resources due to long video duration. In this work, we propose an efficient temporal action detector (ETAD) that can train directly from video frames with extremely low GPU memory consumption. Our main idea is to minimize and balance the heavy computation among features and gradients in each training iteration. We propose to sequentially forward the snippet frame through the video encoder, and backward only a small necessary portion of gradients to update the encoder. To further alleviate the computational redundancy in training, we propose to dynamically sample only a small subset of proposals during training. Moreover, various sampling strategies and ratios are studied for both the encoder and detector. ETAD achieves state-of-the-art performance on TAD benchmarks with remarkable efficiency. On ActivityNet-1.3, training ETAD in 18 hours can reach 38.25% average mAP with only 1.3 GB memory consumption per video under end-to-end training. Our code will be publicly released. + +## Results and Models + +**ActivityNet-1.3** with CUHK classifier. + +| E2E | Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :---: | :------: | :-----: | :------: | :------: | :------: | :-------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| False | TSP | 54.91 | 38.90 | 9.09 | 37.73 | [config](anet_tsp.py) | [model](https://drive.google.com/file/d/1r7zLfIaLPHb_7ba6tPzjKE3_WpGtrnge/view?usp=sharing) \| [log](https://drive.google.com/file/d/1wc27fX4qWUBarzeXR2aDfQjvN25G72Uu/view?usp=sharing) | + +**THUMOS-14** with UtrimmedNet classifier + +| E2E | Features | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :---: | :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :---------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| False | I3D | 67.74 | 64.22 | 58.23 | 49.19 | 38.41 | 55.56 | [config](thumos_i3d.py) | [model](https://drive.google.com/file/d/1sRPYxfD_jGmsa1jB4Kw2Z4bVVnnlxx3u/view?usp=sharing) \| [log](https://drive.google.com/file/d/1T4QHGOz5BZxHsH_vt8_u6aFYKHoZZeuY/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train ETAD on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/etad/anet_tsp.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test ETAD on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/etad/anet_tsp.py --checkpoint exps/anet/etad_tsp_128/gpu1_id0/checkpoint/epoch_5.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + +## Citation + +```latex +@inproceedings{liu2023etad, + title={ETAD: Training Action Detection End to End on a Laptop}, + author={Liu, Shuming and Xu, Mengmeng and Zhao, Chen and Zhao, Xu and Ghanem, Bernard}, + booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, + pages={4524--4533}, + year={2023} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/etad/anet_tsp.py b/OpenTAD/configs/etad/anet_tsp.py new file mode 100644 index 0000000000000000000000000000000000000000..8ef9abe1444dee478a8ee2bd2c933b314458c288 --- /dev/null +++ b/OpenTAD/configs/etad/anet_tsp.py @@ -0,0 +1,44 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize.py", # dataset config + "../_base_/models/etad.py", # model config +] + +model = dict(projection=dict(in_channels=512)) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=1e-4) +scheduler = dict(type="MultiStepLR", milestones=[5], gamma=0.1, max_epoch=6) + +inference = dict(test_epoch=5, load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.35, + max_seg_num=100, + min_score=0.0001, + multiclass=False, + voting_thresh=0, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=5, +) + +work_dir = "exps/anet/etad_tsp_128" diff --git a/OpenTAD/configs/etad/thumos_i3d.py b/OpenTAD/configs/etad/thumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ea064df112ae4e6570a9b5f8b1827045c07f03 --- /dev/null +++ b/OpenTAD/configs/etad/thumos_i3d.py @@ -0,0 +1,69 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_i3d_sw.py", # dataset config + "../_base_/models/etad.py", # model config +] + +window_size = 128 +dataset = dict( + train=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + val=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + test=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ), +) + +model = dict( + projection=dict(in_channels=2048), + roi_head=dict( + proposal_generator=dict(dscale=64, sampling_ratio=0.1), + proposal_roi_extractor=dict(roi_size=16), + proposal_head=dict(roi_size=16, feat_channels=256), + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-4, weight_decay=1e-4) +scheduler = dict(type="MultiStepLR", milestones=[5], gamma=0.1, max_epoch=8) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.3, + max_seg_num=200, + min_score=0.0001, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="UntrimmedNetTHUMOSClassifier", + path="data/thumos-14/classifiers/uNet_test.npy", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=5, +) + +work_dir = "exps/thumos/etad_i3d_sw128" diff --git a/OpenTAD/configs/gtad/README.md b/OpenTAD/configs/gtad/README.md new file mode 100644 index 0000000000000000000000000000000000000000..99a00b6fde53f5ba2551de7dc3b8cf8c6db13080 --- /dev/null +++ b/OpenTAD/configs/gtad/README.md @@ -0,0 +1,72 @@ +# G-TAD + +> [G-TAD: Sub-Graph Localization for Temporal Action Detection](https://arxiv.org/abs/1911.11462) +> Mengmeng Xu, Chen Zhao, David S. Rojas, Ali Thabet, Bernard Ghanem + + + +## Abstract + +Temporal action detection is a fundamental yet challenging task in video understanding. Video context is a critical cue to effectively detect actions, but current works mainly focus on temporal context, while neglecting semantic context as well as other important context properties. In this work, we propose a graph convolutional network (GCN) model to adaptively incorporate multi-level semantic context into video features and cast temporal action detection as a sub-graph localization problem. Specifically, we formulate video snippets as graph nodes, snippet-snippet correlations as edges, and actions associated with context as target sub-graphs. With graph convolution as the basic operation, we design a GCN block called GCNeXt, which learns the features of each node by aggregating its context and dynamically updates the edges in the graph. To localize each sub-graph, we also design an SGAlign layer to embed each sub-graph into the Euclidean space. Extensive experiments show that G-TAD is capable of finding effective video context without extra supervision and achieves state-of-the-art performance on two detection benchmarks. On ActivityNet-1.3, it obtains an average mAP of 34.09%; on THUMOS14, it reaches 51.6% at IoU@0.5 when combined with a proposal processing method. + +## Results and Models + +**ActivityNet-1.3** with CUHK classifier. + +| Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :------: | :-----: | :------: | :------: | :------: | :-------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| TSN | 50.19 | 35.04 | 8.11 | 34.18 | [config](anet_tsn.py) | [model](https://drive.google.com/file/d/1cyiTPZ73ud9-UxHFr7E4tkp7LEkM7_qE/view?usp=sharing) \| [log](https://drive.google.com/file/d/10MfgZlIS8XIc0sffXnIOgOR7RIXTd5Ve/view?usp=sharing) | +| TSP | 52.33 | 37.58 | 8.42 | 36.20 | [config](anet_tsp.py) | [model](https://drive.google.com/file/d/1CoBygy7JM26Rz7RTzIgKk0negmCa5Ier/view?usp=sharing) \| [log](https://drive.google.com/file/d/1ZQo2SI1TZdPkNL80FcslyForVaFDGTlB/view?usp=sharing) | + + +**THUMOS-14** with UtrimmedNet classifier + +| Features | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :---------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| TSN | 60.52 | 55.08 | 48.50 | 39.60 | 28.74 | 46.49 | [config](thumos_tsn.py) | [model](https://drive.google.com/file/d/1SCzVn2RuuIUQ3g2bktSukt0dmLR27ei0/view?usp=sharing) \| [log](https://drive.google.com/file/d/1VFID5LUY8p0mycYAOcjCWjNg9DkcdvEk/view?usp=sharing) | +| I3D | 63.35 | 59.07 | 51.76 | 42.65 | 31.66 | 49.70 | [config](thumos_i3d.py) | [model](https://drive.google.com/file/d/1qW80nahmt671AUR58PABzyBdQYqP9gO1/view?usp=sharing) \| [log](https://drive.google.com/file/d/12FvCQ3j0aP4qGvus0XJaNTJRxhcxIEa5/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train GTAD on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/gtad/anet_tsp.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test GTAD on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/gtad/anet_tsp.py --checkpoint exps/anet/gtad_tsp_100x100/gpu1_id0/checkpoint/epoch_7.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + +## Citation + +```latex +@InProceedings{xu2020gtad, + author = {Xu, Mengmeng and Zhao, Chen and Rojas, David S. and Thabet, Ali and Ghanem, Bernard}, + title = {G-TAD: Sub-Graph Localization for Temporal Action Detection}, + booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, + month = {June}, + year = {2020} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/gtad/anet_tsn.py b/OpenTAD/configs/gtad/anet_tsn.py new file mode 100644 index 0000000000000000000000000000000000000000..f26912518da3e680f5c13d1246f92fea1710bfb7 --- /dev/null +++ b/OpenTAD/configs/gtad/anet_tsn.py @@ -0,0 +1,51 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize.py", # dataset config + "../_base_/models/gtad.py", # model config +] + +resize_length = 100 +data_path = "data/activitynet-1.3/features/anet_tsn_npy_unresize/" +block_list = "data/activitynet-1.3/features/anet_tsn_npy_unresize/missing_files.txt" +dataset = dict( + train=dict(data_path=data_path, block_list=block_list, resize_length=resize_length), + val=dict(data_path=data_path, block_list=block_list, resize_length=resize_length), + test=dict(data_path=data_path, block_list=block_list, resize_length=resize_length), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=4e-3, weight_decay=1e-4) +scheduler = dict(type="MultiStepLR", milestones=[5], gamma=0.1, max_epoch=10) + + +inference = dict(test_epoch=7, load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.8, # 0.45, 0.55 + max_seg_num=100, + iou_threshold=0, # does not matter when use soft nms + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=4, +) + +work_dir = "exps/anet/gtad_tsn_100x100" diff --git a/OpenTAD/configs/gtad/anet_tsp.py b/OpenTAD/configs/gtad/anet_tsp.py new file mode 100644 index 0000000000000000000000000000000000000000..51ce58651f2a09a5849f7794cfb57664a168510f --- /dev/null +++ b/OpenTAD/configs/gtad/anet_tsp.py @@ -0,0 +1,51 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize.py", # dataset config + "../_base_/models/gtad.py", # model config +] + +resize_length = 100 +dataset = dict( + train=dict(resize_length=resize_length), + val=dict(resize_length=resize_length), + test=dict(resize_length=resize_length), +) + +model = dict(projection=dict(in_channels=512)) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=4e-3, weight_decay=1e-4) +scheduler = dict(type="MultiStepLR", milestones=[5], gamma=0.1, max_epoch=10) + + +inference = dict(test_epoch=7, load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.8, + max_seg_num=100, + iou_threshold=0, # does not matter when use soft nms + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=4, +) + +work_dir = "exps/anet/gtad_tsp_100x100" diff --git a/OpenTAD/configs/gtad/thumos_i3d.py b/OpenTAD/configs/gtad/thumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..f76177c0ab4e0e6b2f336e35d586115ed6f25551 --- /dev/null +++ b/OpenTAD/configs/gtad/thumos_i3d.py @@ -0,0 +1,69 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_i3d_sw.py", # dataset config + "../_base_/models/gtad.py", # model config +] + +window_size = 256 +dataset = dict( + train=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + val=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + test=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ), +) + +model = dict( + projection=dict(in_channels=2048), + roi_head=dict( + proposal_generator=dict(dscale=64, tscale=256), + proposal_roi_extractor=dict(dscale=64, tscale=256, roi_size=16, context_size=16), + proposal_head=dict(kernel_size=3), + ), +) + +solver = dict( + train=dict(batch_size=8, num_workers=4), + val=dict(batch_size=8, num_workers=4), + test=dict(batch_size=8, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-4, weight_decay=1e-4) +scheduler = dict(type="MultiStepLR", milestones=[5], gamma=0.1, max_epoch=8) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.3, + max_seg_num=200, + min_score=0.0001, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="UntrimmedNetTHUMOSClassifier", + path="data/thumos-14/classifiers/uNet_test.npy", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=5, +) + +work_dir = "exps/thumos/gtad_i3d_sw256" diff --git a/OpenTAD/configs/gtad/thumos_tsn.py b/OpenTAD/configs/gtad/thumos_tsn.py new file mode 100644 index 0000000000000000000000000000000000000000..8454ef4cdbd5627d7bd40d45ab50c0ac0361ab3b --- /dev/null +++ b/OpenTAD/configs/gtad/thumos_tsn.py @@ -0,0 +1,75 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_tsn_sw.py", # dataset config + "../_base_/models/gtad.py", # model config +] + +window_size = 256 +dataset = dict( + train=dict( + feature_stride=1, + sample_stride=5, + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + val=dict( + feature_stride=1, + sample_stride=5, + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + test=dict( + feature_stride=1, + sample_stride=5, + window_size=window_size, + window_overlap_ratio=0.5, + ), +) + +model = dict( + projection=dict(in_channels=2048), + roi_head=dict( + proposal_generator=dict(dscale=64, tscale=256), + proposal_roi_extractor=dict(dscale=64, tscale=256, roi_size=16, context_size=16), + proposal_head=dict(kernel_size=3), + ), +) + +solver = dict( + train=dict(batch_size=8, num_workers=4), + val=dict(batch_size=8, num_workers=4), + test=dict(batch_size=8, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-4, weight_decay=1e-4) +scheduler = dict(type="MultiStepLR", milestones=[5], gamma=0.1, max_epoch=8) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.3, + max_seg_num=200, + min_score=0.0001, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="UntrimmedNetTHUMOSClassifier", + path="data/thumos-14/classifiers/uNet_test.npy", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=5, +) + +work_dir = "exps/thumos/gtad_tsn_sw256" diff --git a/OpenTAD/configs/re2tal/README.md b/OpenTAD/configs/re2tal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ada485c047cc6f11b819cca9ed8b863b941268b1 --- /dev/null +++ b/OpenTAD/configs/re2tal/README.md @@ -0,0 +1,74 @@ +# Re2TAL + +> [Re2TAL: Rewiring Pretrained Video Backbones for Reversible Temporal Action Localization](https://arxiv.org/abs/2211.14053) +> Chen Zhao, Shuming Liu, Karttikeya Mangalam, Bernard Ghanem + + + +## Abstract + +Temporal action localization (TAL) requires long-form reasoning to predict actions of various durations and complex content. Given limited GPU memory, training TAL end to end (i.e., from videos to predictions) on long videos is a significant challenge. Most methods can only train on pre-extracted features without optimizing them for the localization problem, consequently limiting localization performance. In this work, to extend the potential in TAL networks, we propose a novel end-to-end method Re2TAL, which rewires pretrained video backbones for reversible TAL. Re2TAL builds a backbone with reversible modules, where the input can be recovered from the output such that the bulky intermediate activations can be cleared from memory during training. Instead of designing one single type of reversible module, we propose a network rewiring mechanism, to transform any module with a residual connection to a reversible module without changing any parameters. This provides two benefits: (1) a large variety of reversible networks are easily obtained from existing and even future model designs, and (2) the reversible models require much less training effort as they reuse the pre-trained parameters of their original non-reversible versions. Re2TAL, only using the RGB modality, reaches 37.01% average mAP on ActivityNet-v1.3, a new state-of-the-art record, and mAP 64.9% at tIoU=0.5 on THUMOS-14, outperforming all other RGB-only methods. + +## Results and Models + +To run the experiments, please download the K400-pretrained model weights of [Re2Swin-T](https://drive.google.com/file/d/1tTheMXRHk-BFVvHAL4Rjut14WWKrZ2uH/view?usp=sharing) / [Re2SlowFast-101](https://drive.google.com/file/d/1e6Zg8SrJ9UOWvy5AkhBzo1IHRJHJH-lH/view?usp=sharing), and put them under the path `./pretrained/` + +**ActivityNet-1.3** with CUHK classifier. + +| Backbone | GPUs | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :-------------: | :---: | :-----: | :------: | :------: | :------: | :---------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| Re2Swin-T | 4 | 55.08 | 37.05 | 8.29 | 36.47 | [config](e2e_anet_re2tal_actionformer_swin_tiny.py) | [model](https://drive.google.com/file/d/1XSZ2AICZTIds_aRnuzleEh3jqPkzLAO4/view?usp=sharing) \| [log](https://drive.google.com/file/d/1__vYHlCBeJ6SvPRWhEbK9LYj_7kZXk9N/view?usp=sharing) | +| Re2SlowFast-101 | 4 | 55.81 | 38.49 | 9.36 | 37.55 | [config](e2e_anet_re2tal_actionformer_slowfast101.py) | [model](https://drive.google.com/file/d/1yuo2t1sgXlRD7wqFZxwntlrpe9pv6oqz/view?usp=sharing) \| [log](https://drive.google.com/file/d/1TnpqjP5VBre0NyxTWC40tJLrlYChfIDO/view?usp=sharing) | + +**THUMOS-14** + +| Backbone | GPUs | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :-------------: | :---: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :-----------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| Re2Swin-T | 2 | 82.12 | 78.09 | 70.06 | 59.81 | 44.35 | 66.89 | [config](e2e_thumos_re2tal_actionformer_swin_tiny.py) | [model](https://drive.google.com/file/d/1zcATsfhR2GSNGz_91ASJLR7vr0j227Th/view?usp=sharing) \| [log](https://drive.google.com/file/d/1gAVTN47EryzmJtycDP-8CUP9rP0F3qx_/view?usp=sharing) | +| Re2SlowFast-101 | 2 | 84.16 | 80.26 | 74.27 | 62.66 | 49.60 | 70.19 | [config](e2e_thumos_re2tal_actionformer_slowfast101.py) | [model](https://drive.google.com/file/d/1k1VHvKx72flKNtaCYp-Ttu39ylAttPT3/view?usp=sharing) \| [log](https://drive.google.com/file/d/1Om5ILgKayOTbLf8PjB_uYfxgdGVW59tn/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train Re2TAL on ActivityNet dataset with **4** GPUs. + +```shell +torchrun --nnodes=1 --nproc_per_node=4 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/re2tal/e2e_anet_re2tal_actionformer_slowfast101.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test Re2TAL on ActivityNet dataset with **4** GPUs. + +```shell +torchrun --nnodes=1 --nproc_per_node=4 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/re2tal/e2e_anet_re2tal_actionformer_slowfast101.py --checkpoint exps/anet/re2tal_e2e_actionformer_slowfast101_frame768/gpu4_id0/checkpoint/epoch_14.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + + +## Citation + +```latex +@inproceedings{zhao2023re2tal, + title={Re2tal: Rewiring pretrained video backbones for reversible temporal action localization}, + author={Zhao, Chen and Liu, Shuming and Mangalam, Karttikeya and Ghanem, Bernard}, + booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, + pages={10637--10647}, + year={2023} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/re2tal/e2e_anet_re2tal_actionformer_slowfast101.py b/OpenTAD/configs/re2tal/e2e_anet_re2tal_actionformer_slowfast101.py new file mode 100644 index 0000000000000000000000000000000000000000..adc10e09f4af1147396b8c998e0a32d36c83652b --- /dev/null +++ b/OpenTAD/configs/re2tal/e2e_anet_re2tal_actionformer_slowfast101.py @@ -0,0 +1,174 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/e2e_resize_768_1x224x224.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +resize_length = 192 +dataset = dict( + train=dict( + resize_length=resize_length, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize", scale_factor=4), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 256)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(224, 224), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.ImgAug", transforms="default"), + dict(type="mmaction.ColorJitter"), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + resize_length=resize_length, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize", scale_factor=4), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + resize_length=resize_length, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize", scale_factor=4), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs"]), + dict(type="Collect", inputs="imgs", keys=["masks"]), + ], + ), +) + +model = dict( + backbone=dict( + type="mmaction.Recognizer3D", + backbone=dict( + type="ResNet3dSlowFast_inv", + pretrained=None, + pretrain_type="inv_resnet_3d", + resample_rate=4, # tau + speed_ratio=4, # alpha + channel_ratio=8, # beta_inv + slow_pathway=dict( + type="resnet3d", + depth=101, + pretrained=None, + lateral=True, + fusion_kernel=7, + conv1_kernel=(1, 7, 7), + dilations=(1, 1, 1, 1), + conv1_stride_t=1, + pool1_stride_t=1, + inflate=(0, 0, 1, 1), + norm_eval=True, + frozen_stages=-1, + ), + fast_pathway=dict( + type="resnet3d", + depth=101, + pretrained=None, + lateral=False, + base_channels=8, + conv1_kernel=(5, 7, 7), + conv1_stride_t=1, + pool1_stride_t=1, + norm_eval=True, + frozen_stages=-1, + ), + inv_mode=["custom_backprop", "custom_backprop", "custom_backprop", "custom_backprop"], + ), + data_preprocessor=dict( + type="mmaction.ActionDataPreprocessor", + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + format_shape="NCTHW", + ), + custom=dict( + pretrain="pretrained/invslowfast101_k400_pre_k400_ft_e30.pth", + post_processing_pipeline=[ + dict(type="Reduce", keys=["feats"], ops="b t c tt h w -> b c tt", reduction="mean"), + dict(type="Interpolate", keys=["feats"], size=resize_length), + ], + norm_eval=True, # set all norm layers to eval mode, default is True + freeze_backbone=False, # whether to freeze the backbone, default is False + ), + ), + projection=dict( + in_channels=2304, + out_channels=256, + attn_cfg=dict(n_mha_win_size=-1), + use_abs_pe=True, + max_seq_len=resize_length, + ), + neck=dict(in_channels=256, out_channels=256), + rpn_head=dict( + in_channels=256, + feat_channels=256, + num_classes=1, + label_smoothing=0.1, + loss_weight=2.0, + loss_normalizer=200, + ), +) + +solver = dict( + train=dict(batch_size=8, num_workers=4), + val=dict(batch_size=8, num_workers=4), + test=dict(batch_size=8, num_workers=4), + clip_grad_norm=1, + amp=True, + fp16_compress=True, + static_graph=True, + ema=True, +) + +optimizer = dict( + type="AdamW", + lr=1e-3, + weight_decay=0.05, + paramwise=True, + backbone=dict(lr=1e-5, weight_decay=0.05), +) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=15) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.7, + max_seg_num=100, + min_score=0.001, + multiclass=False, + voting_thresh=0.9, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=100, + checkpoint_interval=1, + val_loss_interval=-1, # do not validate during end-to-end training, waste time + val_eval_interval=1, + val_start_epoch=8, +) + +work_dir = "exps/anet/re2tal_e2e_actionformer_slowfast101_frame768" diff --git a/OpenTAD/configs/re2tal/e2e_anet_re2tal_actionformer_swin_tiny.py b/OpenTAD/configs/re2tal/e2e_anet_re2tal_actionformer_swin_tiny.py new file mode 100644 index 0000000000000000000000000000000000000000..7b28f24a080483e431fddc3be20fe30e639be4dc --- /dev/null +++ b/OpenTAD/configs/re2tal/e2e_anet_re2tal_actionformer_swin_tiny.py @@ -0,0 +1,155 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/e2e_resize_768_1x224x224.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +resize_length = 192 +dataset = dict( + train=dict( + resize_length=resize_length, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize", scale_factor=4), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 256)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(224, 224), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.ImgAug", transforms="default"), + dict(type="mmaction.ColorJitter"), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + resize_length=resize_length, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize", scale_factor=4), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + resize_length=resize_length, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4", prefix="v_"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="resize", scale_factor=4), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs"]), + dict(type="Collect", inputs="imgs", keys=["masks"]), + ], + ), +) + +model = dict( + backbone=dict( + type="mmaction.Recognizer3D", + backbone=dict( + type="SwinTransformer3D_inv", + patch_size=(2, 4, 4), + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=(8, 7, 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, + patch_norm=True, + inv_mode=["custom_backprop", "custom_backprop", "custom_backprop", "custom_backprop"], + ), + data_preprocessor=dict( + type="mmaction.ActionDataPreprocessor", + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + format_shape="NCTHW", + ), + custom=dict( + pretrain="pretrained/invswin-tiny-p244-w877_kinetics400_pre_k400_ft_e30.pth", + post_processing_pipeline=[ + dict(type="Reduce", keys=["feats"], ops="b t c tt h w -> b c tt", reduction="mean"), + dict(type="Interpolate", keys=["feats"], size=resize_length), + ], + norm_eval=True, # set all norm layers to eval mode, default is True + freeze_backbone=False, # whether to freeze the backbone, default is False + ), + ), + projection=dict( + in_channels=768, + out_channels=256, + attn_cfg=dict(n_mha_win_size=-1), + use_abs_pe=True, + max_seq_len=resize_length, + ), + neck=dict(in_channels=256, out_channels=256), + rpn_head=dict( + in_channels=256, + feat_channels=256, + num_classes=1, + label_smoothing=0.1, + loss_weight=2.0, + loss_normalizer=200, + ), +) + +solver = dict( + train=dict(batch_size=8, num_workers=4), + val=dict(batch_size=8, num_workers=4), + test=dict(batch_size=8, num_workers=4), + clip_grad_norm=1, + amp=True, + fp16_compress=True, + static_graph=True, + ema=True, +) + +optimizer = dict( + type="AdamW", + lr=1e-3, + weight_decay=0.05, + paramwise=True, + backbone=dict(lr=1e-5, weight_decay=0.05), +) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=15) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.7, + max_seg_num=100, + min_score=0.001, + multiclass=False, + voting_thresh=0.9, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=100, + checkpoint_interval=1, + val_loss_interval=-1, # do not validate during end-to-end training, waste time + val_eval_interval=1, + val_start_epoch=8, +) + +work_dir = "exps/anet/re2tal_e2e_actionformer_swin_tiny_frame768" diff --git a/OpenTAD/configs/re2tal/e2e_thumos_re2tal_actionformer_slowfast101.py b/OpenTAD/configs/re2tal/e2e_thumos_re2tal_actionformer_slowfast101.py new file mode 100644 index 0000000000000000000000000000000000000000..3c42802a55bf661e242295ef4b8f555c4129506e --- /dev/null +++ b/OpenTAD/configs/re2tal/e2e_thumos_re2tal_actionformer_slowfast101.py @@ -0,0 +1,162 @@ +_base_ = [ + "../_base_/datasets/thumos-14/e2e_train_trunc_test_sw_256x224x224.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +window_size = 512 +dataset = dict( + train=dict( + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict( + type="LoadFrames", + num_clips=1, + method="random_trunc", + trunc_len=window_size, + trunc_thresh=0.75, + crop_ratio=[0.9, 1.0], + scale_factor=2, + ), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 256)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(224, 224), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.ImgAug", transforms="default"), + dict(type="mmaction.ColorJitter"), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + window_size=window_size, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window", scale_factor=2), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + window_size=window_size, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window", scale_factor=2), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs"]), + dict(type="Collect", inputs="imgs", keys=["masks"]), + ], + ), +) + +model = dict( + backbone=dict( + type="mmaction.Recognizer3D", + backbone=dict( + type="ResNet3dSlowFast_inv", + pretrained=None, + pretrain_type="inv_resnet_3d", + resample_rate=4, # tau + speed_ratio=4, # alpha + channel_ratio=8, # beta_inv + slow_pathway=dict( + type="resnet3d", + depth=101, + pretrained=None, + lateral=True, + fusion_kernel=7, + conv1_kernel=(1, 7, 7), + dilations=(1, 1, 1, 1), + conv1_stride_t=1, + pool1_stride_t=1, + inflate=(0, 0, 1, 1), + norm_eval=True, + frozen_stages=-1, + ), + fast_pathway=dict( + type="resnet3d", + depth=101, + pretrained=None, + lateral=False, + base_channels=8, + conv1_kernel=(5, 7, 7), + conv1_stride_t=1, + pool1_stride_t=1, + norm_eval=True, + frozen_stages=-1, + ), + inv_mode=["custom_backprop", "custom_backprop", "custom_backprop", "custom_backprop"], + ), + data_preprocessor=dict( + type="mmaction.ActionDataPreprocessor", + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + format_shape="NCTHW", + ), + custom=dict( + pretrain="pretrained/invslowfast101_k400_pre_k400_ft_e30.pth", + post_processing_pipeline=[ + dict(type="Reduce", keys=["feats"], ops="b t c tt h w -> b c tt", reduction="mean"), + dict(type="Interpolate", keys=["feats"], size=window_size), + ], + norm_eval=True, # set all norm layers to eval mode, default is True + freeze_backbone=False, # whether to freeze the backbone, default is False + ), + ), + projection=dict(in_channels=2304, max_seq_len=window_size, attn_cfg=dict(n_mha_win_size=-1)), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=2, num_workers=2), + test=dict(batch_size=2, num_workers=2), + clip_grad_norm=1, + amp=True, + fp16_compress=True, + static_graph=True, + ema=True, +) + +optimizer = dict( + type="AdamW", + lr=1e-4, + weight_decay=0.05, + paramwise=True, + backbone=dict(lr=1e-5, weight_decay=0.05), +) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=1500) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.7, + max_seg_num=2000, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=50, + checkpoint_interval=5, + val_loss_interval=-1, + val_eval_interval=5, + val_start_epoch=79, + end_epoch=120, +) + +work_dir = "exps/thumos/re2tal_e2e_actionformer_slowfast101_frame1024" diff --git a/OpenTAD/configs/re2tal/e2e_thumos_re2tal_actionformer_swin_tiny.py b/OpenTAD/configs/re2tal/e2e_thumos_re2tal_actionformer_swin_tiny.py new file mode 100644 index 0000000000000000000000000000000000000000..7a6f9d0a9e31c26e506bf23c96fde3513525c808 --- /dev/null +++ b/OpenTAD/configs/re2tal/e2e_thumos_re2tal_actionformer_swin_tiny.py @@ -0,0 +1,143 @@ +_base_ = [ + "../_base_/datasets/thumos-14/e2e_train_trunc_test_sw_256x224x224.py", # dataset config + "../_base_/models/actionformer.py", # model config +] + +window_size = 512 +dataset = dict( + train=dict( + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict( + type="LoadFrames", + num_clips=1, + method="random_trunc", + trunc_len=window_size, + trunc_thresh=0.75, + crop_ratio=[0.9, 1.0], + scale_factor=2, + ), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 256)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(224, 224), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.ImgAug", transforms="default"), + dict(type="mmaction.ColorJitter"), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + window_size=window_size, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window", scale_factor=2), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + window_size=window_size, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window", scale_factor=2), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 224)), + dict(type="mmaction.CenterCrop", crop_size=224), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs"]), + dict(type="Collect", inputs="imgs", keys=["masks"]), + ], + ), +) + +model = dict( + backbone=dict( + type="mmaction.Recognizer3D", + backbone=dict( + type="SwinTransformer3D_inv", + patch_size=(2, 4, 4), + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=(8, 7, 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, + patch_norm=True, + inv_mode=["custom_backprop", "custom_backprop", "custom_backprop", "custom_backprop"], + ), + data_preprocessor=dict( + type="mmaction.ActionDataPreprocessor", + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + format_shape="NCTHW", + ), + custom=dict( + pretrain="pretrained/invswin-tiny-p244-w877_kinetics400_pre_k400_ft_e30.pth", + post_processing_pipeline=[ + dict(type="Reduce", keys=["feats"], ops="b t c tt h w -> b c tt", reduction="mean"), + dict(type="Interpolate", keys=["feats"], size=window_size), + ], + norm_eval=True, # set all norm layers to eval mode, default is True + freeze_backbone=False, # whether to freeze the backbone, default is False + ), + ), + projection=dict(in_channels=768, max_seq_len=window_size, attn_cfg=dict(n_mha_win_size=-1)), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=2, num_workers=2), + test=dict(batch_size=2, num_workers=2), + clip_grad_norm=1, + amp=True, + fp16_compress=True, + static_graph=True, + ema=True, +) + +optimizer = dict( + type="AdamW", + lr=1e-4, + weight_decay=0.05, + paramwise=True, + backbone=dict(lr=1e-5, weight_decay=0.05), +) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=1500) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.7, + max_seg_num=2000, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=50, + checkpoint_interval=5, + val_loss_interval=-1, + val_eval_interval=5, + val_start_epoch=79, + end_epoch=120, +) + +work_dir = "exps/thumos/re2tal_e2e_actionformer_swin_tiny_frame1024" diff --git a/OpenTAD/configs/tadtr/README.md b/OpenTAD/configs/tadtr/README.md new file mode 100644 index 0000000000000000000000000000000000000000..68f9afc1f9905aec66dc4d1af5503db5f0a3be95 --- /dev/null +++ b/OpenTAD/configs/tadtr/README.md @@ -0,0 +1,77 @@ +# TadTR + +> [End-to-end Temporal Action Detection with Transformer](https://arxiv.org/abs/2106.10271) +> Xiaolong Liu, Qimeng Wang, Yao Hu, Xu Tang, Shiwei Zhang, Song Bai, Xiang Bai + + +> [An Empirical Study of End-to-End Temporal Action Detection](https://arxiv.org/abs/2204.02932) +> Xiaolong Liu, Song Bai, Xiang Bai + + +## Results and Models + +**THUMOS-14** + +| Feature | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :-----: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :---------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| I3D | 71.90 | 67.29 | 59.00 | 48.34 | 34.61 | 56.23 | [config](thumos_i3d.py) | [model](https://drive.google.com/file/d/1XIx_Xu0Xv836YZzO7MRfhDSlA8si48hU/view?usp=sharing) \| [log](https://drive.google.com/file/d/1vgFQZhZLatMgPfaW6BBa96s02zRud7zj/view?usp=sharing) | + +| Backbone | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :------------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :----------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| E2E-SlowFasR50 | 64.47 | 59.49 | 53.11 | 44.08 | 33.50 | 50.93 | [config](e2e_thumos_tadtr_slowfast50_sw128s6.py) | [model](https://drive.google.com/file/d/1vxZauOM_LgRMMpYJefK_FUg3gpHBIz9k/view?usp=sharing) \| [log](https://drive.google.com/file/d/1CWcfqxALPPNVHoud8g9MnNRa14lDxh0o/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train TadTR on THUMOS dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/tadtr/thumos_i3d.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test TadTR on THUMOS dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/tadtr/thumos_i3d.py --checkpoint exps/thumos/tridet_i3d/gpu1_id0/checkpoint/epoch_14.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + + +## Citation + +```latex +@article{liu2022end, + title={End-to-end temporal action detection with transformer}, + author={Liu, Xiaolong and Wang, Qimeng and Hu, Yao and Tang, Xu and Zhang, Shiwei and Bai, Song and Bai, Xiang}, + journal={IEEE Transactions on Image Processing}, + volume={31}, + pages={5427--5441}, + year={2022}, + publisher={IEEE} +} + +@inproceedings{liu2022empirical, + title={An empirical study of end-to-end temporal action detection}, + author={Liu, Xiaolong and Bai, Song and Bai, Xiang}, + booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, + pages={20010--20019}, + year={2022} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/tadtr/e2e_thumos_tadtr_slowfast50_sw128s6.py b/OpenTAD/configs/tadtr/e2e_thumos_tadtr_slowfast50_sw128s6.py new file mode 100644 index 0000000000000000000000000000000000000000..9bfd20202f31a9f5497817fc8ab2ce409e657f74 --- /dev/null +++ b/OpenTAD/configs/tadtr/e2e_thumos_tadtr_slowfast50_sw128s6.py @@ -0,0 +1,148 @@ +_base_ = [ + "../_base_/datasets/thumos-14/e2e_sw_256x224x224.py", # dataset config + "../_base_/models/tadtr.py", # model config +] + +window_size = 128 +dataset = dict( + train=dict( + feature_stride=6, + window_overlap_ratio=0.25, + window_size=window_size, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window", scale_factor=2), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 110)), + dict(type="mmaction.RandomResizedCrop"), + dict(type="mmaction.Resize", scale=(96, 96), keep_ratio=False), + dict(type="mmaction.Flip", flip_ratio=0.5), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + feature_stride=6, + window_overlap_ratio=0.25, + window_size=window_size, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window", scale_factor=2), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 96)), + dict(type="mmaction.CenterCrop", crop_size=96), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs", "gt_segments", "gt_labels"]), + dict(type="Collect", inputs="imgs", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + feature_stride=6, + window_overlap_ratio=0.75, + window_size=window_size, + pipeline=[ + dict(type="PrepareVideoInfo", format="mp4"), + dict(type="mmaction.DecordInit", num_threads=4), + dict(type="LoadFrames", num_clips=1, method="sliding_window", scale_factor=2), + dict(type="mmaction.DecordDecode"), + dict(type="mmaction.Resize", scale=(-1, 96)), + dict(type="mmaction.CenterCrop", crop_size=96), + dict(type="mmaction.FormatShape", input_format="NCTHW"), + dict(type="ConvertToTensor", keys=["imgs"]), + dict(type="Collect", inputs="imgs", keys=["masks"]), + ], + ), +) + +model = dict( + backbone=dict( + type="mmaction.Recognizer3D", + backbone=dict( + type="mmaction.ResNet3dSlowFast", + pretrained=None, + resample_rate=8, # tau + speed_ratio=8, # alpha + channel_ratio=8, # beta_inv + slow_pathway=dict( + type="resnet3d", + depth=50, + pretrained=None, + lateral=True, + conv1_kernel=(1, 7, 7), + dilations=(1, 1, 1, 1), + conv1_stride_t=1, + pool1_stride_t=1, + inflate=(0, 0, 1, 1), + norm_eval=True, + ), + fast_pathway=dict( + type="resnet3d", + depth=50, + pretrained=None, + lateral=False, + base_channels=8, + conv1_kernel=(5, 7, 7), + conv1_stride_t=1, + pool1_stride_t=1, + norm_eval=True, + ), + ), + data_preprocessor=dict( + type="mmaction.ActionDataPreprocessor", + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + format_shape="NCTHW", + ), + custom=dict( + pretrain="https://download.openmmlab.com/mmaction/v1.0/recognition/slowfast/slowfast_r50_8xb8-4x16x1-256e_kinetics400-rgb/slowfast_r50_8xb8-4x16x1-256e_kinetics400-rgb_20220901-701b0f6f.pth", + post_processing_pipeline=[ + dict(type="Reduce", keys=["feats"], ops="b t c tt h w -> b c tt", reduction="mean"), + dict(type="Interpolate", keys=["feats"], size=window_size), + ], + norm_eval=True, # set all norm layers to eval mode, default is True + freeze_backbone=False, # whether to freeze the backbone, default is False + ), + ), + projection=dict(in_channels=2304), +) + +solver = dict( + train=dict(batch_size=4, num_workers=4), + val=dict(batch_size=4, num_workers=4), + test=dict(batch_size=4, num_workers=0), + clip_grad_norm=0.1, +) + +optimizer = dict( + type="AdamW", + lr=1e-4, + weight_decay=1e-4, + paramwise=True, + backbone=dict(lr=5e-6, weight_decay=1e-4), +) +scheduler = dict(type="MultiStepLR", milestones=[14], gamma=0.1, max_epoch=17) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.4, + max_seg_num=2000, + multiclass=True, + voting_thresh=0.95, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=100, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=8, +) + +work_dir = "exps/thumos/tadtr_e2e_slowfast50_sw128s6" diff --git a/OpenTAD/configs/tadtr/thumos_i3d.py b/OpenTAD/configs/tadtr/thumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..0e786a5cf16cae9d4ab4e1efdfece4bf457d6223 --- /dev/null +++ b/OpenTAD/configs/tadtr/thumos_i3d.py @@ -0,0 +1,42 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_i3d_sw.py", + "../_base_/models/tadtr.py", +] + +dataset = dict( + train=dict(window_size=256, window_overlap_ratio=0.25), + val=dict(window_size=256, window_overlap_ratio=0.25), + test=dict(window_size=256, window_overlap_ratio=0.75), +) + +solver = dict( + train=dict(batch_size=8, num_workers=4), + val=dict(batch_size=8, num_workers=4), + test=dict(batch_size=8, num_workers=4), + clip_grad_norm=0.1, +) + +optimizer = dict(type="AdamW", lr=2e-4, weight_decay=1e-4, paramwise=True) +scheduler = dict(type="MultiStepLR", milestones=[14], gamma=0.1, max_epoch=17) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.4, + max_seg_num=2000, + multiclass=True, + voting_thresh=0.95, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=300, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=12, +) + +work_dir = "exps/thumos/tadtr_i3d" diff --git a/OpenTAD/configs/temporalmaxer/README.md b/OpenTAD/configs/temporalmaxer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c7660af4b87a9800084569670995837c29f212e0 --- /dev/null +++ b/OpenTAD/configs/temporalmaxer/README.md @@ -0,0 +1,78 @@ +# TemporalMaxer + +> [TemporalMaxer: Maximize Temporal Context with only Max Pooling for Temporal Action Localization](https://arxiv.org/abs/2303.09055) +> Tuan N. Tang, Kwonyoung Kim, Kwanghoon Sohn + + + +## Abstract + +Temporal Action Localization (TAL) is a challenging task in video understanding that aims to identify and localize actions within a video sequence. Recent studies have emphasized the importance of applying long-term temporal context modeling (TCM) blocks to the extracted video clip features such as employing complex self-attention mechanisms. In this paper, we present the simplest method ever to address this task and argue that the extracted video clip features are already informative to achieve outstanding performance without sophisticated architectures. To this end, we introduce TemporalMaxer, which minimizes long-term temporal context modeling while maximizing information from the extracted video clip features with a basic, parameter-free, and local region operating max-pooling block. Picking out only the most critical information for adjacent and local clip embeddings, this block results in a more efficient TAL model. We demonstrate that TemporalMaxer outperforms other state-of-the-art methods that utilize long-term TCM such as self-attention on various TAL datasets while requiring significantly fewer parameters and computational resources. The code for our approach is publicly available at https://github.com/TuanTNG/TemporalMaxer. + +## Results and Models + +**Note:** TemporalMaxer needs more than 40 GB GPU memory when training on Multi-THUMOS and Epic-kitchen. + +**THUMOS-14** + +| Features | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :---------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| I3D | 83.17 | 79.09 | 71.66 | 61.72 | 46.00 | 68.33 | [config](thumos_i3d.py) | [model](https://drive.google.com/file/d/1Qh1CBphRbU0R07FRLk1nkQ_g53na6WLv/view?usp=sharing) \| [log](https://drive.google.com/file/d/1jQPUKp4X1amda1NJ2AuzK1SDxiT7pbxc/view?usp=sharing) | + +**MultiTHUMOS** + +| Features | mAP@0.2 | mAP@0.5 | mAP@0.7 | ave. mAP (0.1:0.9:0.1) | Config | Download | +| :------------: | :-----: | :-----: | :-----: | :--------------------: | :------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| I3D (rgb) | 53.55 | 38.38 | 20.60 | 33.91 | [config](multithumos_i3d_rgb.py) | [model](https://drive.google.com/file/d/1l2YnyNx_nYjGH-y-eEV62wsQ7DUR-qmo/view?usp=sharing) \| [log](https://drive.google.com/file/d/1YuTjv89l-A4mmUafuZVZtuKEQ22mUL29/view?usp=sharing) | +| I3D (rgb+flow) | 60.30 | 44.92 | 25.45 | 39.32 | [config](multithumos_i3d.py) | [model](https://drive.google.com/file/d/1n1ZMSmn3mRmrF4CFYFoLTq8M3pRhtLcF/view?usp=sharing) \| [log](https://drive.google.com/file/d/1mc1JifZDfqfvX6cjChE8O3vKtgCf_TbC/view?usp=sharing) | + +**Epic-Kitchens-100** + +| Subset | Features | mAP@0.1 | mAP@0.2 | mAP@0.3 | mAP@0.4 | mAP@0.5 | ave. mAP | Config | Download | +| :----: | :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :--------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| Noun | SlowFast | 25.46 | 24.35 | 22.55 | 20.32 | 17.08 | 21.96 | [config](epic_kitchens_slowfast_noun.py) | [model](https://drive.google.com/file/d/17Iuc5RHMje1BW8XnECIkeKX7q_BNvNXo/view?usp=sharing) \| [log](https://drive.google.com/file/d/1taY9F7x2avb0jTRsiGdwCNepuYQ9wi9u/view?usp=sharing) | +| Verb | SlowFast | 28.64 | 27.84 | 25.59 | 23.60 | 19.69 | 25.07 | [config](epic_kitchens_slowfast_verb.py) | [model](https://drive.google.com/file/d/1OaECxAV_HS6WBTb30tZFFczhLziRVYdW/view?usp=sharing) \| [log](https://drive.google.com/file/d/1LUR5vfzAcTW5WzDB1u3GPZgOfQ0HOF_3/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train TemporalMaxer on THUMOS dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/temporalmaxer/thumos_i3d.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test TemporalMaxer on THUMOS dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/temporalmaxer/thumos_i3d.py --checkpoint exps/thumos/temporalmaxer_i3d/gpu1_id0/checkpoint/epoch_45.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + +## Citation + +```latex +@article{tang2023temporalmaxer, + title={TemporalMaxer: Maximize Temporal Context with only Max Pooling for Temporal Action Localization}, + author={Tang, Tuan N and Kim, Kwonyoung and Sohn, Kwanghoon}, + journal={arXiv preprint arXiv:2303.09055}, + year={2023} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/temporalmaxer/epic_kitchens_slowfast_noun.py b/OpenTAD/configs/temporalmaxer/epic_kitchens_slowfast_noun.py new file mode 100644 index 0000000000000000000000000000000000000000..91bd4552ba80ede9c9ca26d8803b3c2b5ce365de --- /dev/null +++ b/OpenTAD/configs/temporalmaxer/epic_kitchens_slowfast_noun.py @@ -0,0 +1,54 @@ +_base_ = [ + "../_base_/datasets/epic_kitchens-100/features_slowfast_noun.py", # dataset config + "../_base_/models/temporalmaxer.py", # model config +] + +model = dict( + projection=dict(in_channels=2304), + neck=dict(norm_cfg=dict(type="GN", num_groups=4, affine=False)), + rpn_head=dict( + num_classes=293, # total 300, but 7 classes are empty + prior_generator=dict( + strides=[1, 2, 4, 8, 16, 32], + regression_range=[(0, 4), (2, 8), (4, 16), (8, 32), (16, 64), (32, 10000)], + ), + loss_normalizer=250, + ), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=35) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=5000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.4, + max_seg_num=2000, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=True, + voting_thresh=0.75, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=15, +) + +work_dir = "exps/epic_kitchens/temporalmaxer_slowfast_noun" diff --git a/OpenTAD/configs/temporalmaxer/epic_kitchens_slowfast_verb.py b/OpenTAD/configs/temporalmaxer/epic_kitchens_slowfast_verb.py new file mode 100644 index 0000000000000000000000000000000000000000..ca58b754f603fafa218a4ef38ec11df4d66e0d8d --- /dev/null +++ b/OpenTAD/configs/temporalmaxer/epic_kitchens_slowfast_verb.py @@ -0,0 +1,53 @@ +_base_ = [ + "../_base_/datasets/epic_kitchens-100/features_slowfast_verb.py", # dataset config + "../_base_/models/temporalmaxer.py", # model config +] + +model = dict( + projection=dict(in_channels=2304), + rpn_head=dict( + num_classes=97, + prior_generator=dict( + strides=[1, 2, 4, 8, 16, 32], + regression_range=[(0, 4), (2, 8), (4, 16), (8, 32), (16, 64), (32, 10000)], + ), + loss_normalizer=250, + ), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=35) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=5000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.4, + max_seg_num=2000, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=True, + voting_thresh=0.75, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=15, +) + +work_dir = "exps/epic_kitchens/temporalmaxer_slowfast_verb" diff --git a/OpenTAD/configs/temporalmaxer/multithumos_i3d.py b/OpenTAD/configs/temporalmaxer/multithumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..524f7c937d45812e8490680cd50d1b162bee5821 --- /dev/null +++ b/OpenTAD/configs/temporalmaxer/multithumos_i3d.py @@ -0,0 +1,46 @@ +_base_ = [ + "../_base_/datasets/multithumos/features_i3d_pad.py", # dataset config + "../_base_/models/temporalmaxer.py", # model config +] + +model = dict( + projection=dict(in_channels=2048, arch=(3, 0, 5)), + rpn_head=dict(num_classes=65), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=65) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=8000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=8000, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=20, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=29, + end_epoch=50, +) + +work_dir = "exps/multithumos/temporalmaxer_i3d" diff --git a/OpenTAD/configs/temporalmaxer/multithumos_i3d_rgb.py b/OpenTAD/configs/temporalmaxer/multithumos_i3d_rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..b17618c9397201bf8709f7178cffb8639cd5ea3f --- /dev/null +++ b/OpenTAD/configs/temporalmaxer/multithumos_i3d_rgb.py @@ -0,0 +1,46 @@ +_base_ = [ + "../_base_/datasets/multithumos/features_i3d_rgb_pad.py", # dataset config + "../_base_/models/temporalmaxer.py", # model config +] + +model = dict( + projection=dict(in_channels=1024, arch=(3, 0, 5)), + rpn_head=dict(num_classes=65), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=65) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=8000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=8000, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=20, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=29, + end_epoch=50, +) + +work_dir = "exps/multithumos/temporalmaxer_i3d_rgb" diff --git a/OpenTAD/configs/temporalmaxer/thumos_i3d.py b/OpenTAD/configs/temporalmaxer/thumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..e5ca512389c94140abf3062ef59bec85b794673e --- /dev/null +++ b/OpenTAD/configs/temporalmaxer/thumos_i3d.py @@ -0,0 +1,47 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_i3d_pad.py", # dataset config + "../_base_/models/temporalmaxer.py", # model config +] + +model = dict( + projection=dict(in_channels=2048, drop_out=0.2), + neck=dict(norm_cfg=dict(type="GN", num_groups=4, affine=False)), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=65) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=2000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=200, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=20, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=39, + end_epoch=50, +) + +work_dir = "exps/thumos/temporalmaxer_i3d" diff --git a/OpenTAD/configs/tridet/README.md b/OpenTAD/configs/tridet/README.md new file mode 100644 index 0000000000000000000000000000000000000000..52760e73ebf1987390119447a5b0dd200013fb43 --- /dev/null +++ b/OpenTAD/configs/tridet/README.md @@ -0,0 +1,83 @@ +# TriDet + +> [TriDet: Temporal Action Detection with Relative Boundary Modeling](https://arxiv.org/abs/2303.07347) +> Dingfeng Shi, Yujie Zhong, Qiong Cao, Lin Ma, Jia Li, Dacheng Tao + + + +## Abstract + +In this paper, we present a one-stage framework TriDet for temporal action detection. Existing methods often suffer from imprecise boundary predictions due to the ambiguous action boundaries in videos. To alleviate this problem, we propose a novel Trident-head to model the action boundary via an estimated relative probability distribution around the boundary. In the feature pyramid of TriDet, we propose an efficient Scalable-Granularity Perception (SGP) layer to mitigate the rank loss problem of self-attention that takes place in the video features and aggregate information across different temporal granularities. Benefiting from the Trident-head and the SGP-based feature pyramid, TriDet achieves state-of-the-art performance on three challenging benchmarks: THUMOS14, HACS and EPIC-KITCHEN 100, with lower computational costs, compared to previous methods. For example, TriDet hits an average mAP of 69.3% on THUMOS14, outperforming the previous best by 2.5%, but with only 74.6% of its latency. + +## Results and Models + +**ActivityNet-1.3** with CUHK classifier. + +| Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :------: | :-----: | :------: | :------: | :------: | :-------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| TSP | 54.84 | 37.46 | 7.98 | 36.51 | [config](anet_tsp.py) | [model](https://drive.google.com/file/d/1qUDzT6xSIKOlx8cHJoYJL8S6eC_c4K3I/view?usp=sharing) \| [log](https://drive.google.com/file/d/1IANbg_ueEg-F75dkgute5BVkUNUUodzX/view?usp=sharing) | + +**THUMOS-14** + +| Features | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :---------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| I3D | 84.46 | 81.05 | 73.41 | 62.58 | 46.51 | 69.60 | [config](thumos_i3d.py) | [model](https://drive.google.com/file/d/18nQ2jJMJkkqeCfWzj-OfV0Hi_Ej3Y1lN/view?usp=sharing) \| [log](https://drive.google.com/file/d/1YLXoZoliAD1jLHa2Lxtct0EFtpgabesM/view?usp=sharing) | + +**HACS** + +| Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :------: | :-----: | :------: | :------: | :------: | :------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| SlowFast | 56.84 | 39.04 | 11.13 | 38.47 | [config](hacs_slowfast.py) | [model](https://drive.google.com/file/d/13e34x-kXRWTm9jNkvv61D10vRdBtRgZ_/view?usp=sharing) \| [log](https://drive.google.com/file/d/1RGwwtenzxiZ5IBw7SdF9V2bFNk5TBZq1/view?usp=sharing) | + +**Epic-Kitchens-100** + +| Subset | Features | mAP@0.1 | mAP@0.2 | mAP@0.3 | mAP@0.4 | mAP@0.5 | ave. mAP | Config | Download | +| :----: | :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :--------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| Noun | SlowFast | 24.95 | 23.76 | 22.22 | 20.00 | 16.63 | 21.51 | [config](epic_kitchens_slowfast_noun.py) | [model](https://drive.google.com/file/d/18F0Ruc9RJL9KLOjIEFvBGBQzXxNUkJgH/view?usp=sharing) \| [log](https://drive.google.com/file/d/1Tfi4KyKmnanO2F3rry1hIRDtlvKZDRTT/view?usp=sharing) | +| Verb | SlowFast | 27.88 | 27.00 | 25.52 | 23.74 | 20.72 | 24.97 | [config](epic_kitchens_slowfast_verb.py) | [model](https://drive.google.com/file/d/1LIGCduQFPXKQl98s53h_feIYNLBsXkXd/view?usp=sharing) \| [log](https://drive.google.com/file/d/10xZSt7r6T_tauqvc9UHi3bCiloZPATDp/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train TriDet on THUMOS dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/tridet/thumos_i3d.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test TriDet on THUMOS dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/tridet/thumos_i3d.py --checkpoint exps/thumos/tridet_i3d/gpu1_id0/checkpoint/epoch_37.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + + +## Citation + +```latex +@inproceedings{shi2023tridet, + title={TriDet: Temporal Action Detection with Relative Boundary Modeling}, + author={Shi, Dingfeng and Zhong, Yujie and Cao, Qiong and Ma, Lin and Li, Jia and Tao, Dacheng}, + booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, + pages={18857--18866}, + year={2023} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/tridet/anet_tsp.py b/OpenTAD/configs/tridet/anet_tsp.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe41b57b47152afac7c5ede73facc6b9d22cdf6 --- /dev/null +++ b/OpenTAD/configs/tridet/anet_tsp.py @@ -0,0 +1,67 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_pad.py", # dataset config + "../_base_/models/tridet.py", # model config +] + +model = dict( + projection=dict( + in_channels=512, + out_channels=256, + sgp_win_size=[15, 15, 15, 15, 15, 15], + sgp_mlp_dim=2048, + use_abs_pe=True, + max_seq_len=768, + k=1.3, + init_conv_vars=0.2, + input_noise=0.5, + ), + neck=dict(in_channels=256, out_channels=256), + rpn_head=dict( + in_channels=256, + num_classes=1, + label_smoothing=0.1, + loss_normalizer=400, + iou_weight_power=1, + num_bins=12, + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=0.4, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=0.04, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=10, max_epoch=15, eta_min=5e-5) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.7, + max_seg_num=200, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=7, +) + +work_dir = "exps/anet/tridet_tsp" diff --git a/OpenTAD/configs/tridet/epic_kitchens_slowfast_noun.py b/OpenTAD/configs/tridet/epic_kitchens_slowfast_noun.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b5104eecb3f326064bf97c824c901a364a627c --- /dev/null +++ b/OpenTAD/configs/tridet/epic_kitchens_slowfast_noun.py @@ -0,0 +1,59 @@ +_base_ = [ + "../_base_/datasets/epic_kitchens-100/features_slowfast_noun.py", # dataset config + "../_base_/models/tridet.py", # model config +] + +model = dict( + projection=dict( + in_channels=2304, + sgp_mlp_dim=1024, + k=4, + ), + rpn_head=dict( + num_classes=293, # total 300, but 7 classes are empty + prior_generator=dict( + strides=[1, 2, 4, 8, 16, 32], + regression_range=[(0, 4), (2, 8), (4, 16), (8, 32), (16, 64), (32, 10000)], + ), + label_smoothing=0.1, + loss_normalizer=250, + iou_weight_power=0.25, + ), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=20) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=5000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.4, + max_seg_num=2000, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=True, + voting_thresh=0.75, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=15, +) + +work_dir = "exps/epic_kitchens/tridet_slowfast_noun" diff --git a/OpenTAD/configs/tridet/epic_kitchens_slowfast_verb.py b/OpenTAD/configs/tridet/epic_kitchens_slowfast_verb.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8214b41cf928f15fba5d54c50aed125090675f --- /dev/null +++ b/OpenTAD/configs/tridet/epic_kitchens_slowfast_verb.py @@ -0,0 +1,59 @@ +_base_ = [ + "../_base_/datasets/epic_kitchens-100/features_slowfast_verb.py", # dataset config + "../_base_/models/tridet.py", # model config +] + +model = dict( + projection=dict( + in_channels=2304, + sgp_mlp_dim=1024, + k=2, + sgp_win_size=[5, 5, 5, 5, 5, 5], + ), + rpn_head=dict( + num_classes=97, + prior_generator=dict( + strides=[1, 2, 4, 8, 16, 32], + regression_range=[(0, 4), (2, 8), (4, 16), (8, 32), (16, 64), (32, 10000)], + ), + loss_normalizer=250, + iou_weight_power=0.25, + ), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=25) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=5000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.4, + max_seg_num=2000, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=True, + voting_thresh=0.75, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=15, +) + +work_dir = "exps/epic_kitchens/tridet_slowfast_verb" diff --git a/OpenTAD/configs/tridet/hacs_slowfast.py b/OpenTAD/configs/tridet/hacs_slowfast.py new file mode 100644 index 0000000000000000000000000000000000000000..e4a3a8bca3bd22c6aca17e30505e10dd865be0e7 --- /dev/null +++ b/OpenTAD/configs/tridet/hacs_slowfast.py @@ -0,0 +1,64 @@ +_base_ = [ + "../_base_/datasets/hacs-1.1.1/features_slowfast_pad.py", # dataset config + "../_base_/models/tridet.py", # model config +] + +model = dict( + projection=dict( + in_channels=2304, + out_channels=1024, + sgp_win_size=[3, 3, 3, 3, 3, 3], + sgp_mlp_dim=1024, + use_abs_pe=True, + max_seq_len=960, + k=1.2, + init_conv_vars=0.1, + input_noise=0.2, + ), + neck=dict(in_channels=1024, out_channels=1024), + rpn_head=dict( + in_channels=1024, + feat_channels=1024, + kernel_size=5, + boundary_kernel_size=1, + num_classes=200, + label_smoothing=0.1, + loss_normalizer=400, + iou_weight_power=1, + num_bins=14, + ), +) +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=0.5, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=0.03, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=7, max_epoch=11, eta_min=5e-4) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.75, + max_seg_num=250, + iou_threshold=0, # does not matter when use soft nms + min_score=0.001, + multiclass=True, + voting_thresh=0.95, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=8, +) + +work_dir = "exps/hacs/tridet_slowfast" diff --git a/OpenTAD/configs/tridet/thumos_i3d.py b/OpenTAD/configs/tridet/thumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..6a17ba6d28b3c105c2ebedb6624243888ea32f1e --- /dev/null +++ b/OpenTAD/configs/tridet/thumos_i3d.py @@ -0,0 +1,40 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_i3d_pad.py", # dataset config + "../_base_/models/tridet.py", # model config +] + +model = dict(projection=dict(in_channels=2048, input_noise=0.0005)) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.025, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=20, max_epoch=40, eta_min=1e-8) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=2000, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=20, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=30, +) + +work_dir = "exps/thumos/tridet_i3d" diff --git a/OpenTAD/configs/tsi/README.md b/OpenTAD/configs/tsi/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2d3a579205570bcf935ff84a1fca4f8e0e920925 --- /dev/null +++ b/OpenTAD/configs/tsi/README.md @@ -0,0 +1,84 @@ +# TSI + +> [TSI: Temporal Scale Invariant Network for Action Proposal Generation](https://openaccess.thecvf.com/content/ACCV2020/papers/Liu_TSI_Temporal_Scale_Invariant_Network_for_Action_Proposal_Generation_ACCV_2020_paper.pdf) +> Shuming Liu, Xu Zhao, Haisheng Su, and Zhilan Hu + + + +## Abstract + +Despite the great progress in temporal action proposal generation, most state-of-the-art methods ignore the impact of action scales and the performance of short actions is still far from satisfaction. In this paper, we first analyze the sample imbalance issue in action proposal generation, and correspondingly devise a novel scale-invariant loss function to alleviate the insufficient learning of short actions. To further achieve proposal generation task, we adopt the pipeline of boundary evaluation and proposal completeness regression, and propose the Temporal Scale Invariant network. To better leverage the temporal context, boundary evaluation module generates action boundaries with high-precision-assured global branch and high-recall-assured local branch. Simultaneously, the proposal evaluation module is supervised with introduced scale-invariant loss, predicting accurate proposal completeness for different scales of actions. Comprehensive experiments are conducted on ActivityNet-1.3 and THUMOS14 benchmarks, where TSI achieves state-of-the-art performance. Especially, AUC performance of short actions is boosted from 36.53% to 39.63% compared with baseline. + +## Results and Models + +**ActivityNet-1.3** with CUHK classifier. + +| Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :------: | :-----: | :------: | :------: | :------: | :-------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| TSN | 49.76 | 33.01 | 9.03 | 32.88 | [config](anet_tsn.py) | [model](https://drive.google.com/file/d/1ErsNd6b9zlxSANmeVoIxDyYxcUOp-mp9/view?usp=sharing) \| [log](https://drive.google.com/file/d/1eQJTYpyu-i9vck7A012FC6p8lSwn_9zi/view?usp=sharing) | +| TSP | 52.44 | 35.57 | 9.80 | 35.36 | [config](anet_tsp.py) | [model](https://drive.google.com/file/d/17U9ZhKGGz7w0SGZB6_EC2hqqFE0YIsKA/view?usp=sharing) \| [log](https://drive.google.com/file/d/1FoDQtL3w-pH-QDDyAtRv2kjnU3ad33LS/view?usp=sharing) | + +Use above checkpoints to evaluate the recall performance: + +| Features | AR@1 | AR@5 | AR@10 | AR@100 | AUC | Config | Download | +| :------: | :---: | :---: | :---: | :----: | :---: | :--------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| TSN | 32.53 | 49.64 | 57.18 | 76.45 | 68.31 | [config](anet_tsn_recall.py) | [model](https://drive.google.com/file/d/1ErsNd6b9zlxSANmeVoIxDyYxcUOp-mp9/view?usp=sharing) \| [log](https://drive.google.com/file/d/1nqfwC-YM6aGP4z9nbWiXZJosHAVjeBho/view?usp=sharing) | +| TSP | 34.12 | 52.03 | 59.45 | 77.20 | 69.72 | [config](anet_tsp_recall.py) | [model](https://drive.google.com/file/d/17U9ZhKGGz7w0SGZB6_EC2hqqFE0YIsKA/view?usp=sharing) \| [log](https://drive.google.com/file/d/1GDneUY9Uu11kI9IKUKK_2G5Fn-P0gh-l/view?usp=sharing) | + + +**THUMOS-14** with UtrimmedNet classifier + +| Features | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :---------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| TSN | 60.37 | 54.38 | 46.14 | 37.05 | 25.81 | 44.75 | [config](thumos_tsn.py) | [model](https://drive.google.com/file/d/1kdo-SkivVdiErhpnIlGQIYcRFl68G9b9/view?usp=sharing) \| [log](https://drive.google.com/file/d/1fscHNUKF0eSULu_w0ww1tiwqDBHwYIL_/view?usp=sharing) | +| I3D | 62.56 | 57.00 | 50.22 | 40.18 | 30.17 | 48.03 | [config](thumos_i3d.py) | [model](https://drive.google.com/file/d/1ivTkvw_2a35iE1vv-u1oHABW4NxvVyTg/view?usp=sharing) \| [log](https://drive.google.com/file/d/1MrzMFdapaPZQjSab-3w05st_EK7suChA/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train TSI on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/tsi/anet_tsp.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test TSI on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/tsi/anet_tsp.py --checkpoint exps/anet/tsi_tsp_128/gpu1_id0/checkpoint/epoch_9.pth +``` + +To test the recal performance: + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/tsi/anet_tsp_recall.py --checkpoint exps/anet/tsi_tsp_128/gpu1_id0/checkpoint/epoch_9.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + +## Citation + +```latex +@inproceedings{liu2020tsi, + title={TSI: Temporal Scale Invariant Network for Action Proposal Generation}, + author={Liu, Shuming and Zhao, Xu and Su, Haisheng and Hu, Zhilan}, + booktitle={Proceedings of the Asian Conference on Computer Vision}, + year={2020} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/tsi/anet_tsn.py b/OpenTAD/configs/tsi/anet_tsn.py new file mode 100644 index 0000000000000000000000000000000000000000..952d73b3a6e6c2f1df08fa1f2c4e2f800b021f4d --- /dev/null +++ b/OpenTAD/configs/tsi/anet_tsn.py @@ -0,0 +1,50 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize.py", # dataset config + "../_base_/models/tsi.py", # model config +] + +data_path = "data/activitynet-1.3/features/anet_tsn_npy_unresize/" +block_list = "data/activitynet-1.3/features/anet_tsn_npy_unresize/missing_files.txt" +dataset = dict( + train=dict(data_path=data_path, block_list=block_list), + val=dict(data_path=data_path, block_list=block_list), + test=dict(data_path=data_path, block_list=block_list), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-3, weight_decay=1e-4, paramwise=True) +scheduler = dict(type="MultiStepLR", milestones=[7], gamma=0.1, max_epoch=10) + +inference = dict(test_epoch=7, load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=100, + min_score=0, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=7, +) + +work_dir = "exps/anet/tsi_tsn_128" diff --git a/OpenTAD/configs/tsi/anet_tsn_recall.py b/OpenTAD/configs/tsi/anet_tsn_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..cca951183f3ba637f7354d2a61edbdb9aca44f79 --- /dev/null +++ b/OpenTAD/configs/tsi/anet_tsn_recall.py @@ -0,0 +1,27 @@ +_base_ = ["anet_tsn.py"] + +evaluation = dict( + type="Recall", + subset="validation", + topk=[1, 5, 10, 100], + max_avg_nr_proposals=100, + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], +) + +post_processing = dict( + score_type="iou*s*e", + proposal=True, + nms=dict( + use_soft_nms=True, + sigma=0.35, + max_seg_num=100, + min_score=0, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + method=3, + t1=0.55, + t2=0.37, + ), + external_cls=dict(_delete_=True, type="PseudoClassifier"), + save_dict=False, +) diff --git a/OpenTAD/configs/tsi/anet_tsp.py b/OpenTAD/configs/tsi/anet_tsp.py new file mode 100644 index 0000000000000000000000000000000000000000..af003686bf668bf388c35f365a12960cbb168a20 --- /dev/null +++ b/OpenTAD/configs/tsi/anet_tsp.py @@ -0,0 +1,44 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize.py", # dataset config + "../_base_/models/tsi.py", # model config +] + +model = dict(projection=dict(in_channels=512)) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-3, weight_decay=1e-4, paramwise=True) +scheduler = dict(type="MultiStepLR", milestones=[7], gamma=0.1, max_epoch=10) + +inference = dict(test_epoch=7, load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=100, + min_score=0, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=7, +) + +work_dir = "exps/anet/tsi_tsp_128" diff --git a/OpenTAD/configs/tsi/anet_tsp_recall.py b/OpenTAD/configs/tsi/anet_tsp_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..28076028aa4bcf02ded6784a94a2e9e05fb84ed9 --- /dev/null +++ b/OpenTAD/configs/tsi/anet_tsp_recall.py @@ -0,0 +1,27 @@ +_base_ = ["anet_tsp.py"] + +evaluation = dict( + type="Recall", + subset="validation", + topk=[1, 5, 10, 100], + max_avg_nr_proposals=100, + tiou_thresholds=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95], +) + +post_processing = dict( + score_type="iou*s*e", + proposal=True, + nms=dict( + use_soft_nms=True, + sigma=0.35, + max_seg_num=100, + min_score=0, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + method=3, + t1=0.55, + t2=0.37, + ), + external_cls=dict(_delete_=True, type="PseudoClassifier"), + save_dict=False, +) diff --git a/OpenTAD/configs/tsi/thumos_i3d.py b/OpenTAD/configs/tsi/thumos_i3d.py new file mode 100644 index 0000000000000000000000000000000000000000..63cc55cb39584cad3c51326e0e16cdecca57f1b1 --- /dev/null +++ b/OpenTAD/configs/tsi/thumos_i3d.py @@ -0,0 +1,68 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_i3d_sw.py", # dataset config + "../_base_/models/tsi.py", # model config +] + +window_size = 128 +dataset = dict( + train=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + val=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + test=dict( + window_size=window_size, + window_overlap_ratio=0.5, + ), +) + +model = dict( + projection=dict(in_channels=2048), + roi_head=dict( + proposal_generator=dict(dscale=64, tscale=128), + proposal_roi_extractor=dict(dscale=64, tscale=128), + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-4, weight_decay=1e-4, paramwise=True) +scheduler = dict(type="MultiStepLR", milestones=[5], gamma=0.1, max_epoch=8) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.3, + max_seg_num=200, + min_score=0.0001, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="UntrimmedNetTHUMOSClassifier", + path="data/thumos-14/classifiers/uNet_test.npy", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=5, +) + +work_dir = "exps/thumos/tsi_i3d_sw128" diff --git a/OpenTAD/configs/tsi/thumos_tsn.py b/OpenTAD/configs/tsi/thumos_tsn.py new file mode 100644 index 0000000000000000000000000000000000000000..c61df25221e1b7ff0b11551d67f7dca5eea08f6f --- /dev/null +++ b/OpenTAD/configs/tsi/thumos_tsn.py @@ -0,0 +1,74 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_tsn_sw.py", # dataset config + "../_base_/models/tsi.py", # model config +] + +window_size = 128 +dataset = dict( + train=dict( + feature_stride=1, + sample_stride=5, + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + val=dict( + feature_stride=1, + sample_stride=5, + window_size=window_size, + window_overlap_ratio=0.5, + ioa_thresh=0.9, + ), + test=dict( + feature_stride=1, + sample_stride=5, + window_size=window_size, + window_overlap_ratio=0.5, + ), +) + +model = dict( + projection=dict(in_channels=2048), + roi_head=dict( + proposal_generator=dict(dscale=64, tscale=128), + proposal_roi_extractor=dict(dscale=64, tscale=128), + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="Adam", lr=1e-4, weight_decay=1e-4, paramwise=True) +scheduler = dict(type="MultiStepLR", milestones=[5], gamma=0.1, max_epoch=8) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.3, + max_seg_num=200, + min_score=0.0001, + multiclass=False, + voting_thresh=0.95, # set 0 to disable + ), + external_cls=dict( + type="UntrimmedNetTHUMOSClassifier", + path="data/thumos-14/classifiers/uNet_test.npy", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=-1, + val_eval_interval=1, + val_start_epoch=5, +) + +work_dir = "exps/thumos/tsi_tsn_sw128" diff --git a/OpenTAD/configs/videomambasuite/README.md b/OpenTAD/configs/videomambasuite/README.md new file mode 100644 index 0000000000000000000000000000000000000000..67bc9aedc047a0e395ae04f351f98939b447ad8b --- /dev/null +++ b/OpenTAD/configs/videomambasuite/README.md @@ -0,0 +1,97 @@ +# Video Mamba Suite + +> [Video Mamba Suite: State Space Model as a Versatile Alternative for Video Understanding](https://arxiv.org/abs/2403.09626) +> Guo Chen, Yifei Huang, Jilan Xu, Baoqi Pei, Zhe Chen, Zhiqi Li, Jiahao Wang, Kunchang Li, Tong Lu, Limin Wang + + + +## Abstract + +Understanding videos is one of the fundamental directions in computer vision research, with extensive efforts dedicated to exploring various architectures such as RNN, 3D CNN, and Transformers. The newly proposed architecture of state space model, e.g., Mamba, shows promising traits to extend its success in long sequence modeling to video modeling. To assess whether Mamba can be a viable alternative to Transformers in the video understanding domain, in this work, we conduct a comprehensive set of studies, probing different roles Mamba can play in modeling videos, while investigating diverse tasks where Mamba could exhibit superiority. We categorize Mamba into four roles for modeling videos, deriving a Video Mamba Suite composed of 14 models/modules, and evaluating them on 12 video understanding tasks. Our extensive experiments reveal the strong potential of Mamba on both video-only and video-language tasks while showing promising efficiency-performance trade-offs. We hope this work could provide valuable data points and insights for future research on video understanding. + +## Usage + +Before running the TAD experiments, go to [video-mamba-suite official repo](https://github.com/OpenGVLab/video-mamba-suite?tab=readme-ov-file#preliminary-installation) and install the mamba module as the library. + + +## Results and Models + +**ActivityNet-1.3** with InternVideo2 classifier. + +| Features | Setting | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :-------------: | :-----: | :-----: | :------: | :------: | :------: | :-----------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| InternVideo2-6B | DBM | 63.13 | 44.36 | 10.36 | 42.80 | [config](anet_internvideo6b.py) | [model](https://drive.google.com/file/d/1jI8TKcGP2L5SM_yN-Q6HvcoTKg5-VYas/view?usp=sharing) \| [log](https://drive.google.com/file/d/1qrxU_ER8J0hrv2fwoAlfoVS-NRlnMAx1/view?usp=sharing) | + + - The validation dataset we used has 4,728 videos, which is the same number as in BMN but less than ActionFormer's implementation. Consequently, this result is slightly higher than VideoMambaSuite's official result. You can check [README](../../tools/prepare_data/activitynet/README.md) for more details. + +**THUMOS-14** + +| Features | Setting | mAP@0.3 | mAP@0.4 | mAP@0.5 | mAP@0.6 | mAP@0.7 | ave. mAP | Config | Download | +| :-------------: | :-----: | :-----: | :-----: | :-----: | :-----: | :-----: | :------: | :-------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| InternVideo2-6B | DBM | 87.30 | 82.95 | 77.17 | 67.06 | 51.74 | 73.24 | [config](thumos_internvideo6b.py) | [model](https://drive.google.com/file/d/14ASHrwj7bl7w83e1L07qd8i8dGQcyI-F/view?usp=sharing) \| [log](https://drive.google.com/file/d/1oJcOHSrt_UIu_gb_Xw3QMASqpqNZL1YL/view?usp=sharing) | + +- Following VSGN, we additionally delete `video_test_0000270` during testing due to wrong annotation. Consequently, this result is slightly higher than VideoMambaSuite's official result. You can check [README](../../tools/prepare_data/thumos/README.md) for more details. + +**FineAction** + +| Features | Setting | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :-------------: | :-----: | :-----: | :------: | :------: | :------: | :-----------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| InternVideo2-1B | DBM | 45.72 | 29.37 | 5.37 | 29.13 | [config](fineaction_internvideo1b.py) | [model](https://drive.google.com/file/d/1F3R0ysS8w9a7RyID3rnp1pr6w93mXQ5b/view?usp=sharing) \| [log](https://drive.google.com/file/d/1HU31IHYohYijgrVT4rePrGT1_1tspLcI/view?usp=sharing) | + +**HACS** with InternVideo2 classifier. + +| Features | Setting | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :-------------: | :-----: | :-----: | :------: | :------: | :------: | :-----------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| InternVideo2-6B | DBM | 64.16 | 46.08 | 13.86 | 44.81 | [config](hacs_internvideo6b.py) | [model](https://drive.google.com/file/d/1F2AB2gfPLIKZQ0G_KONe9SeAtYJxnJfj/view?usp=sharing) \| [log](https://drive.google.com/file/d/1q7IkLcjnRIHIuvO4K1lvLZWd-XcY2BQr/view?usp=sharing) | + +**MultiTHUMOS** + +| Features | Setting | mAP@0.2 | mAP@0.5 | mAP@0.7 | ave. mAP (0.1:0.9:0.1) | Config | Download | +| :-------------: | :-----: | :-----: | :-----: | :-----: | :--------------------: | :------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| InternVideo2-6B | DBM | 66.40 | 52.15 | 32.34 | 45.32 | [config](multithumos_internvideo6b.py) | [model](https://drive.google.com/file/d/1b_isRM9JDE0hN0ENW9GBopF5nqt6vgNM/view?usp=sharing) \| [log](https://drive.google.com/file/d/1EAL9jfzgh8CW1ssq8unBcCgSkwocm_yW/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train VideoMambaSuite on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/videomambasuite/videomambasuite_internvideo6b.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test VideoMambaSuite on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/videomambasuite/videomambasuite_internvideo6b.py --checkpoint exps/anet/videomambasuite_internvideo6b/gpu1_id0/checkpoint/epoch_11.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + +## Citation + +```latex +@misc{2024videomambasuite, + title={Video Mamba Suite: State Space Model as a Versatile Alternative for Video Understanding}, + author={Guo Chen, Yifei Huang, Jilan Xu, Baoqi Pei, Zhe Chen, Zhiqi Li, Jiahao Wang, Kunchang Li, Tong Lu, Limin Wang}, + year={2024}, + eprint={2403.09626}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/videomambasuite/anet_internvideo6b.py b/OpenTAD/configs/videomambasuite/anet_internvideo6b.py new file mode 100644 index 0000000000000000000000000000000000000000..79f848276f4c883c12f4f6a249f9a7f701863ae0 --- /dev/null +++ b/OpenTAD/configs/videomambasuite/anet_internvideo6b.py @@ -0,0 +1,101 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize_trunc.py", # dataset config + "../_base_/models/videomambasuite.py", # model config +] + +resize_length = 192 +data_path = "data/activitynet-1.3/features/activitynet_6b/" +dataset = dict( + train=dict( + data_path=data_path, + block_list=None, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", prefix="v_", suffix="_spatial_pool_feature_6"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="RandomTrunc", trunc_len=resize_length, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + data_path=data_path, + block_list=None, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", prefix="v_", suffix="_spatial_pool_feature_6"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + data_path=data_path, + block_list=None, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", prefix="v_", suffix="_spatial_pool_feature_6"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="ResizeFeat", tool="torchvision_align"), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + + +model = dict( + projection=dict( + in_channels=3200, + out_channels=256, + max_seq_len=192, + input_pdrop=0.2, + ), + neck=dict(in_channels=256, out_channels=256), + rpn_head=dict( + in_channels=256, + feat_channels=256, + num_classes=1, + label_smoothing=0.1, + loss_weight=2.0, + loss_normalizer=200, + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=15) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.75, + max_seg_num=100, + min_score=0.001, + multiclass=False, + voting_thresh=0.9, # set 0 to disable + ), + external_cls=dict( + type="StandardClassifier", + path="data/activitynet-1.3/classifiers/anet_UMTv2_6B_k710+K40_f16_frozenTuning.json_converted.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=7, +) + +work_dir = "exps/anet/videomambasuite_internvideo6b" diff --git a/OpenTAD/configs/videomambasuite/fineaction_internvideo1b.py b/OpenTAD/configs/videomambasuite/fineaction_internvideo1b.py new file mode 100644 index 0000000000000000000000000000000000000000..efeafae27c8c23773e291218c9b36426e9f1389e --- /dev/null +++ b/OpenTAD/configs/videomambasuite/fineaction_internvideo1b.py @@ -0,0 +1,106 @@ +_base_ = [ + "../_base_/datasets/fineaction/features_internvideo_pad.py", # dataset config + "../_base_/models/videomambasuite.py", # model config +] + +trunc_len = 2304 +data_path = "data/fineaction/features/fineaction_1b/" +dataset = dict( + train=dict( + data_path=data_path, + block_list=["v_00004011", "v_00006080", "v_00002783"], # dirty annotation + feature_stride=4, + sample_stride=2, + offset_frames=8, + fps=30, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", suffix="_spatial_pool_feature_5"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=trunc_len, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + data_path=data_path, + block_list=None, + feature_stride=4, + sample_stride=2, + offset_frames=8, + fps=30, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", suffix="_spatial_pool_feature_5"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + data_path=data_path, + block_list=None, + feature_stride=4, + sample_stride=2, + offset_frames=8, + fps=30, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", suffix="_spatial_pool_feature_5"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) +model = dict( + projection=dict( + in_channels=1408, + out_channels=512, + arch=(2, 2, 7), + max_seq_len=2304, + input_pdrop=0.1, + ), + neck=dict(in_channels=512, out_channels=512, num_levels=8), + rpn_head=dict( + in_channels=512, + feat_channels=512, + num_classes=106, + prior_generator=dict( + type="PointGenerator", + strides=[1, 2, 4, 8, 16, 32, 64, 128], + regression_range=[(0, 4), (4, 8), (8, 16), (16, 32), (32, 64), (64, 128), (128, 256), (256, 10000)], + ), + ), +) + +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=1, num_workers=0), + test=dict(batch_size=1, num_workers=0), + clip_grad_norm=1.0, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=25) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.75, + max_seg_num=200, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=10, +) + +work_dir = "exps/fineaction/videomambasuite_internvideo1b" diff --git a/OpenTAD/configs/videomambasuite/hacs_internvideo6b.py b/OpenTAD/configs/videomambasuite/hacs_internvideo6b.py new file mode 100644 index 0000000000000000000000000000000000000000..f323663bc9bff996e16344602d60529b690f289a --- /dev/null +++ b/OpenTAD/configs/videomambasuite/hacs_internvideo6b.py @@ -0,0 +1,141 @@ +_base_ = [ + "../_base_/datasets/hacs-1.1.1/features_slowfast_pad.py", # dataset config + "../_base_/models/videomambasuite.py", # model config +] + +block_list = [ + "-LzyV1PtJXE", + "6okHpDA7caA", + "8P9hAN-teOU", + "AcOgvJ6U0T8", + "AkMSIaZyX00", + "Cm2j1EhVkHc", + "EEvcgmd8kzg", + "HjunnoyAinU", + "Ht2gV7oaqbo", + "Jbu3hE_CQaw", + "Lp1oWVjxm4I", + "New9JV1dKSU", + "PcltZ1RZmZ0", + "Q_QRFa5r3s0", + "S4ZC3rz0q5c", + "ShwMX7iMdCw", + "V9uNF5W9KjM", + "ZrhHEvR84AE", + "d0ViiZ_QsLo", + "jsuwmH5Y7OM", + "mAE0CQURjj8", + "mllZ0ycwvTs", + "mnhMpLONbtY", + "oUMmneMSfC0", + "tqBKTZxSxwQ", + "vA4STJJyyxU", + "xaAjiyc4VmM", + "y41wrOt1K1M", +] # missing video in HACS, not used in evaluation + +trunc_len = 2304 +data_path = "data/hacs-1.1.1/features/hacs_6b/" +dataset = dict( + train=dict( + data_path=data_path, + block_list=None, + feature_stride=8, + offset_frames=8, + fps=30, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", prefix="v_", suffix="_spatial_pool_feature_6"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="RandomTrunc", trunc_len=trunc_len, trunc_thresh=0.5, crop_ratio=[0.9, 1.0]), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + val=dict( + data_path=data_path, + block_list=block_list, + feature_stride=8, + offset_frames=8, + fps=30, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", prefix="v_", suffix="_spatial_pool_feature_6"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Padding", length=trunc_len), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks", "gt_segments", "gt_labels"]), + ], + ), + test=dict( + data_path=data_path, + block_list=block_list, + feature_stride=8, + offset_frames=8, + fps=30, + class_agnostic=True, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", prefix="v_", suffix="_spatial_pool_feature_6"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Padding", length=trunc_len), + dict(type="Rearrange", keys=["feats"], ops="t c-> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + +model = dict( + projection=dict( + in_channels=3200, + out_channels=256, + use_abs_pe=True, + max_seq_len=2304, + input_pdrop=0.1, + ), + neck=dict(in_channels=256, out_channels=256), + rpn_head=dict( + in_channels=256, + feat_channels=256, + num_classes=1, + label_smoothing=0.1, + loss_normalizer=400, + ), +) +solver = dict( + train=dict(batch_size=16, num_workers=4), + val=dict(batch_size=16, num_workers=4), + test=dict(batch_size=16, num_workers=4), + clip_grad_norm=1.0, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-3, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=25) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.75, + max_seg_num=100, + min_score=0.001, + multiclass=False, + voting_thresh=0.7, # set 0 to disable + ), + external_cls=dict( + type="StandardClassifier", + path="data/hacs-1.1.1/classifiers/hacs_UMTv2_6B_k710+K40_f16_frozenTuning.json_converted.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=8, +) + +work_dir = "exps/hacs/videomambasuite_internvideo6b" diff --git a/OpenTAD/configs/videomambasuite/multithumos_internvideo6b.py b/OpenTAD/configs/videomambasuite/multithumos_internvideo6b.py new file mode 100644 index 0000000000000000000000000000000000000000..b89d94ba201286f4358845b72a3838631bc80add --- /dev/null +++ b/OpenTAD/configs/videomambasuite/multithumos_internvideo6b.py @@ -0,0 +1,98 @@ +_base_ = [ + "../_base_/datasets/multithumos/features_i3d_pad.py", # dataset config + "../_base_/models/videomambasuite.py", # model config +] + +trunc_len = 2304 +data_path = "data/thumos-14/features/thumos14_6b/" +dataset = dict( + train=dict( + data_path=data_path, + block_list=None, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", suffix="_spatial_feature"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict( + type="RandomTrunc", + trunc_len=trunc_len, + trunc_thresh=0.5, + crop_ratio=[0.9, 1.0], + ), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict( + type="Collect", + inputs="feats", + keys=["masks", "gt_segments", "gt_labels"], + ), + ], + ), + val=dict( + data_path=data_path, + block_list=None, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", suffix="_spatial_feature"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict( + type="Collect", + inputs="feats", + keys=["masks", "gt_segments", "gt_labels"], + ), + ], + ), + test=dict( + data_path=data_path, + block_list=None, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", suffix="_spatial_feature"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + +model = dict( + projection=dict(in_channels=3200, arch=(3, 0, 5), input_pdrop=0.1), + rpn_head=dict(num_classes=65), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=65) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + pre_nms_topk=8000, + pre_nms_thresh=0.001, + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=8000, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=20, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=39, + end_epoch=55, +) + +work_dir = "exps/multithumos/videomambasuite_internvideo6b" diff --git a/OpenTAD/configs/videomambasuite/thumos_internvideo6b.py b/OpenTAD/configs/videomambasuite/thumos_internvideo6b.py new file mode 100644 index 0000000000000000000000000000000000000000..bbd8e36a265516b095bc27d7322ff71fea35de6c --- /dev/null +++ b/OpenTAD/configs/videomambasuite/thumos_internvideo6b.py @@ -0,0 +1,94 @@ +_base_ = [ + "../_base_/datasets/thumos-14/features_i3d_pad.py", # dataset config + "../_base_/models/videomambasuite.py", # model config +] + +trunc_len = 2304 +data_path = "data/thumos-14/features/thumos14_6b/" +dataset = dict( + train=dict( + data_path=data_path, + block_list=None, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", suffix="_spatial_feature"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict( + type="RandomTrunc", + trunc_len=trunc_len, + trunc_thresh=0.5, + crop_ratio=[0.9, 1.0], + ), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict( + type="Collect", + inputs="feats", + keys=["masks", "gt_segments", "gt_labels"], + ), + ], + ), + val=dict( + data_path=data_path, + block_list=None, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", suffix="_spatial_feature"), + dict(type="ConvertToTensor", keys=["feats", "gt_segments", "gt_labels"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict( + type="Collect", + inputs="feats", + keys=["masks", "gt_segments", "gt_labels"], + ), + ], + ), + test=dict( + data_path=data_path, + block_list=None, + offset_frames=8, + pipeline=[ + dict(type="LoadFeats", feat_format="pt", suffix="_spatial_feature"), + dict(type="ConvertToTensor", keys=["feats"]), + dict(type="Rearrange", keys=["feats"], ops="t c -> c t"), + dict(type="Collect", inputs="feats", keys=["masks"]), + ], + ), +) + +model = dict( + projection=dict(in_channels=3200, input_pdrop=0.1), +) + +solver = dict( + train=dict(batch_size=2, num_workers=2), + val=dict(batch_size=1, num_workers=1), + test=dict(batch_size=1, num_workers=1), + clip_grad_norm=1, + ema=True, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=0.05, paramwise=True) +scheduler = dict(type="LinearWarmupCosineAnnealingLR", warmup_epoch=5, max_epoch=50) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=2000, + min_score=0.001, + multiclass=True, + voting_thresh=0.7, # set 0 to disable + ), + save_dict=False, +) + +workflow = dict( + logging_interval=20, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=24, +) + +work_dir = "exps/thumos/videomambasuite_internvideo6b" diff --git a/OpenTAD/configs/vsgn/README.md b/OpenTAD/configs/vsgn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c85d8b3d32d00681347e605986fea706fc6aa624 --- /dev/null +++ b/OpenTAD/configs/vsgn/README.md @@ -0,0 +1,64 @@ +# VSGN + +> [Video Self-Stitching Graph Network for Temporal Action Localization](https://arxiv.org/abs/2011.14598) +> Chen Zhao, Ali Thabet, Bernard Ghanem + + + +## Abstract + +Temporal action localization (TAL) in videos is a challenging task, especially due to the large variation in action temporal scales. Short actions usually occupy the major proportion in the data, but have the lowest performance with all current methods. In this paper, we confront the challenge of short actions and propose a multi-level cross-scale solution dubbed as video self-stitching graph network (VSGN). We have two key components in VSGN: video self-stitching (VSS) and cross-scale graph pyramid network (xGPN). In VSS, we focus on a short period of a video and magnify it along the temporal dimension to obtain a larger scale. We stitch the original clip and its magnified counterpart in one input sequence to take advantage of the complementary properties of both scales. The xGPN component further exploits the cross-scale correlations by a pyramid of cross-scale graph networks, each containing a hybrid module to aggregate features from across scales as well as within the same scale. Our VSGN not only enhances the feature representations, but also generates more positive anchors for short actions and more short training samples. Experiments demonstrate that VSGN obviously improves the localization performance of short actions as well as achieving the state-of-the-art overall performance on THUMOS-14 and ActivityNet-v1.3. + +## Results and Models + +**ActivityNet-1.3** with CUHK classifier. + +| Stitching | GCN | Features | mAP@0.5 | mAP@0.75 | mAP@0.95 | ave. mAP | Config | Download | +| :-------: | :---: | :------: | :-----: | :------: | :------: | :------: | :-----------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| False | Fasle | TSP | 54.40 | 36.88 | 9.15 | 36.27 | [config](anet_tsp.py) | [model](https://drive.google.com/file/d/1E85NhJyyO_6qfnucfVg5mEyW9t6UJH7v/view?usp=sharing) \| [log](https://drive.google.com/file/d/1g1UVUtd-6UnNVawist6cvHaGEsnlZHxP/view?usp=sharing) | +| False | True | TSP | 54.80 | 37.35 | 9.80 | 36.89 | [config](anet_tsp_gcn.py) | [model](https://drive.google.com/file/d/1y7PqP1TiNkGNxx-WLBccZvuTUo2mfbOD/view?usp=sharing) \| [log](https://drive.google.com/file/d/1krOBqbYNI9moRbIhbYpOT6RUphXIQDD9/view?usp=sharing) | + + +## Train + +You can use the following command to train a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +Example: train VSGN on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py configs/vsgn/anet_tsp.py +``` + +For more details, you can refer to the Training part in the [Usage](../../docs/en/usage.md). + +## Test + +You can use the following command to test a model. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py ${CONFIG_FILE} --checkpoint ${CHECKPOINT_FILE} [optional arguments] +``` + +Example: test VSGN on ActivityNet dataset. + +```shell +torchrun --nnodes=1 --nproc_per_node=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py configs/vsgn/anet_tsp.py --checkpoint exps/anet/vsgn_tsp_256/gpu1_id0/checkpoint/epoch_9.pth +``` + +For more details, you can refer to the Test part in the [Usage](../../docs/en/usage.md). + +## Citation + +```latex +@inproceedings{zhao2021video, + title={Video self-stitching graph network for temporal action localization}, + author={Zhao, Chen and Thabet, Ali K and Ghanem, Bernard}, + booktitle={Proceedings of the IEEE/CVF International Conference on Computer Vision}, + pages={13658--13667}, + year={2021} +} +``` \ No newline at end of file diff --git a/OpenTAD/configs/vsgn/anet_tsp.py b/OpenTAD/configs/vsgn/anet_tsp.py new file mode 100644 index 0000000000000000000000000000000000000000..8996ebc9994271718cb1da9d57101ae02fec88dd --- /dev/null +++ b/OpenTAD/configs/vsgn/anet_tsp.py @@ -0,0 +1,57 @@ +_base_ = [ + "../_base_/datasets/activitynet-1.3/features_tsp_resize.py", # dataset config + "../_base_/models/vsgn.py", # model config +] + + +tscale = 256 + +dataset = dict( + train=dict(resize_length=tscale), + val=dict(resize_length=tscale), + test=dict(resize_length=tscale), +) + +model = dict( + projection=dict(in_channels=512), + rpn_head=dict( + anchor_generator=dict(tscale=tscale, anchor_scale=[3, 7.5]), + loss_cls=dict(type="FocalLoss", gamma=2.0, alpha=0.35), + ), + roi_head=dict(roi_extractor=dict(tscale=tscale)), +) + +solver = dict( + train=dict(batch_size=32, num_workers=4), + val=dict(batch_size=32, num_workers=4), + test=dict(batch_size=32, num_workers=4), + clip_grad_norm=1, +) + +optimizer = dict(type="AdamW", lr=1e-4, weight_decay=1e-4) +scheduler = dict(type="MultiStepLR", milestones=[15], gamma=0.1, max_epoch=15) + +inference = dict(load_from_raw_predictions=False, save_raw_prediction=False) +post_processing = dict( + nms=dict( + use_soft_nms=True, + sigma=0.5, + max_seg_num=100, + voting_thresh=0, # set 0 to disable + ), + external_cls=dict( + type="CUHKANETClassifier", + path="data/activitynet-1.3/classifiers/cuhk_val_simp_7.json", + topk=2, + ), + save_dict=False, +) + +workflow = dict( + logging_interval=200, + checkpoint_interval=1, + val_loss_interval=1, + val_eval_interval=1, + val_start_epoch=7, +) +work_dir = "exps/anet/vsgn_tsp_256" diff --git a/OpenTAD/configs/vsgn/anet_tsp_gcn.py b/OpenTAD/configs/vsgn/anet_tsp_gcn.py new file mode 100644 index 0000000000000000000000000000000000000000..bb1b6996474b5f5124c487415ede0e8b5a983fbf --- /dev/null +++ b/OpenTAD/configs/vsgn/anet_tsp_gcn.py @@ -0,0 +1,11 @@ +_base_ = ["anet_tsp.py"] + + +model = dict( + projection=dict( + use_gcn=True, + gcn_kwargs=dict(num_neigh=10, nfeat_mode="feat_ctr", agg_type="max", edge_weight="false"), + ), +) + +work_dir = "exps/anet/vsgn_tsp_256_gcn" diff --git a/OpenTAD/docs/en/changelog.md b/OpenTAD/docs/en/changelog.md new file mode 100644 index 0000000000000000000000000000000000000000..571e887b252d7588db8aad2f272ef6cc623c13bc --- /dev/null +++ b/OpenTAD/docs/en/changelog.md @@ -0,0 +1,6 @@ +## Changelog + +### v0.1.0 (2024/03/28) + +- Initial release of OpenTAD. +- The codebase is under beta testing. Feedbacks and suggestions are welcome! diff --git a/OpenTAD/docs/en/install.md b/OpenTAD/docs/en/install.md new file mode 100644 index 0000000000000000000000000000000000000000..ad75560fd1fae93366485578b125d365007b42b1 --- /dev/null +++ b/OpenTAD/docs/en/install.md @@ -0,0 +1,45 @@ +# Installation + +**Step 1.** Install PyTorch=2.0.1, Python=3.10.12 + +``` +conda create -n opentad python=3.10.12 +source activate opentad +conda install pytorch=2.0.1 torchvision=0.15.2 pytorch-cuda=11.8 -c pytorch -c nvidia +``` + +**Step 2.** Install mmaction2 for end-to-end training +``` +pip install openmim +mim install mmcv==2.0.1 +mim install mmaction2==1.1.0 +``` + +**Step 3.** Install OpenTAD +``` +git clone git@github.com:sming256/OpenTAD.git +cd OpenTAD + +pip install -r requirements.txt +``` + +The code is tested with Python 3.10.12, PyTorch 2.0.1, CUDA 11.8, and gcc 11.3.0 on Ubuntu 20.04, other versions might also work. + +**Step 4.** Prepare the annotation and data. + +| Dataset | Description | +| :--------------------------------------------------------- | :-------------------------------------------------------------------------------------------- | +| [ActivityNet](/tools/prepare_data/activitynet/README.md) | A Large-Scale Video Benchmark for Human Activity Understanding with 19,994 videos. | +| [THUMOS14](/tools/prepare_data/thumos/README.md) | Consists of 413 videos with temporal annotations. | +| [EPIC-KITCHENS](/tools/prepare_data/epic/README.md) | Large-scale dataset in first-person (egocentric) vision. Latest version is EPIC-KITCHENS-100. | +| [Ego4D-MQ](/tools/prepare_data/ego4d/README.md) | Ego4D is the world's largest egocentric video dataset. MQ refers to its moment query task. | +| [HACS](/tools/prepare_data/hacs/README.md) | The same action taxonomy with ActivityNet, but consists of around 50K videos. | +| [FineAction](/tools/prepare_data/fineaction/README.md) | Contains 103K temporal instances of 106 action categories, annotated in 17K untrimmed videos. | +| [Multi-THUMOS](/tools/prepare_data/multi-thumos/README.md) | Dense, multilabel action annotations of THUMOS14. | +| [Charades](/tools/prepare_data/charades/README.md) | Contains dense-labeled 9,848 annotated videos of daily activities. | + + +PS: If you meet `FileNotFoundError: [Errno 2] No such file or directory: 'xxx/missing_files.txt'` +- It means you may need to generate a `missing_files.txt`, which should record the missing features compared to all the videos in the annotation files. You can use `python tools/prepare_data/generate_missing_list.py annotation.json feature_folder` to generate the txt file. +- eg. `python tools/prepare_data/generate_missing_list.py data/fineaction/annotations/annotations_gt.json data/fineaction/features/fineaction_mae_g` +- In the provided feature from this codebase, we have already included this txt in the zip file. \ No newline at end of file diff --git a/OpenTAD/docs/en/roadmap.md b/OpenTAD/docs/en/roadmap.md new file mode 100644 index 0000000000000000000000000000000000000000..8d1e026f544147a9e60b20e69d6d8c16386433a5 --- /dev/null +++ b/OpenTAD/docs/en/roadmap.md @@ -0,0 +1,12 @@ +## Roadmap + +### Major Features +- [ ] Release Ego4D configs. +- [ ] Visualization tool. +- [ ] Feature extraction code. +- [ ] Detailed documentation. +- [ ] Colab demo for inference. +- [ ] Support tensorboard. +- [ ] Support Wandb. +- [ ] Support tools to measure flops, speed, params. +- [ ] Add benchmark results. \ No newline at end of file diff --git a/OpenTAD/docs/en/usage.md b/OpenTAD/docs/en/usage.md new file mode 100644 index 0000000000000000000000000000000000000000..02dfc970fcd0f53773d550daeeea2ba9cc32aef7 --- /dev/null +++ b/OpenTAD/docs/en/usage.md @@ -0,0 +1,57 @@ +## Usage + +By default, we use DistributedDataParallel (DDP) both in single GPU and multiple GPU cases for simplicity. + +### Training + +`torchrun --nnodes={num_node} --nproc_per_node={num_gpu} --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/train.py {config}` + +- `num_node` is often set as 1 if all gpus are allocated in a single node. `num_gpu` is the number of used GPU. +- `config` is the path of the config file. + +Example: + +- Training feature-based ActionFormer on 1 GPU. +```bash +torchrun \ + --nnodes=1 \ + --nproc_per_node=1 \ + --rdzv_backend=c10d \ + --rdzv_endpoint=localhost:0 \ + tools/train.py configs/actionformer/thumos_i3d.py +``` + +- Training end-to-end-based AdaTAD on 4 GPUs within 1 node. +```bash +torchrun \ + --nnodes=1 \ + --nproc_per_node=4 \ + --rdzv_backend=c10d \ + --rdzv_endpoint=localhost:0 \ + tools/train.py configs/adatad/e2e_anet_videomae_s_adapter_frame768_img160.py +``` + +Note: +- **GPU number would affect the detection performance in most cases.** Since TAD dataset is small, and the number of ground truth actions per video differs dramatically in different videos. Therefore, the recommended setting for training feature-based TAD is 1 GPU, empirically. +- By default, evaluation is also conducted in the training, based on the argument in the config file. You can disable this, or increase the evaluation interval to speed up the training. + +### Inference and Evaluation + +`torchrun --nnodes={num_node} --nproc_per_node={num_gpu} --rdzv_backend=c10d --rdzv_endpoint=localhost:0 tools/test.py {config} --checkpoint {path}` + +- if `checkpoint` is not specified, the `best.pth` in the config's result folder will be used. + + +Example: + +- Inference and Evaluate ActionFormer on 1 GPU. +```bash +torchrun \ + --nnodes=1 \ + --nproc_per_node=1 \ + --rdzv_backend=c10d \ + --rdzv_endpoint=localhost:0 \ + tools/test.py \ + configs/actionformer/thumos_i3d.py \ + --checkpoint exps/thumos/actionformer_i3d/gpu1_id0/checkpoint/epoch_34.pth +``` diff --git a/OpenTAD/opentad/cores/__init__.py b/OpenTAD/opentad/cores/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..82be05e0f582b6e9faf6950fca9d02cc39c9beae --- /dev/null +++ b/OpenTAD/opentad/cores/__init__.py @@ -0,0 +1,6 @@ +from .train_engine import train_one_epoch, val_one_epoch +from .test_engine import eval_one_epoch +from .optimizer import build_optimizer +from .scheduler import build_scheduler + +__all__ = ["train_one_epoch", "val_one_epoch", "eval_one_epoch", "build_optimizer", "build_scheduler"] diff --git a/OpenTAD/opentad/cores/layer_decay_optimizer.py b/OpenTAD/opentad/cores/layer_decay_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..bc289b91c2f0d0a5751eaad26f18fc184e7cbc95 --- /dev/null +++ b/OpenTAD/opentad/cores/layer_decay_optimizer.py @@ -0,0 +1,93 @@ +import torch + + +def get_layer_id_for_vit(var_name, max_layer_id): + """Get the layer id to set the different learning rates in ``layer_wise`` + decay_type. + + Args: + var_name (str): The key of the model. + max_layer_id (int): Maximum layer id. + Returns: + int: The id number corresponding to different learning rate in + ``LayerDecayOptimizerConstructor``. + """ + if var_name.startswith("model.backbone"): + if "patch_embed" in var_name or "pos_embed" in var_name: + return 0 + elif ".blocks." in var_name: + layer_id = int(var_name.split(".")[3]) + 1 + return layer_id + else: + return max_layer_id + 1 + else: + return max_layer_id + 1 + + +def build_vit_optimizer(cfg, model, logger): + assert model.module.backbone.freeze_backbone == False, "The backbone should not be frozen." + + num_layers = cfg["num_layers"] + 2 + decay_rate = cfg["layer_decay_rate"] + logger.info(f"Build LayerDecayOptimizer: layer_decay={decay_rate}, num_layers={num_layers}") + base_lr = cfg["lr"] + base_wd = cfg["weight_decay"] + + parameter_groups = {} + + # loop the backbone's parameters + for name, param in model.module.backbone.named_parameters(): + if not param.requires_grad: + continue # frozen weights + if name.startswith("model.backbone.blocks") and "norm" in name: + group_name = "no_decay" + this_weight_decay = 0.0 + elif "pos_embed" in name: + group_name = "no_decay_pos_embed" + this_weight_decay = 0 + else: + group_name = "decay" + this_weight_decay = base_wd + + layer_id = get_layer_id_for_vit(name, cfg["num_layers"]) + logger.info(f"set param {name} as id {layer_id}") + + group_name = f"layer_{layer_id}_{group_name}" + + if group_name not in parameter_groups: + scale = decay_rate ** (num_layers - 1 - layer_id) + + parameter_groups[group_name] = { + "weight_decay": this_weight_decay, + "params": [], + "param_names": [], + "lr_scale": scale, + "group_name": group_name, + "lr": scale * base_lr, + } + + parameter_groups[group_name]["params"].append(param) + parameter_groups[group_name]["param_names"].append(name) + + # set the detector's optim_groups: SHOULD NOT CONTAIN BACKBONE PARAMS + # here, if each method want their own paramwise config, eg. to specify the learning rate, + # weight decay for a certain layer, the model should have a function called get_optim_groups + if "paramwise" in cfg.keys() and cfg["paramwise"]: + cfg.pop("paramwise") + det_optim_groups = model.module.get_optim_groups(cfg) + else: + # optim_groups that does not contain backbone params + detector_params = [] + for name, param in model.module.named_parameters(): + # exclude the backbone + if name.startswith("backbone"): + continue + detector_params.append(param) + det_optim_groups = [dict(params=detector_params)] + + # merge the optim_groups + optim_groups = [] + optim_groups.extend(parameter_groups.values()) + optim_groups = optim_groups + det_optim_groups + optimizer = torch.optim.AdamW(optim_groups) + return optimizer diff --git a/OpenTAD/opentad/cores/optimizer.py b/OpenTAD/opentad/cores/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ed126d87ca2f012bfdc37e01bb8ecad8616e8d --- /dev/null +++ b/OpenTAD/opentad/cores/optimizer.py @@ -0,0 +1,137 @@ +import torch +from .layer_decay_optimizer import build_vit_optimizer + + +def build_optimizer(cfg, model, logger): + optimizer_type = cfg["type"] + cfg.pop("type") + + if optimizer_type == "LayerDecayAdamW": + return build_vit_optimizer(cfg, model, logger) + + # set the backbone's optim_groups: SHOULD ONLY CONTAIN BACKBONE PARAMS + if hasattr(model.module, "backbone"): # if backbone exists + if model.module.backbone.freeze_backbone == False: # not frozen + backbone_cfg = cfg["backbone"] + cfg.pop("backbone") + backbone_optim_groups = get_backbone_optim_groups(backbone_cfg, model, logger) + + else: # frozen backbone + backbone_optim_groups = [] + logger.info(f"Freeze the backbone...") + else: + backbone_optim_groups = [] + + # set the detector's optim_groups: SHOULD NOT CONTAIN BACKBONE PARAMS + # here, if each method want their own paramwise config, eg. to specify the learning rate, + # weight decay for a certain layer, the model should have a function called get_optim_groups + if "paramwise" in cfg.keys() and cfg["paramwise"]: + cfg.pop("paramwise") + det_optim_groups = model.module.get_optim_groups(cfg) + else: + # optim_groups that does not contain backbone params + detector_params = [] + for name, param in model.module.named_parameters(): + # exclude the backbone + if name.startswith("backbone"): + continue + detector_params.append(param) + det_optim_groups = [dict(params=detector_params)] + + # merge the optim_groups + optim_groups = backbone_optim_groups + det_optim_groups + + if optimizer_type == "AdamW": + optimizer = torch.optim.AdamW(optim_groups, **cfg) + elif optimizer_type == "Adam": + optimizer = torch.optim.Adam(optim_groups, **cfg) + elif optimizer_type == "SGD": + optimizer = torch.optim.SGD(optim_groups, **cfg) + else: + raise f"Optimizer {optimizer_type} is not supported so far." + + return optimizer + + +def get_backbone_optim_groups(cfg, model, logger): + """Example: + backbone = dict( + lr=1e-5, + weight_decay=1e-4, + custom=[dict(name="residual", lr=1e-3, weight_decay=1e-4)], + exclude=[], + ) + """ + + # custom_name_list + if "custom" in cfg.keys(): + custom_name_list = [d["name"] for d in cfg["custom"]] + custom_params_list = [[]] * len(custom_name_list) + else: + custom_name_list = [] + + # exclude_name_list + if "exclude" in cfg.keys(): + exclude_name_list = cfg["exclude"] + else: + exclude_name_list = [] + + # rest_params_list + rest_params_list = [] + + name_list = [] + # split the backbone parameters into different groups + for name, param in model.module.backbone.named_parameters(): + # loop the exclude_name_list + is_exclude = False + if len(exclude_name_list) > 0: + for exclude_name in exclude_name_list: + if exclude_name in name: + is_exclude = True + break + + # loop through the custom_name_list + is_custom = False + if len(custom_name_list) > 0: + for i, custom_name in enumerate(custom_name_list): + if custom_name in name: + custom_params_list[i].append(param) + name_list.append(name) + is_custom = True + break + + # if is_custom, we have already appended the param to the custom_params_list + # if is _exclude, we do not need to append the param to the rest_params_list + if is_exclude or is_custom: + continue + + # this is a rest parameter without special treatment + if not is_custom: + # this is the rest backbone parameters + rest_params_list.append(param) + name_list.append(name) + + for name in name_list: + logger.info(f"Backbone parameter: {name}") + # add params to optim_groups + backbone_optim_groups = [] + + if len(rest_params_list) > 0: + backbone_optim_groups.append( + dict( + params=rest_params_list, + lr=cfg["lr"], + weight_decay=cfg["weight_decay"], + ) + ) + + if len(custom_name_list) > 0: + for i, custom_name in enumerate(custom_name_list): + backbone_optim_groups.append( + dict( + params=custom_params_list[i], + lr=cfg["custom"][i]["lr"], + weight_decay=cfg["custom"][i]["weight_decay"], + ) + ) + return backbone_optim_groups diff --git a/OpenTAD/opentad/cores/scheduler.py b/OpenTAD/opentad/cores/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..58a59c3868c537dae0bb223ab5845878e6a4c421 --- /dev/null +++ b/OpenTAD/opentad/cores/scheduler.py @@ -0,0 +1,212 @@ +import math +import warnings +from bisect import bisect_right +from collections import Counter +from torch.optim.lr_scheduler import _LRScheduler + + +def build_scheduler(cfg, optimizer, dataloader_len): + scheduler_type = cfg["type"] + cfg.pop("type") + + max_epoch = cfg["max_epoch"] + + if scheduler_type == "LinearWarmupCosineAnnealingLR": + cfg["warmup_epoch"] *= dataloader_len + cfg["max_epoch"] *= dataloader_len + scheduler = LinearWarmupCosineAnnealingLR(optimizer, **cfg) + elif scheduler_type == "LinearWarmupMultiStepLR": + cfg.pop("max_epoch") + cfg["warmup_epoch"] *= dataloader_len + cfg["milestones"] = [dataloader_len * step for step in cfg["milestones"]] + scheduler = LinearWarmupMultiStepLR(optimizer, **cfg) + elif scheduler_type == "MultiStepLR": + cfg.pop("max_epoch") + cfg["milestones"] = [dataloader_len * step for step in cfg["milestones"]] + scheduler = LinearWarmupMultiStepLR(optimizer, warmup_epoch=0, **cfg) + else: + raise f"Optimizer {scheduler_type} is not supported so far." + + return scheduler, max_epoch + + +class LinearWarmupCosineAnnealingLR(_LRScheduler): + """ + Sets the learning rate of each parameter group to follow a linear warmup schedule + between warmup_start_lr and base_lr followed by a cosine annealing schedule between + base_lr and eta_min. + + .. warning:: + It is recommended to call :func:`.step()` for :class:`LinearWarmupCosineAnnealingLR` + after each iteration as calling it after each epoch will keep the starting lr at + warmup_start_lr for the first epoch which is 0 in most cases. + + .. warning:: + passing epoch to :func:`.step()` is being deprecated and comes with an EPOCH_DEPRECATION_WARNING. + It calls the :func:`_get_closed_form_lr()` method for this scheduler instead of + :func:`get_lr()`. Though this does not change the behavior of the scheduler, when passing + epoch param to :func:`.step()`, the user should call the :func:`.step()` function before calling + train and validation methods. + + Example: + >>> layer = nn.Linear(10, 1) + >>> optimizer = Adam(layer.parameters(), lr=0.02) + >>> scheduler = LinearWarmupCosineAnnealingLR(optimizer, warmup_epoch=10, max_epoch=40) + >>> # + >>> # the default case + >>> for epoch in range(40): + ... # train(...) + ... # validate(...) + ... scheduler.step() + >>> # + >>> # passing epoch param case + >>> for epoch in range(40): + ... scheduler.step(epoch) + ... # train(...) + ... # validate(...) + """ + + def __init__( + self, + optimizer, + warmup_epoch, + max_epoch, + warmup_start_lr=0.0, + eta_min=1e-8, + last_epoch=-1, + ): + """ + Args: + optimizer (Optimizer): Wrapped optimizer. + warmup_epoch (int): Maximum number of iterations for linear warmup + max_epoch (int): Maximum number of iterations + warmup_start_lr (float): Learning rate to start the linear warmup. Default: 0. + eta_min (float): Minimum learning rate. Default: 0. + last_epoch (int): The index of last epoch. Default: -1. + """ + self.warmup_epoch = warmup_epoch + self.max_epoch = max_epoch + self.warmup_start_lr = warmup_start_lr + self.eta_min = eta_min + + super(LinearWarmupCosineAnnealingLR, self).__init__(optimizer, last_epoch) + + def get_lr(self): + """ + Compute learning rate using chainable form of the scheduler + """ + if not self._get_lr_called_within_step: + warnings.warn( + "To get the last learning rate computed by the scheduler, " "please use `get_last_lr()`.", + UserWarning, + ) + + if self.last_epoch == 0: + return [self.warmup_start_lr] * len(self.base_lrs) + elif self.last_epoch < self.warmup_epoch: + return [ + group["lr"] + (base_lr - self.warmup_start_lr) / (self.warmup_epoch - 1) + for base_lr, group in zip(self.base_lrs, self.optimizer.param_groups) + ] + elif self.last_epoch == self.warmup_epoch: + return self.base_lrs + elif (self.last_epoch - 1 - self.max_epoch) % (2 * (self.max_epoch - self.warmup_epoch)) == 0: + return [ + group["lr"] + + (base_lr - self.eta_min) * (1 - math.cos(math.pi / (self.max_epoch - self.warmup_epoch))) / 2 + for base_lr, group in zip(self.base_lrs, self.optimizer.param_groups) + ] + + return [ + (1 + math.cos(math.pi * (self.last_epoch - self.warmup_epoch) / (self.max_epoch - self.warmup_epoch))) + / (1 + math.cos(math.pi * (self.last_epoch - self.warmup_epoch - 1) / (self.max_epoch - self.warmup_epoch))) + * (group["lr"] - self.eta_min) + + self.eta_min + for group in self.optimizer.param_groups + ] + + def _get_closed_form_lr(self): + """ + Called when epoch is passed as a param to the `step` function of the scheduler. + """ + if self.last_epoch < self.warmup_epoch: + return [ + self.warmup_start_lr + self.last_epoch * (base_lr - self.warmup_start_lr) / (self.warmup_epoch - 1) + for base_lr in self.base_lrs + ] + + return [ + self.eta_min + + 0.5 + * (base_lr - self.eta_min) + * (1 + math.cos(math.pi * (self.last_epoch - self.warmup_epoch) / (self.max_epoch - self.warmup_epoch))) + for base_lr in self.base_lrs + ] + + +class LinearWarmupMultiStepLR(_LRScheduler): + """Decays the learning rate of each parameter group by gamma once the + number of epoch reaches one of the milestones. Notice that such decay can + happen simultaneously with other changes to the learning rate from outside + this scheduler. When last_epoch=-1, sets initial lr as lr. + + Args: + optimizer (Optimizer): Wrapped optimizer. + milestones (list): List of epoch indices. Must be increasing. + gamma (float): Multiplicative factor of learning rate decay. + Default: 0.1. + last_epoch (int): The index of last epoch. Default: -1. + verbose (bool): If ``True``, prints a message to stdout for + each update. Default: ``False``. + + Example: + >>> # Assuming optimizer uses lr = 0.05 for all groups + >>> # lr = 0.05 if epoch < 30 + >>> # lr = 0.005 if 30 <= epoch < 80 + >>> # lr = 0.0005 if epoch >= 80 + >>> scheduler = MultiStepLR(optimizer, milestones=[30,80], gamma=0.1) + >>> for epoch in range(100): + >>> train(...) + >>> validate(...) + >>> scheduler.step() + """ + + def __init__( + self, + optimizer, + milestones, + gamma=0.1, + last_epoch=-1, + warmup_epoch=0, + warmup_start_lr=0, + ): + self.milestones = Counter(milestones) + self.gamma = gamma + self.warmup_epoch = warmup_epoch + self.warmup_start_lr = warmup_start_lr + super(LinearWarmupMultiStepLR, self).__init__(optimizer, last_epoch) + + def get_lr(self): + if not self._get_lr_called_within_step: + warnings.warn( + "To get the last learning rate computed by the scheduler, " "please use `get_last_lr()`.", UserWarning + ) + + # last epoch actually means last iter + if self.last_epoch == self.warmup_epoch: + return self.base_lrs + elif self.last_epoch == 0: + return [self.warmup_start_lr] * len(self.base_lrs) + elif self.last_epoch < self.warmup_epoch: + return [ + group["lr"] + (base_lr - self.warmup_start_lr) / self.warmup_epoch + for base_lr, group in zip(self.base_lrs, self.optimizer.param_groups) + ] + elif self.last_epoch in self.milestones: + return [group["lr"] * self.gamma for group in self.optimizer.param_groups] + else: + return [group["lr"] for group in self.optimizer.param_groups] + + def _get_closed_form_lr(self): + milestones = list(sorted(self.milestones.elements())) + return [base_lr * self.gamma ** bisect_right(milestones, self.last_epoch) for base_lr in self.base_lrs] diff --git a/OpenTAD/opentad/cores/test_engine.py b/OpenTAD/opentad/cores/test_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..31d5e9290d715a1912c84a0850142b57ead506c3 --- /dev/null +++ b/OpenTAD/opentad/cores/test_engine.py @@ -0,0 +1,129 @@ +import os +import copy +import json +import tqdm +import torch +import torch.distributed as dist + +from opentad.utils import create_folder +from opentad.models.utils.post_processing import build_classifier, batched_nms +from opentad.evaluations import build_evaluator +from opentad.datasets.base import SlidingWindowDataset + + +def eval_one_epoch( + test_loader, + model, + cfg, + logger, + rank, + model_ema=None, + use_amp=False, + world_size=0, + not_eval=False, +): + """Inference and Evaluation the model""" + + # load the ema dict for evaluation + if model_ema != None: + current_dict = copy.deepcopy(model.state_dict()) + model.load_state_dict(model_ema.module.state_dict()) + + cfg.inference["folder"] = os.path.join(cfg.work_dir, "outputs") + if cfg.inference.save_raw_prediction: + create_folder(cfg.inference["folder"]) + + # external classifier + if "external_cls" in cfg.post_processing: + if cfg.post_processing.external_cls != None: + external_cls = build_classifier(cfg.post_processing.external_cls) + else: + external_cls = test_loader.dataset.class_map + + # whether the testing dataset is sliding window + cfg.post_processing.sliding_window = isinstance(test_loader.dataset, SlidingWindowDataset) + + # model forward + model.eval() + result_dict = {} + for data_dict in tqdm.tqdm(test_loader, disable=(rank != 0)): + with torch.cuda.amp.autocast(dtype=torch.float16, enabled=use_amp): + with torch.no_grad(): + results = model( + **data_dict, + return_loss=False, + infer_cfg=cfg.inference, + post_cfg=cfg.post_processing, + ext_cls=external_cls, + ) + + # update the result dict + for k, v in results.items(): + if k in result_dict.keys(): + result_dict[k].extend(v) + else: + result_dict[k] = v + + result_dict = gather_ddp_results(world_size, result_dict, cfg.post_processing) + + # load back the normal model dict + if model_ema != None: + model.load_state_dict(current_dict) + + if rank == 0: + result_eval = dict(results=result_dict) + if cfg.post_processing.save_dict: + result_path = os.path.join(cfg.work_dir, "result_detection_onAnetTest.json") + with open(result_path, "w") as out: + json.dump(result_eval, out, indent=4) + + if not not_eval: + # build evaluator + evaluator = build_evaluator(dict(prediction_filename=result_eval, **cfg.evaluation)) + # evaluate and output + logger.info("Evaluation starts...") + metrics_dict = evaluator.evaluate() + evaluator.logging(logger) + + +def gather_ddp_results(world_size, result_dict, post_cfg): + gather_dict_list = [None for _ in range(world_size)] + dist.all_gather_object(gather_dict_list, result_dict) + result_dict = {} + for i in range(world_size): # update the result dict + for k, v in gather_dict_list[i].items(): + if k in result_dict.keys(): + result_dict[k].extend(v) + else: + result_dict[k] = v + + # do nms for sliding window, if needed + if post_cfg.sliding_window == True and post_cfg.nms is not None: + # assert sliding_window=True + tmp_result_dict = {} + for k, v in result_dict.items(): + segments = torch.Tensor([data["segment"] for data in v]) + scores = torch.Tensor([data["score"] for data in v]) + labels = [] + class_idx = [] + for data in v: + if data["label"] not in class_idx: + class_idx.append(data["label"]) + labels.append(class_idx.index(data["label"])) + labels = torch.Tensor(labels) + + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=class_idx[int(label.item())], + score=round(score.item(), 4), + ) + ) + tmp_result_dict[k] = results_per_video + result_dict = tmp_result_dict + return result_dict diff --git a/OpenTAD/opentad/cores/train_engine.py b/OpenTAD/opentad/cores/train_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..c36f278cefc14be29be25e20213f829ce60dd816 --- /dev/null +++ b/OpenTAD/opentad/cores/train_engine.py @@ -0,0 +1,128 @@ +import copy +import torch +import tqdm +from opentad.utils.misc import AverageMeter, reduce_loss + + +def train_one_epoch( + train_loader, + model, + optimizer, + scheduler, + curr_epoch, + logger, + model_ema=None, + clip_grad_l2norm=-1, + logging_interval=200, + scaler=None, +): + """Training the model for one epoch""" + + logger.info("[Train]: Epoch {:d} started".format(curr_epoch)) + losses_tracker = {} + num_iters = len(train_loader) + use_amp = False if scaler is None else True + + model.train() + for iter_idx, data_dict in enumerate(train_loader): + optimizer.zero_grad() + + # current learning rate + curr_backbone_lr = None + if hasattr(model.module, "backbone"): # if backbone exists + if model.module.backbone.freeze_backbone == False: # not frozen + curr_backbone_lr = scheduler.get_last_lr()[0] + curr_det_lr = scheduler.get_last_lr()[-1] + + # forward pass + with torch.cuda.amp.autocast(dtype=torch.float16, enabled=use_amp): + losses = model(**data_dict, return_loss=True) + + # compute the gradients + if use_amp: + scaler.scale(losses["cost"]).backward() + else: + losses["cost"].backward() + + # gradient clipping (to stabilize training if necessary) + if clip_grad_l2norm > 0.0: + if use_amp: + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(model.parameters(), clip_grad_l2norm) + + # update parameters + if use_amp: + scaler.step(optimizer) + scaler.update() + else: + optimizer.step() + + # update scheduler + scheduler.step() + + # update ema + if model_ema is not None: + model_ema.update(model) + + # track all losses + losses = reduce_loss(losses) # only for log + for key, value in losses.items(): + if key not in losses_tracker: + losses_tracker[key] = AverageMeter() + losses_tracker[key].update(value.item()) + + # printing each logging_interval + if ((iter_idx != 0) and (iter_idx % logging_interval) == 0) or ((iter_idx + 1) == num_iters): + # print to terminal + block1 = "[Train]: [{:03d}][{:05d}/{:05d}]".format(curr_epoch, iter_idx, num_iters - 1) + block2 = "Loss={:.4f}".format(losses_tracker["cost"].avg) + block3 = ["{:s}={:.4f}".format(key, value.avg) for key, value in losses_tracker.items() if key != "cost"] + block4 = "lr_det={:.1e}".format(curr_det_lr) + if curr_backbone_lr is not None: + block4 = "lr_backbone={:.1e}".format(curr_backbone_lr) + " " + block4 + block5 = "mem={:.0f}MB".format(torch.cuda.max_memory_allocated() / 1024.0 / 1024.0) + logger.info(" ".join([block1, block2, " ".join(block3), block4, block5])) + + +def val_one_epoch( + val_loader, + model, + logger, + rank, + curr_epoch, + model_ema=None, + use_amp=False, +): + """Validating the model for one epoch: compute the loss""" + + # load the ema dict for evaluation + if model_ema != None: + current_dict = copy.deepcopy(model.state_dict()) + model.load_state_dict(model_ema.module.state_dict()) + + logger.info("[Val]: Epoch {:d} Loss".format(curr_epoch)) + losses_tracker = {} + + model.eval() + for data_dict in tqdm.tqdm(val_loader, disable=(rank != 0)): + with torch.cuda.amp.autocast(dtype=torch.float16, enabled=use_amp): + with torch.no_grad(): + losses = model(**data_dict, return_loss=True) + + # track all losses + losses = reduce_loss(losses) # only for log + for key, value in losses.items(): + if key not in losses_tracker: + losses_tracker[key] = AverageMeter() + losses_tracker[key].update(value.item()) + + # print to terminal + block1 = "[Val]: [{:03d}]".format(curr_epoch) + block2 = "Loss={:.4f}".format(losses_tracker["cost"].avg) + block3 = ["{:s}={:.4f}".format(key, value.avg) for key, value in losses_tracker.items() if key != "cost"] + logger.info(" ".join([block1, block2, " ".join(block3)])) + + # load back the normal model dict + if model_ema != None: + model.load_state_dict(current_dict) + return losses_tracker["cost"].avg diff --git a/OpenTAD/opentad/datasets/__init__.py b/OpenTAD/opentad/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..931af1565a90c22e95b0b4f5f17bcd061b9b90d9 --- /dev/null +++ b/OpenTAD/opentad/datasets/__init__.py @@ -0,0 +1,22 @@ +from .builder import build_dataset, build_dataloader +from .transforms import * +from .base import * +from .anet import AnetResizeDataset, AnetPaddingDataset, AnetSlidingDataset +from .thumos import ThumosSlidingDataset, ThumosPaddingDataset +from .ego4d import Ego4DSlidingDataset, Ego4DPaddingDataset, Ego4DResizeDataset +from .epic_kitchens import EpicKitchensSlidingDataset, EpicKitchensPaddingDataset + +__all__ = [ + "build_dataset", + "build_dataloader", + "AnetResizeDataset", + "AnetPaddingDataset", + "AnetSlidingDataset", + "ThumosSlidingDataset", + "ThumosPaddingDataset", + "Ego4DSlidingDataset", + "Ego4DPaddingDataset", + "Ego4DResizeDataset", + "EpicKitchensSlidingDataset", + "EpicKitchensPaddingDataset", +] diff --git a/OpenTAD/opentad/datasets/anet.py b/OpenTAD/opentad/datasets/anet.py new file mode 100644 index 0000000000000000000000000000000000000000..156e575e805a8db0fa0d702b268286f67c9eaa66 --- /dev/null +++ b/OpenTAD/opentad/datasets/anet.py @@ -0,0 +1,155 @@ +import numpy as np +from .base import ResizeDataset, PaddingDataset, SlidingWindowDataset, filter_same_annotation +from .builder import DATASETS + + +@DATASETS.register_module() +class AnetResizeDataset(ResizeDataset): + def get_gt(self, video_info, thresh=0.01): + gt_segment = [] + gt_label = [] + for anno in video_info["annotations"]: + gt_start = float(anno["segment"][0]) + gt_end = float(anno["segment"][1]) + gt_scale = (gt_end - gt_start) / float(video_info["duration"]) + + if (not self.filter_gt) or (gt_scale > thresh): + gt_segment.append([gt_start, gt_end]) + if self.class_agnostic: + gt_label.append(0) + else: + gt_label.append(self.class_map.index(anno["label"])) + + if len(gt_segment) == 0: # have no valid gt + return None + else: + annotation = dict( + gt_segments=np.array(gt_segment, dtype=np.float32), + gt_labels=np.array(gt_label, dtype=np.int32), + ) + return filter_same_annotation(annotation) + + def __getitem__(self, index): + video_name, video_info, video_anno = self.data_list[index] + + results = self.pipeline( + dict( + video_name=video_name, + data_path=self.data_path, + resize_length=self.resize_length, + sample_stride=self.sample_stride, + # resize post process setting + fps=-1, + duration=float(video_info["duration"]), + **video_anno, + ) + ) + return results + + +@DATASETS.register_module() +class AnetPaddingDataset(PaddingDataset): + def get_gt(self, video_info, thresh=0.0): + # if fps is not set, use the original fps + fps = self.fps if self.fps > 0 else float(video_info["frame"]) / float(video_info["duration"]) + + gt_segment = [] + gt_label = [] + for anno in video_info["annotations"]: + gt_start = int(anno["segment"][0] * fps) + gt_end = int(anno["segment"][1] * fps) + + if (not self.filter_gt) or (gt_end - gt_start > thresh): + gt_segment.append([gt_start, gt_end]) + if self.class_agnostic: + gt_label.append(0) + else: + gt_label.append(self.class_map.index(anno["label"])) + + if len(gt_segment) == 0: # have no valid gt + return None + else: + annotation = dict( + gt_segments=np.array(gt_segment, dtype=np.float32), + gt_labels=np.array(gt_label, dtype=np.int32), + ) + return filter_same_annotation(annotation) + + def __getitem__(self, index): + video_name, video_info, video_anno = self.data_list[index] + + if video_anno != {}: + video_anno["gt_segments"] = video_anno["gt_segments"] - self.offset_frames + video_anno["gt_segments"] = video_anno["gt_segments"] / self.snippet_stride + + results = self.pipeline( + dict( + video_name=video_name, + data_path=self.data_path, + sample_stride=self.sample_stride, + snippet_stride=self.snippet_stride, + # if fps is not set, use the original fps + fps=self.fps if self.fps > 0 else float(video_info["frame"]) / float(video_info["duration"]), + duration=float(video_info["duration"]), + offset_frames=self.offset_frames, + **video_anno, + ) + ) + return results + + +@DATASETS.register_module() +class AnetSlidingDataset(SlidingWindowDataset): + def get_gt(self, video_info, thresh=0.0): + # if fps is not set, use the original fps + fps = self.fps if self.fps > 0 else float(video_info["frame"]) / float(video_info["duration"]) + + gt_segment = [] + gt_label = [] + for anno in video_info["annotations"]: + gt_start = int(anno["segment"][0] * fps) + gt_end = int(anno["segment"][1] * fps) + + if (not self.filter_gt) or (gt_end - gt_start > thresh): + gt_segment.append([gt_start, gt_end]) + if self.class_agnostic: + gt_label.append(0) + else: + gt_label.append(self.class_map.index(anno["label"])) + + if len(gt_segment) == 0: # have no valid gt + return None + else: + annotation = dict( + gt_segments=np.array(gt_segment, dtype=np.float32), + gt_labels=np.array(gt_label, dtype=np.int32), + ) + return filter_same_annotation(annotation) + + def __getitem__(self, index): + video_name, video_info, video_anno, window_snippet_centers = self.data_list[index] + + if video_anno != {}: + video_anno["gt_segments"] = video_anno["gt_segments"] - window_snippet_centers[0] - self.offset_frames + video_anno["gt_segments"] = video_anno["gt_segments"] / self.snippet_stride + + results = self.pipeline( + dict( + video_name=video_name, + data_path=self.data_path, + window_size=self.window_size, + # trunc window setting + feature_start_idx=int(window_snippet_centers[0] / self.snippet_stride), + feature_end_idx=int(window_snippet_centers[-1] / self.snippet_stride), + sample_stride=self.sample_stride, + # sliding post process setting + fps=self.fps if self.fps > 0 else float(video_info["frame"]) / float(video_info["duration"]), + snippet_stride=self.snippet_stride, + window_start_frame=window_snippet_centers[0], + duration=video_info["duration"], + offset_frames=self.offset_frames, + # training setting + **video_anno, + ) + ) + return results diff --git a/OpenTAD/opentad/datasets/base/__init__.py b/OpenTAD/opentad/datasets/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..11eb31b0559bbf42af8af4ba4c04c1525ad6e1bf --- /dev/null +++ b/OpenTAD/opentad/datasets/base/__init__.py @@ -0,0 +1,11 @@ +from .resize_dataset import ResizeDataset +from .sliding_dataset import SlidingWindowDataset +from .padding_dataset import PaddingDataset +from .util import filter_same_annotation + +__all__ = ["ResizeDataset", "SlidingWindowDataset", "PaddingDataset", "filter_same_annotation"] + +# There are three types of dataset preprocessing in TAD. +# 1. ResizeDataset: for each video, resize the video to a fixed length. It is commonly used in ActivityNet / HACS dataset. +# 2. SlidingWindowDataset: for each video, split the video into several windows. Such as used by G-TAD / BMN in THUMOS dataset. +# 3. PaddingDataset: for each video, pad the video to a fixed length. If the video is longer than the fixed length, then random cut a clip from the video. Such as used by ActionFormer / TriDet in THUMOS / EPIC-KITCHENS dataset. diff --git a/OpenTAD/opentad/datasets/base/padding_dataset.py b/OpenTAD/opentad/datasets/base/padding_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..135146f80eddbad62c3ecd37e279445c8ec8c784 --- /dev/null +++ b/OpenTAD/opentad/datasets/base/padding_dataset.py @@ -0,0 +1,99 @@ +import json +import os +from mmengine.dataset import Compose + +from ..builder import DATASETS, get_class_index + + +@DATASETS.register_module() +class PaddingDataset: + def __init__( + self, + ann_file, # path of the annotation json file + subset_name, # name of the subset, such as training, validation, testing + data_path, # folder path of the raw video / pre-extracted feature + pipeline, # data pipeline + class_map, # path of the class map, convert the class id to category name + filter_gt=False, # if True, filter out those gt has the scale smaller than 0.01 + class_agnostic=False, # if True, the class index will be replaced by 0 + block_list=None, # some videos might be missed in the features or videos, we need to block them + test_mode=False, # if True, running on test mode with no annotation + # for feature setting + feature_stride=-1, # the frames between two adjacent features, such as 4 frames + sample_stride=1, # if you want to extract the feature[::sample_stride] + offset_frames=0, # the start offset frame of the input feature + fps=-1, # some annotations are based on video-seconds + logger=None, + ): + super(PaddingDataset, self).__init__() + + # basic settings + self.data_path = data_path + self.block_list = block_list + self.ann_file = ann_file + self.subset_name = subset_name + self.logger = logger.info if logger != None else print + self.class_map = self.get_class_map(class_map) + self.class_agnostic = class_agnostic + self.filter_gt = filter_gt + self.test_mode = test_mode + self.pipeline = Compose(pipeline) + + # feature settings + self.feature_stride = feature_stride + self.sample_stride = sample_stride + self.offset_frames = int(offset_frames) + self.snippet_stride = int(feature_stride * sample_stride) + self.fps = fps + + self.get_dataset() + self.logger(f"{self.subset_name} subset: {len(self.data_list)} videos") + + def get_dataset(self): + with open(self.ann_file, "r") as f: + anno_database = json.load(f)["database"] + + # some videos might be missed in the features or videos, we need to block them + if self.block_list != None: + if isinstance(self.block_list, list): + blocked_videos = self.block_list + else: + with open(self.block_list, "r") as f: + blocked_videos = [line.rstrip("\n") for line in f] + else: + blocked_videos = [] + + self.data_list = [] + for video_name, video_info in anno_database.items(): + if (video_name in blocked_videos) or (video_info["subset"] not in self.subset_name): + continue + + # get the ground truth annotation + if self.test_mode: + video_anno = {} + else: + video_anno = self.get_gt(video_info) + if video_anno == None: # have no valid gt + continue + + self.data_list.append([video_name, video_info, video_anno]) + assert len(self.data_list) > 0, f"No data found in {self.subset_name} subset." + + def get_class_map(self, class_map_path): + if not os.path.exists(class_map_path): + class_map = get_class_index(self.ann_file, class_map_path) + self.logger(f"Class map is saved in {class_map_path}, total {len(class_map)} classes.") + else: + with open(class_map_path, "r", encoding="utf8") as f: + lines = f.readlines() + class_map = [item.rstrip("\n") for item in lines] + return class_map + + def get_gt(self): + pass + + def __getitem__(self): + pass + + def __len__(self): + return len(self.data_list) diff --git a/OpenTAD/opentad/datasets/base/resize_dataset.py b/OpenTAD/opentad/datasets/base/resize_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..a78e30ded10b6783d9b00bdaa98a19e2976f1417 --- /dev/null +++ b/OpenTAD/opentad/datasets/base/resize_dataset.py @@ -0,0 +1,91 @@ +import json +import os +import numpy as np +from ..builder import DATASETS, get_class_index +from mmengine.dataset import Compose + + +@DATASETS.register_module() +class ResizeDataset: + def __init__( + self, + ann_file, # path of the annotation json file + subset_name, # name of the subset, such as training, validation, testing + data_path, # folder path of the raw video / pre-extracted feature + pipeline, # data pipeline + class_map, # path of the class map, convert the class id to category name + filter_gt=False, # if True, filter out those gt has the scale smaller than 0.01 + class_agnostic=False, # if True, the class index will be replaced by 0 + block_list=None, # some videos might be missed in the features or videos, we need to block them + test_mode=False, # if True, running on test mode with no annotation + resize_length=128, # the length of the resized video + sample_stride=1, # if you want to extract the feature[::sample_stride] + logger=None, + ): + super(ResizeDataset, self).__init__() + + # basic settings + self.data_path = data_path + self.block_list = block_list + self.ann_file = ann_file + self.subset_name = subset_name + self.logger = logger.info if logger != None else print + self.class_map = self.get_class_map(class_map) + self.class_agnostic = class_agnostic + self.filter_gt = filter_gt + self.test_mode = test_mode + self.resize_length = resize_length + self.sample_stride = sample_stride + self.pipeline = Compose(pipeline) + + self.get_dataset() + self.logger(f"{self.subset_name} subset: {len(self.data_list)} videos") + + def get_dataset(self): + with open(self.ann_file, "r") as f: + anno_database = json.load(f)["database"] + + # some videos might be missed in the features or videos, we need to block them + if self.block_list != None: + if isinstance(self.block_list, list): + blocked_videos = self.block_list + else: + with open(self.block_list, "r") as f: + blocked_videos = [line.rstrip("\n") for line in f] + else: + blocked_videos = [] + + self.data_list = [] + for video_name, video_info in anno_database.items(): + if (video_name in blocked_videos) or (video_info["subset"] not in self.subset_name): + continue + + # get the ground truth annotation + if self.test_mode: + video_anno = {} + else: + video_anno = self.get_gt(video_info) + if video_anno == None: # have no valid gt + continue + + self.data_list.append([video_name, video_info, video_anno]) + assert len(self.data_list) > 0, f"No data found in {self.subset_name} subset." + + def get_class_map(self, class_map_path): + if not os.path.exists(class_map_path): + class_map = get_class_index(self.ann_file, class_map_path) + self.logger(f"Class map is saved in {class_map_path}, total {len(class_map)} classes.") + else: + with open(class_map_path, "r", encoding="utf8") as f: + lines = f.readlines() + class_map = [item.rstrip("\n") for item in lines] + return class_map + + def get_gt(self): + pass + + def __getitem__(self): + pass + + def __len__(self): + return len(self.data_list) diff --git a/OpenTAD/opentad/datasets/base/sliding_dataset.py b/OpenTAD/opentad/datasets/base/sliding_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..76a58a49da20440bf22fd7a649a8875549d01803 --- /dev/null +++ b/OpenTAD/opentad/datasets/base/sliding_dataset.py @@ -0,0 +1,199 @@ +import json +import os +import numpy as np +from mmengine.dataset import Compose + +from ..builder import DATASETS, get_class_index + + +@DATASETS.register_module() +class SlidingWindowDataset: + def __init__( + self, + ann_file, # path of the annotation json file + subset_name, # name of the subset, such as training, validation, testing + data_path, # folder path of the raw video / pre-extracted feature + pipeline, # data pipeline + class_map, # path of the class map, convert the class id to category name + filter_gt=False, # if True, filter out those gt has the scale smaller than 0.01 + block_list=None, # some videos might be missed in the features or videos, we need to block them + test_mode=False, # if True, running on test mode with no annotation + # for feature setting + feature_stride=-1, # the frames between two adjacent features, such as 4 frames + sample_stride=1, # if you want to extract the feature[::sample_stride] + offset_frames=0, # the start offset frame of the input feature + # for sliding window setting + window_size=-1, # the number of features in a window + window_overlap_ratio=0.25, # the overlap ratio of two adjacent windows + ioa_thresh=0.75, # the threshold of the completeness of the gt inside the window + fps=-1, # some annotations are based on video-seconds + logger=None, + ): + super(SlidingWindowDataset, self).__init__() + + # basic settings + self.data_path = data_path + self.block_list = block_list + self.ann_file = ann_file + self.subset_name = subset_name + self.logger = logger.info if logger != None else print + self.class_map = self.get_class_map(class_map) + self.filter_gt = filter_gt + self.test_mode = test_mode + self.pipeline = Compose(pipeline) + + # feature settings + self.feature_stride = int(feature_stride) + self.sample_stride = int(sample_stride) + self.offset_frames = int(offset_frames) + self.snippet_stride = int(feature_stride * sample_stride) + self.fps = fps + + # window settings + self.window_size = int(window_size) + self.window_stride = int(window_size * (1 - window_overlap_ratio)) + self.ioa_thresh = ioa_thresh + + self.get_dataset() + self.logger( + f"{self.subset_name} subset: {len(set([data[0] for data in self.data_list]))} videos, " + f"truncated as {len(self.data_list)} windows." + ) + + def get_dataset(self): + with open(self.ann_file, "r") as f: + anno_database = json.load(f)["database"] + + # some videos might be missed in the features or videos, we need to block them + if self.block_list != None: + if isinstance(self.block_list, list): + blocked_videos = self.block_list + else: + with open(self.block_list, "r") as f: + blocked_videos = [line.rstrip("\n") for line in f] + else: + blocked_videos = [] + + self.data_list = [] + for video_name, video_info in anno_database.items(): + if (video_name in blocked_videos) or (video_info["subset"] not in self.subset_name): + continue + + # get the ground truth annotation + if self.test_mode: + video_anno = {} + else: + video_anno = self.get_gt(video_info) + if video_anno == None: # have no valid gt + continue + + tmp_data_list = self.split_video_to_windows(video_name, video_info, video_anno) + self.data_list.extend(tmp_data_list) + assert len(self.data_list) > 0, f"No data found in {self.subset_name} subset." + + def split_video_to_windows(self, video_name, video_info, video_anno): + # need: video frame, video duration, video fps + if self.fps > 0: + num_frames = int(video_info["duration"] * self.fps) + else: + num_frames = video_info["frame"] + + video_snippet_centers = np.arange(0, num_frames, self.snippet_stride) + snippet_num = len(video_snippet_centers) + + data_list = [] + last_window = False # whether it is the last window + + for idx in range(max(1, snippet_num // self.window_stride)): # at least one window + window_start = idx * self.window_stride + window_end = window_start + self.window_size + + if window_end > snippet_num: # this is the last window + window_end = snippet_num + window_start = max(0, window_end - self.window_size) + last_window = True + + window_snippet_centers = video_snippet_centers[window_start:window_end] + window_start_frame = window_snippet_centers[0] + window_end_frame = window_snippet_centers[-1] + + if (video_anno != {}) and (self.ioa_thresh > 0): + gt_segments = video_anno["gt_segments"] + gt_labels = video_anno["gt_labels"] + anchor = np.array([window_start_frame, window_end_frame]) + + # truncate the gt segments inside the window and compute the completeness + gt_completeness, truncated_gt = compute_gt_completeness(gt_segments, anchor) + valid_idx = gt_completeness > self.ioa_thresh + + # only append window who has gt + if np.sum(valid_idx) > 0: + window_anno = dict( + gt_segments=truncated_gt[valid_idx], + gt_labels=gt_labels[valid_idx], + ) + data_list.append( + [ + video_name, + video_info, + window_anno, + window_snippet_centers, + ] + ) + else: + data_list.append( + [ + video_name, + video_info, + video_anno, + window_snippet_centers, + ] + ) + + if last_window: # the last window + break + + return data_list + + def get_class_map(self, class_map_path): + if not os.path.exists(class_map_path): + class_map = get_class_index(self.ann_file, class_map_path) + self.logger(f"Class map is saved in {class_map_path}, total {len(class_map)} classes.") + else: + with open(class_map_path, "r", encoding="utf8") as f: + lines = f.readlines() + class_map = [item.rstrip("\n") for item in lines] + return class_map + + def get_gt(self): + pass + + def __getitem__(self): + pass + + def __len__(self): + return len(self.data_list) + + +def compute_gt_completeness(gt_boxes, anchors): + """Compute the completeness of the gt_bboxes. + GT will be first truncated by the anchor start/end, then the completeness is defined as the ratio of the truncated_gt_len / original_gt_len. + If this ratio is too small, it means this gt is not complete enough to be used for training. + Args: + gt_boxes: np.array shape [N, 2] + anchors: np.array shape [2] + """ + + scores = np.zeros(gt_boxes.shape[0]) # initialized as 0 + valid_idx = np.logical_and(gt_boxes[:, 0] < anchors[1], gt_boxes[:, 1] > anchors[0]) # valid gt + valid_gt_boxes = gt_boxes[valid_idx] + + truncated_valid_gt_len = np.minimum(valid_gt_boxes[:, 1], anchors[1]) - np.maximum(valid_gt_boxes[:, 0], anchors[0]) + original_valid_gt_len = valid_gt_boxes[:, 1] - valid_gt_boxes[:, 0] + scores[valid_idx] = truncated_valid_gt_len / original_valid_gt_len + + # also truncated gt + truncated_gt_boxes = np.stack( + [np.maximum(gt_boxes[:, 0], anchors[0]), np.minimum(gt_boxes[:, 1], anchors[1])], axis=1 + ) + return scores, truncated_gt_boxes # shape [N] diff --git a/OpenTAD/opentad/datasets/base/util.py b/OpenTAD/opentad/datasets/base/util.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c2d2563b526b5f31737f30707a55d875b1cb0d --- /dev/null +++ b/OpenTAD/opentad/datasets/base/util.py @@ -0,0 +1,36 @@ +import numpy as np + + +def filter_same_annotation(annotation): + gt_segments = [] + gt_labels = [] + for gt_segment, gt_label in zip(annotation["gt_segments"].tolist(), annotation["gt_labels"].tolist()): + if (gt_segment not in gt_segments) or (gt_label not in gt_labels): + gt_segments.append(gt_segment) + gt_labels.append(gt_label) + else: + if gt_labels[gt_segments.index(gt_segment)] != gt_label: + gt_segments.append(gt_segment) + gt_labels.append(gt_label) + else: + continue + + annotation = dict( + gt_segments=np.array(gt_segments, dtype=np.float32), + gt_labels=np.array(gt_labels, dtype=np.int32), + ) + return annotation + + +if __name__ == "__main__": + anno1 = dict(gt_segments=np.array([[3, 5], [3, 6], [3, 5]]), gt_labels=np.array([0, 1, 0])) + print(filter_same_annotation(anno1)) + # output should be: + # 'gt_segments': array([[3., 5.], [3., 6.]], dtype=float32), + # 'gt_labels': array([0, 1], dtype=int32)} + + anno2 = dict(gt_segments=np.array([[3, 5], [3, 6], [3, 5]]), gt_labels=np.array([0, 1, 2])) + print(filter_same_annotation(anno2)) + # output should be: + # 'gt_segments': array([[3., 5.], [3., 6.], [3., 5.]], dtype=float32), + # 'gt_labels': array([0, 1, 2], dtype=int32)} diff --git a/OpenTAD/opentad/datasets/builder.py b/OpenTAD/opentad/datasets/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..c16192ec320516f4efb708e1f6102e3652b64cf5 --- /dev/null +++ b/OpenTAD/opentad/datasets/builder.py @@ -0,0 +1,79 @@ +import json +import torch +from torch.utils.data.dataloader import default_collate +from collections.abc import Sequence +from mmengine.registry import Registry, build_from_cfg, TRANSFORMS + +DATASETS = Registry("dataset") +PIPELINES = TRANSFORMS + + +def build_dataset(cfg, default_args=None): + """Build a dataset from config dict. + + Args: + cfg (dict): Config dict. It should at least contain the key "type". + default_args (dict | None, optional): Default initialization arguments. + Default: None. + + Returns: + Dataset: The constructed dataset. + """ + dataset = build_from_cfg(cfg, DATASETS, default_args) + return dataset + + +def build_dataloader(dataset, batch_size, rank, world_size, shuffle=False, drop_last=False, **kwargs): + sampler = torch.utils.data.distributed.DistributedSampler( + dataset, + num_replicas=world_size, + rank=rank, + shuffle=shuffle, + drop_last=drop_last, + ) + + assert batch_size % world_size == 0, f"batch size {batch_size} should be divided by world size {world_size}" + dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=batch_size // world_size, + collate_fn=collate, + pin_memory=True, + sampler=sampler, + **kwargs, + ) + return dataloader + + +def collate(batch): + if not isinstance(batch, Sequence): + raise TypeError(f"{batch.dtype} is not supported.") + + gpu_stack_keys = ["inputs", "masks"] + + collate_data = {} + for key in batch[0]: + if key in gpu_stack_keys: + collate_data[key] = default_collate([sample[key] for sample in batch]) + else: + collate_data[key] = [sample[key] for sample in batch] + return collate_data + + +def get_class_index(gt_json_path, class_map_path): + with open(gt_json_path, "r") as f: + anno = json.load(f) + + anno = anno["database"] + class_map = [] + for video_name in anno.keys(): + if "annotations" in anno[video_name]: + for tmpp_data in anno[video_name]["annotations"]: + if tmpp_data["label"] not in class_map: + class_map.append(tmpp_data["label"]) + + class_map.sort() + f2 = open(class_map_path, "w") + for name in class_map: + f2.write(name + "\n") + f2.close() + return class_map diff --git a/OpenTAD/opentad/datasets/ego4d.py b/OpenTAD/opentad/datasets/ego4d.py new file mode 100644 index 0000000000000000000000000000000000000000..e5fdf42845552d76670fedf1f0682b8ae88b98c0 --- /dev/null +++ b/OpenTAD/opentad/datasets/ego4d.py @@ -0,0 +1,138 @@ +import numpy as np +from .base import PaddingDataset, ResizeDataset, SlidingWindowDataset, filter_same_annotation +from .builder import DATASETS + + +@DATASETS.register_module() +class Ego4DPaddingDataset(PaddingDataset): + def get_gt(self, video_info, thresh=0.0): + gt_segment = [] + gt_label = [] + for anno in video_info["annotations"]: + gt_start = int(anno["segment"][0] / video_info["duration"] * video_info["frame"]) + gt_end = int(anno["segment"][1] / video_info["duration"] * video_info["frame"]) + + if (not self.filter_gt) or (gt_end - gt_start > thresh): + gt_segment.append([gt_start, gt_end]) + gt_label.append(self.class_map.index(anno["label"])) + + if len(gt_segment) == 0: # have no valid gt + return None + else: + annotation = dict( + gt_segments=np.array(gt_segment, dtype=np.float32), + gt_labels=np.array(gt_label, dtype=np.int32), + ) + return filter_same_annotation(annotation) + + def __getitem__(self, index): + video_name, video_info, video_anno = self.data_list[index] + + if video_anno != {}: + video_anno["gt_segments"] = video_anno["gt_segments"] - self.offset_frames + video_anno["gt_segments"] = video_anno["gt_segments"] / self.snippet_stride + + results = self.pipeline( + dict( + video_name=video_name, + data_path=self.data_path, + sample_stride=self.sample_stride, + snippet_stride=self.snippet_stride, + fps=video_info["frame"] / video_info["duration"], + duration=video_info["duration"], + offset_frames=self.offset_frames, + **video_anno, + ) + ) + return results + + +@DATASETS.register_module() +class Ego4DResizeDataset(ResizeDataset): + def get_gt(self, video_info, thresh=0.0): + gt_segment = [] + gt_label = [] + for anno in video_info["annotations"]: + gt_start = int(anno["segment"][0]) + gt_end = int(anno["segment"][1]) + gt_scale = (gt_end - gt_start) / float(video_info["duration"]) + + if (not self.filter_gt) or (gt_scale > thresh): + gt_segment.append([gt_start, gt_end]) + gt_label.append(self.class_map.index(anno["label"])) + + if len(gt_segment) == 0: # have no valid gt + return None + else: + annotation = dict( + gt_segments=np.array(gt_segment, dtype=np.float32), + gt_labels=np.array(gt_label, dtype=np.int32), + ) + return filter_same_annotation(annotation) + + def __getitem__(self, index): + video_name, video_info, video_anno = self.data_list[index] + + results = self.pipeline( + dict( + video_name=video_name, + data_path=self.data_path, + resize_length=self.resize_length, + sample_stride=self.sample_stride, + fps=-1, + duration=video_info["duration"], + **video_anno, + ) + ) + return results + + +@DATASETS.register_module() +class Ego4DSlidingDataset(SlidingWindowDataset): + def get_gt(self, video_info, thresh=0.0): + gt_segment = [] + gt_label = [] + for anno in video_info["annotations"]: + gt_start = int(anno["segment"][0] / video_info["duration"] * video_info["frame"]) + gt_end = int(anno["segment"][1] / video_info["duration"] * video_info["frame"]) + + if (not self.filter_gt) or (gt_end - gt_start > thresh): + gt_segment.append([gt_start, gt_end]) + gt_label.append(self.class_map.index(anno["label"])) + + if len(gt_segment) == 0: # have no valid gt + return None + else: + annotation = dict( + gt_segments=np.array(gt_segment, dtype=np.float32), + gt_labels=np.array(gt_label, dtype=np.int32), + ) + return filter_same_annotation(annotation) + + def __getitem__(self, index): + video_name, video_info, video_anno, window_snippet_centers = self.data_list[index] + + if video_anno != {}: + video_anno["gt_segments"] = video_anno["gt_segments"] - window_snippet_centers[0] - self.offset_frames + video_anno["gt_segments"] = video_anno["gt_segments"] / self.snippet_stride + + results = self.pipeline( + dict( + video_name=video_name, + data_path=self.data_path, + window_size=self.window_size, + # trunc window setting + feature_start_idx=int(window_snippet_centers[0] / self.snippet_stride), + feature_end_idx=int(window_snippet_centers[-1] / self.snippet_stride), + sample_stride=self.sample_stride, + # sliding post process setting + fps=video_info["frame"] / video_info["duration"], + snippet_stride=self.snippet_stride, + window_start_frame=window_snippet_centers[0], + duration=video_info["duration"], + offset_frames=self.offset_frames, + # training setting + **video_anno, + ) + ) + return results diff --git a/OpenTAD/opentad/datasets/epic_kitchens.py b/OpenTAD/opentad/datasets/epic_kitchens.py new file mode 100644 index 0000000000000000000000000000000000000000..6b12deeb175c8551c2595787ef013c0104255095 --- /dev/null +++ b/OpenTAD/opentad/datasets/epic_kitchens.py @@ -0,0 +1,98 @@ +import numpy as np +from .base import SlidingWindowDataset, PaddingDataset, filter_same_annotation +from .builder import DATASETS + + +@DATASETS.register_module() +class EpicKitchensPaddingDataset(PaddingDataset): + def get_gt(self, video_info, thresh=0.0): + gt_segment = [] + gt_label = [] + for anno in video_info["annotations"]: + gt_start = int(anno["segment"][0] * self.fps) + gt_end = int(anno["segment"][1] * self.fps) + + if (not self.filter_gt) or (gt_end - gt_start > thresh): + gt_segment.append([gt_start, gt_end]) + gt_label.append(self.class_map.index(anno["label"])) + + if len(gt_segment) == 0: # have no valid gt + return None + else: + annotation = dict( + gt_segments=np.array(gt_segment, dtype=np.float32), + gt_labels=np.array(gt_label, dtype=np.int32), + ) + return filter_same_annotation(annotation) + + def __getitem__(self, index): + video_name, video_info, video_anno = self.data_list[index] + + if video_anno != {}: + video_anno["gt_segments"] = video_anno["gt_segments"] - self.offset_frames + video_anno["gt_segments"] = video_anno["gt_segments"] / self.snippet_stride + + results = self.pipeline( + dict( + video_name=video_name, + data_path=self.data_path, + sample_stride=self.sample_stride, + snippet_stride=self.snippet_stride, + fps=self.fps, + duration=video_info["duration"], + offset_frames=self.offset_frames, + **video_anno, + ) + ) + return results + + +@DATASETS.register_module() +class EpicKitchensSlidingDataset(SlidingWindowDataset): + def get_gt(self, video_info, thresh=0.0): + gt_segment = [] + gt_label = [] + for anno in video_info["annotations"]: + gt_start = int(anno["segment"][0] * self.fps) + gt_end = int(anno["segment"][1] * self.fps) + + if (not self.filter_gt) or (gt_end - gt_start > thresh): + gt_segment.append([gt_start, gt_end]) + gt_label.append(self.class_map.index(anno["label"])) + + if len(gt_segment) == 0: # have no valid gt + return None + else: + annotation = dict( + gt_segments=np.array(gt_segment, dtype=np.float32), + gt_labels=np.array(gt_label, dtype=np.int32), + ) + return filter_same_annotation(annotation) + + def __getitem__(self, index): + video_name, video_info, video_anno, window_snippet_centers = self.data_list[index] + + if video_anno != {}: + video_anno["gt_segments"] = video_anno["gt_segments"] - window_snippet_centers[0] - self.offset_frames + video_anno["gt_segments"] = video_anno["gt_segments"] / self.snippet_stride + + results = self.pipeline( + dict( + video_name=video_name, + data_path=self.data_path, + window_size=self.window_size, + # trunc window setting + feature_start_idx=int(window_snippet_centers[0] / self.snippet_stride), + feature_end_idx=int(window_snippet_centers[-1] / self.snippet_stride), + sample_stride=self.sample_stride, + # sliding post process setting + fps=self.fps, + snippet_stride=self.snippet_stride, + window_start_frame=window_snippet_centers[0], + duration=video_info["duration"], + offset_frames=self.offset_frames, + # training setting + **video_anno, + ) + ) + return results diff --git a/OpenTAD/opentad/datasets/thumos.py b/OpenTAD/opentad/datasets/thumos.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a5116df8bf58929248a82d9ebe4fc6f1c72fab --- /dev/null +++ b/OpenTAD/opentad/datasets/thumos.py @@ -0,0 +1,104 @@ +import numpy as np +from .base import SlidingWindowDataset, PaddingDataset, filter_same_annotation +from .builder import DATASETS + + +@DATASETS.register_module() +class ThumosSlidingDataset(SlidingWindowDataset): + def get_gt(self, video_info, thresh=0.0): + gt_segment = [] + gt_label = [] + for anno in video_info["annotations"]: + if anno["label"] == "Ambiguous": + continue + gt_start = int(anno["segment"][0] / video_info["duration"] * video_info["frame"]) + gt_end = int(anno["segment"][1] / video_info["duration"] * video_info["frame"]) + + if (not self.filter_gt) or (gt_end - gt_start > thresh): + gt_segment.append([gt_start, gt_end]) + gt_label.append(self.class_map.index(anno["label"])) + + if len(gt_segment) == 0: # have no valid gt + return None + else: + annotation = dict( + gt_segments=np.array(gt_segment, dtype=np.float32), + gt_labels=np.array(gt_label, dtype=np.int32), + ) + return filter_same_annotation(annotation) + + def __getitem__(self, index): + video_name, video_info, video_anno, window_snippet_centers = self.data_list[index] + + if video_anno != {}: + # frame divided by snippet stride inside current window + # this is only valid gt inside this window + video_anno["gt_segments"] = video_anno["gt_segments"] - window_snippet_centers[0] - self.offset_frames + video_anno["gt_segments"] = video_anno["gt_segments"] / self.snippet_stride + + results = self.pipeline( + dict( + video_name=video_name, + data_path=self.data_path, + window_size=self.window_size, + # trunc window setting + feature_start_idx=int(window_snippet_centers[0] / self.snippet_stride), + feature_end_idx=int(window_snippet_centers[-1] / self.snippet_stride), + sample_stride=self.sample_stride, + # sliding post process setting + fps=video_info["frame"] / video_info["duration"], + snippet_stride=self.snippet_stride, + window_start_frame=window_snippet_centers[0], + duration=video_info["duration"], + offset_frames=self.offset_frames, + # training setting + **video_anno, + ) + ) + return results + + +@DATASETS.register_module() +class ThumosPaddingDataset(PaddingDataset): + def get_gt(self, video_info, thresh=0.0): + gt_segment = [] + gt_label = [] + for anno in video_info["annotations"]: + if anno["label"] == "Ambiguous": + continue + gt_start = int(anno["segment"][0] / video_info["duration"] * video_info["frame"]) + gt_end = int(anno["segment"][1] / video_info["duration"] * video_info["frame"]) + + if (not self.filter_gt) or (gt_end - gt_start > thresh): + gt_segment.append([gt_start, gt_end]) + gt_label.append(self.class_map.index(anno["label"])) + + if len(gt_segment) == 0: # have no valid gt + return None + else: + annotation = dict( + gt_segments=np.array(gt_segment, dtype=np.float32), + gt_labels=np.array(gt_label, dtype=np.int32), + ) + return filter_same_annotation(annotation) + + def __getitem__(self, index): + video_name, video_info, video_anno = self.data_list[index] + + if video_anno != {}: + video_anno["gt_segments"] = video_anno["gt_segments"] - self.offset_frames + video_anno["gt_segments"] = video_anno["gt_segments"] / self.snippet_stride + + results = self.pipeline( + dict( + video_name=video_name, + data_path=self.data_path, + sample_stride=self.sample_stride, + snippet_stride=self.snippet_stride, + fps=video_info["frame"] / video_info["duration"], + duration=video_info["duration"], + offset_frames=self.offset_frames, + **video_anno, + ) + ) + return results diff --git a/OpenTAD/opentad/datasets/transforms/__init__.py b/OpenTAD/opentad/datasets/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25b9477ec811c8c53201fbc518d0a8b85130b2a3 --- /dev/null +++ b/OpenTAD/opentad/datasets/transforms/__init__.py @@ -0,0 +1,18 @@ +from .loading import LoadFeats, SlidingWindowTrunc, RandomTrunc +from .formatting import Collect, ConvertToTensor, Rearrange, Reduce, Padding, ChannelReduction +from .end_to_end import PrepareVideoInfo, LoadSnippetFrames, LoadFrames + +__all__ = [ + "LoadFeats", + "SlidingWindowTrunc", + "RandomTrunc", + "Collect", + "ConvertToTensor", + "Rearrange", + "Reduce", + "Padding", + "ChannelReduction", + "PrepareVideoInfo", + "LoadSnippetFrames", + "LoadFrames", +] diff --git a/OpenTAD/opentad/datasets/transforms/end_to_end.py b/OpenTAD/opentad/datasets/transforms/end_to_end.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ac350365abbccabe8a264191c666cbaccdec45 --- /dev/null +++ b/OpenTAD/opentad/datasets/transforms/end_to_end.py @@ -0,0 +1,348 @@ +import copy +import os +import pickle +import random +import torch +import random +import pandas as pd +import numpy as np + +from ..builder import PIPELINES +from torch.nn import functional as F + + +@PIPELINES.register_module() +class PrepareVideoInfo: + def __init__(self, format="mp4", modality="RGB", prefix=""): + self.format = format + self.modality = modality + self.prefix = prefix + + def __call__(self, results): + results["modality"] = self.modality + results["filename"] = os.path.join( + results["data_path"], + self.prefix + results["video_name"] + "." + self.format, + ) + return results + + +@PIPELINES.register_module() +class LoadSnippetFrames: + """Load the snippet frame, the output should follows the format: + snippet_num x channel x clip_len x height x width + """ + + def __init__( + self, + clip_len, + frame_interval=1, + method="resize", + trunc_len=None, + trunc_thresh=None, + crop_ratio=None, + ): + self.clip_len = clip_len + self.frame_interval = frame_interval + self.method = method # resize or padding or sliding window + # todo: support to change FPS + # random_trunc settings + self.trunc_len = trunc_len + self.trunc_thresh = trunc_thresh + self.crop_ratio = crop_ratio + + def random_trunc(self, feats, trunc_len, gt_segments, gt_labels, offset=0, max_num_trials=200): + feat_len = feats.shape[0] + num_segs = gt_segments.shape[0] + + trunc_len = trunc_len + if feat_len <= trunc_len: + if self.crop_ratio == None: # do nothing + return feats, gt_segments, gt_labels + else: # randomly crop the seq by setting trunc_len to a value in [l, r] + trunc_len = random.randint( + max(round(self.crop_ratio[0] * feat_len), 1), + min(round(self.crop_ratio[1] * feat_len), feat_len), + ) + # corner case + if feat_len == trunc_len: + return feats, gt_segments, gt_labels + + # try a few times till a valid truncation with at least one action + for _ in range(max_num_trials): + # sample a random truncation of the video feats + st = random.randint(0, feat_len - trunc_len) + ed = st + trunc_len + window = np.array([st, ed], dtype=np.float32) + + # compute the intersection between the sampled window and all segments + window = np.repeat(window[None, :], num_segs, axis=0) + left = np.maximum(window[:, 0] - offset, gt_segments[:, 0]) + right = np.minimum(window[:, 1] + offset, gt_segments[:, 1]) + inter = np.clip(right - left, a_min=0, a_max=None) + area_segs = np.abs(gt_segments[:, 1] - gt_segments[:, 0]) + inter_ratio = inter / area_segs + + # only select those segments over the thresh + seg_idx = inter_ratio >= self.trunc_thresh + + # with at least one action + if seg_idx.sum().item() > 0: + break + + feats = feats[st:ed] + gt_segments = np.stack((left[seg_idx], right[seg_idx]), axis=1) # [N,2] in feature grids + gt_segments = gt_segments - st # shift the time stamps due to truncation + gt_labels = gt_labels[seg_idx] # [N] + return feats, gt_segments, gt_labels + + def __call__(self, results): + assert "total_frames" in results.keys(), "should have total_frames as a key" + total_frames = results["total_frames"] + fps = results["avg_fps"] + + if self.method == "resize": + assert "resize_length" in results.keys(), "should have resize_length as a key" + snippet_num = results["resize_length"] + snippet_stride = total_frames / snippet_num + snippet_center = np.arange( + snippet_stride / 2 - 0.5, + total_frames + snippet_stride / 2 - 0.5, + snippet_stride, + ) + masks = torch.ones(results["resize_length"]).bool() + + # don't forget to resize the ground truth segments + if "gt_segments" in results.keys(): + # convert gt seconds to feature grid + results["gt_segments"] = np.clip(results["gt_segments"] / results["duration"], 0.0, 1.0) + results["gt_segments"] *= results["resize_length"] + + elif self.method == "random_trunc": + snippet_num = self.trunc_len + snippet_center = np.arange(0, total_frames, results["snippet_stride"]) + + # trunc the snippet_center + snippet_center, gt_segments, gt_labels = self.random_trunc( + snippet_center, + trunc_len=snippet_num, + gt_segments=results["gt_segments"], + gt_labels=results["gt_labels"], + ) + + # update the gt_segments + results["gt_segments"] = gt_segments + results["gt_labels"] = gt_labels + + # pad the snippet_center + if len(snippet_center) < snippet_num: + valid_len = len(snippet_center) + snippet_center = np.pad(snippet_center, (0, snippet_num - valid_len), mode="edge") + masks = torch.cat([torch.ones(valid_len), torch.zeros(snippet_num - valid_len)]).bool() + else: + masks = torch.ones(snippet_num).bool() + + elif self.method == "sliding_window": + snippet_num = results["window_size"] + snippet_center = np.arange(0, total_frames, results["snippet_stride"]) + + start_idx = min(results["feature_start_idx"], len(snippet_center)) + end_idx = min((results["feature_end_idx"] + 1), len(snippet_center)) + + snippet_center = snippet_center[start_idx:end_idx] + + if len(snippet_center) < snippet_num: + valid_len = len(snippet_center) + snippet_center = np.pad(snippet_center, (0, snippet_num - valid_len), mode="edge") + masks = torch.cat([torch.ones(valid_len), torch.zeros(snippet_num - valid_len)]).bool() + else: + masks = torch.ones(snippet_num).bool() + elif self.method == "padding": + raise NotImplementedError + + # extend snippet center to a clip + clip_idxs = np.arange(-(self.clip_len // 2), self.clip_len // 2) + frame_idxs = snippet_center[:, None] + self.frame_interval * clip_idxs[None, :] # [snippet_num, clip_len] + + # truncate to [0, total_frames-1], and round to int + frame_idxs = np.clip(frame_idxs, 0, total_frames - 1).round() + + assert frame_idxs.shape[0] == snippet_num, "snippet center number should be equal to snippet number" + assert frame_idxs.shape[1] == self.clip_len, "snippet length should be equal to clip length" + + results["frame_inds"] = frame_idxs.astype(int) + results["num_clips"] = snippet_num + results["clip_len"] = self.clip_len + results["masks"] = masks + return results + + +@PIPELINES.register_module() +class LoadFrames: + def __init__( + self, + num_clips=1, + scale_factor=1, + method="resize", + trunc_len=None, + trunc_thresh=None, + crop_ratio=None, + ): + self.num_clips = num_clips + self.scale_factor = scale_factor # multiply by the frame number, if backbone has downsampling + self.method = method # resize or padding or random_trunc or sliding_window + # random_trunc settings + self.trunc_len = trunc_len + self.trunc_thresh = trunc_thresh + self.crop_ratio = crop_ratio + + def random_trunc(self, feats, trunc_len, gt_segments, gt_labels, offset=0, max_num_trials=200): + feat_len = feats.shape[0] + num_segs = gt_segments.shape[0] + + trunc_len = trunc_len + if feat_len <= trunc_len: + if self.crop_ratio == None: # do nothing + return feats, gt_segments, gt_labels + else: # randomly crop the seq by setting trunc_len to a value in [l, r] + trunc_len = random.randint( + max(round(self.crop_ratio[0] * feat_len), 1), + min(round(self.crop_ratio[1] * feat_len), feat_len), + ) + # corner case + if feat_len == trunc_len: + return feats, gt_segments, gt_labels + + # try a few times till a valid truncation with at least one action + for _ in range(max_num_trials): + # sample a random truncation of the video feats + st = random.randint(0, feat_len - trunc_len) + ed = st + trunc_len + window = np.array([st, ed], dtype=np.float32) + + # compute the intersection between the sampled window and all segments + window = np.repeat(window[None, :], num_segs, axis=0) + left = np.maximum(window[:, 0] - offset, gt_segments[:, 0]) + right = np.minimum(window[:, 1] + offset, gt_segments[:, 1]) + inter = np.clip(right - left, a_min=0, a_max=None) + area_segs = np.abs(gt_segments[:, 1] - gt_segments[:, 0]) + inter_ratio = inter / area_segs + + # only select those segments over the thresh + seg_idx = inter_ratio >= self.trunc_thresh + + # with at least one action + if seg_idx.sum().item() > 0: + break + + feats = feats[st:ed] + gt_segments = np.stack((left[seg_idx], right[seg_idx]), axis=1) # [N,2] in feature grids + gt_segments = gt_segments - st # shift the time stamps due to truncation + gt_labels = gt_labels[seg_idx] # [N] + return feats, gt_segments, gt_labels + + def __call__(self, results): + assert "total_frames" in results.keys(), "should have total_frames as a key" + total_frames = results["total_frames"] + fps = results["avg_fps"] + + if self.method == "resize": + assert "resize_length" in results.keys(), "should have resize_length as a key" + frame_num = results["resize_length"] * self.scale_factor + frame_stride = total_frames / frame_num + frame_idxs = np.arange( + frame_stride / 2 - 0.5, + total_frames + frame_stride / 2 - 0.5, + frame_stride, + ) + masks = torch.ones(results["resize_length"]).bool() # should not multiply by scale_factor + + # don't forget to resize the ground truth segments + if "gt_segments" in results.keys(): + # convert gt seconds to feature grid + results["gt_segments"] = np.clip(results["gt_segments"] / results["duration"], 0.0, 1.0) + results["gt_segments"] *= results["resize_length"] + + elif self.method == "random_trunc": + assert results["snippet_stride"] >= self.scale_factor, "snippet_stride should be larger than scale_factor" + assert ( + results["snippet_stride"] % self.scale_factor == 0 + ), "snippet_stride should be divisible by scale_factor" + + frame_num = self.trunc_len * self.scale_factor + frame_stride = results["snippet_stride"] // self.scale_factor + frame_idxs = np.arange(0, total_frames, frame_stride) + + # trunc the frame_idxs + frame_idxs, gt_segments, gt_labels = self.random_trunc( + frame_idxs, + trunc_len=frame_num, + gt_segments=results["gt_segments"] * self.scale_factor, # gt segment should be mapped to frame level + gt_labels=results["gt_labels"], + ) + results["gt_segments"] = gt_segments / self.scale_factor # convert back to original scale + results["gt_labels"] = gt_labels + + # pad the frame_idxs + if len(frame_idxs) < frame_num: + valid_len = len(frame_idxs) // self.scale_factor + frame_idxs = np.pad(frame_idxs, (0, frame_num - len(frame_idxs)), mode="edge") + masks = torch.cat([torch.ones(valid_len), torch.zeros(self.trunc_len - valid_len)]).bool() + else: + masks = torch.ones(self.trunc_len).bool() + + elif self.method == "sliding_window": + assert results["snippet_stride"] >= self.scale_factor, "snippet_stride should be larger than scale_factor" + assert ( + results["snippet_stride"] % self.scale_factor == 0 + ), "snippet_stride should be divisible by scale_factor" + + window_size = results["window_size"] + frame_num = window_size * self.scale_factor + frame_stride = results["snippet_stride"] // self.scale_factor + frame_idxs = np.arange(0, total_frames, frame_stride) + + start_idx = min(results["feature_start_idx"] * self.scale_factor, len(frame_idxs)) + end_idx = min((results["feature_end_idx"] + 1) * self.scale_factor, len(frame_idxs)) + + frame_idxs = frame_idxs[start_idx:end_idx] + + if len(frame_idxs) < frame_num: + valid_len = len(frame_idxs) // self.scale_factor + frame_idxs = np.pad(frame_idxs, (0, frame_num - len(frame_idxs)), mode="edge") + masks = torch.cat([torch.ones(valid_len), torch.zeros(window_size - valid_len)]).bool() + else: + masks = torch.ones(window_size).bool() + + elif self.method == "padding": + raise NotImplementedError + + # truncate to [0, total_frames-1], and round to int + frame_idxs = np.clip(frame_idxs, 0, total_frames - 1).round() + + assert frame_idxs.shape[0] == frame_num, "snippet center number should be equal to snippet number" + + results["frame_inds"] = frame_idxs.astype(int) + results["num_clips"] = self.num_clips + results["clip_len"] = frame_num // self.num_clips + results["masks"] = masks + return results + + +@PIPELINES.register_module() +class Interpolate: + def __init__(self, keys, size=128, mode="linear"): + self.keys = keys + self.size = size + self.mode = mode + + def __call__(self, results): + for key in self.keys: + if results[key].shape[2:] != self.size: + results[key] = F.interpolate( + results[key], + size=self.size, + mode=self.mode, + align_corners=False, + ) + return results diff --git a/OpenTAD/opentad/datasets/transforms/formatting.py b/OpenTAD/opentad/datasets/transforms/formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..c9f07c0dcd5dfd631bde5a782fdfdf9e44a84e1a --- /dev/null +++ b/OpenTAD/opentad/datasets/transforms/formatting.py @@ -0,0 +1,287 @@ +import torch +import torch.nn.functional as F +import torchvision +import scipy +import numpy as np +from collections.abc import Sequence +from einops import rearrange, reduce + +from ..builder import PIPELINES + + +def to_tensor(data): + """Convert objects of various python types to :obj:`torch.Tensor`. + Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, + :class:`Sequence`, :class:`int` and :class:`float`. + """ + if isinstance(data, torch.Tensor): + return data + if isinstance(data, np.ndarray): + return torch.from_numpy(data) + if isinstance(data, Sequence): + return torch.tensor(data) + if isinstance(data, int): + return torch.LongTensor([data]) + if isinstance(data, float): + return torch.FloatTensor([data]) + raise TypeError(f"type {type(data)} cannot be converted to tensor.") + + +@PIPELINES.register_module() +class Collect: + def __init__( + self, + inputs, + keys=[], + meta_keys=[ + "video_name", + "data_path", + "fps", + "duration", + "snippet_stride", + "window_start_frame", + "resize_length", + "window_size", + "offset_frames", + ], + ): + self.inputs = inputs + self.keys = keys + self.meta_keys = meta_keys + + def __call__(self, results): + data = {} + + # input key + data["inputs"] = results[self.inputs] # [C,T] + + # AutoAugment key: gt_segments, gt_labels, masks + for key in self.keys: + if key == "masks" and key not in results.keys(): + results["masks"] = torch.ones(data["inputs"].shape[-1]).bool() + data[key] = results[key] + + # meta keys + if len(self.meta_keys) != 0: + meta = {} + for key in self.meta_keys: + if key in results.keys(): + meta[key] = results[key] + data["metas"] = meta + + return data + + def __repr__(self): + return f"{self.__class__.__name__}(" f"keys={self.keys}, meta_keys={self.meta_keys}, " + + +@PIPELINES.register_module() +class ConvertToTensor: + def __init__(self, keys): + self.keys = keys + + def __call__(self, results): + for key in self.keys: + results[key] = to_tensor(results[key]) + return results + + def __repr__(self): + return f"{self.__class__.__name__}(keys={self.keys})" + + +@PIPELINES.register_module() +class Rearrange: + def __init__(self, keys, ops, **kwargs): + self.keys = keys + self.ops = ops + self.kwargs = kwargs + + def __call__(self, results): + for key in self.keys: + results[key] = rearrange(results[key], self.ops, **self.kwargs) + return results + + def __repr__(self): + return f"{self.__class__.__name__}(keys={self.keys}ops={self.ops})" + + +@PIPELINES.register_module() +class Reduce: + def __init__(self, keys, ops, reduction): + self.keys = keys + self.ops = ops + self.reduction = reduction + + def __call__(self, results): + for key in self.keys: + results[key] = reduce(results[key], self.ops, reduction=self.reduction) + return results + + def __repr__(self): + return f"{self.__class__.__name__}(keys={self.keys}ops={self.ops})reduction={self.reduction}" + + +@PIPELINES.register_module() +class ResizeFeat: + def __init__(self, tool, channel_first=False): + self.tool = tool + self.channel_first = channel_first + + @torch.no_grad() + def torchvision_align(self, feat, tscale): + # input feat shape [C,T] + pseudo_input = feat.unsqueeze(0).unsqueeze(3) # [1,C,T,1] + pseudo_bbox = torch.Tensor([[0, 0, 0, 1, feat.shape[1]]]) + # output feat shape [C,tscale] + output = torchvision.ops.roi_align( + pseudo_input.half().double(), + pseudo_bbox.half().double(), + output_size=(tscale, 1), + aligned=True, + ).to(pseudo_input.dtype) + output = output.squeeze(0).squeeze(-1) + return output + + @torch.no_grad() + def gtad_align(self, feat): + raise "not implement yet" + + @torch.no_grad() + def bmn_align(self, feat, tscale, num_bin=1, num_sample_bin=3, pool_type="mean"): + feat = feat.numpy() + C, T = feat.shape + + # x is the temporal location corresponding to each location in feature sequence + x = [0.5 + ii for ii in range(T)] + f = scipy.interpolate.interp1d(x, feat, axis=1) + + video_feature = [] + zero_sample = np.zeros(num_bin * C) + tmp_anchor_xmin = [1.0 / tscale * i for i in range(tscale)] + tmp_anchor_xmax = [1.0 / tscale * i for i in range(1, tscale + 1)] + + num_sample = num_bin * num_sample_bin + for idx in range(tscale): + xmin = max(x[0] + 0.0001, tmp_anchor_xmin[idx] * T) + xmax = min(x[-1] - 0.0001, tmp_anchor_xmax[idx] * T) + if xmax < x[0]: + video_feature.append(zero_sample) + continue + if xmin > x[-1]: + video_feature.append(zero_sample) + continue + + plen = (xmax - xmin) / (num_sample - 1) + x_new = [xmin + plen * ii for ii in range(num_sample)] + y_new = f(x_new) + y_new_pool = [] + for b in range(num_bin): + tmp_y_new = y_new[:, num_sample_bin * b : num_sample_bin * (b + 1)] + if pool_type == "mean": + tmp_y_new = np.mean(tmp_y_new, axis=1) + elif pool_type == "max": + tmp_y_new = np.max(tmp_y_new, axis=1) + y_new_pool.append(tmp_y_new) + y_new_pool = np.stack(y_new_pool, axis=1).reshape(-1) + # y_new_pool = np.reshape(y_new_pool, [-1]) + video_feature.append(y_new_pool) + video_feature = np.stack(video_feature, axis=1) + return torch.from_numpy(video_feature) + + @torch.no_grad() + def torch_interpolate(self, feat, tscale): + # input feat shape [C,T] + feats = F.interpolate(feat.unsqueeze(0), size=tscale, mode="linear", align_corners=False).squeeze(0) + return feats + + def __call__(self, results): + assert "resize_length" in results.keys(), "should have resize_length as a key" + tscale = results["resize_length"] + + if not self.channel_first: + feats = results["feats"].permute(1, 0) # [T,C] -> [C,T] + else: + feats = results["feats"] + + assert isinstance(feats, torch.Tensor) + assert feats.ndim == 2 # [C,T] + + if self.tool == "torchvision_align": + resized_feat = self.torchvision_align(feats, tscale) + elif self.tool == "gtad_align": + resized_feat = self.gtad_align(feats, tscale) + elif self.tool == "bmn_align": + resized_feat = self.bmn_align(feats, tscale) + elif self.tool == "interpolate": + resized_feat = self.torch_interpolate(feats, tscale) + + assert resized_feat.shape[0] == feats.shape[0] + assert resized_feat.shape[1] == tscale + + if "gt_segments" in results.keys(): + # convert gt seconds to feature grid + results["gt_segments"] = (results["gt_segments"] / results["duration"]).clamp(min=0.0, max=1.0) + results["gt_segments"] *= tscale + + results["feats_len_ori"] = results["feats"].shape[1] # for future usage + if not self.channel_first: + results["feats"] = resized_feat.permute(1, 0) # [C,T] -> [T,C] + else: + results["feats"] = resized_feat + return results + + +@PIPELINES.register_module() +class Padding: + def __init__(self, length, pad_value=0, channel_first=False): + self.length = length + self.pad_value = pad_value + self.channel_first = channel_first + + def __call__(self, results): + assert "feats" in results.keys(), "should have feats as a key" + assert results["feats"].ndim == 2, "feats should be 2 dim" + + if self.channel_first: + feats = results["feats"].permute(1, 0) + else: + feats = results["feats"] + + assert ( + feats.shape[0] <= self.length + ), "feature length should be smaller than padding length, but now we have {}".format(results["feats"].shape) + + feat_len = feats.shape[0] + if feat_len < self.length: + pad = torch.ones((self.length - feat_len, feats.shape[1])) * self.pad_value + new_feats = torch.cat((feats, pad), dim=0) + + if self.channel_first: + results["feats"] = new_feats.permute(1, 0) + else: + results["feats"] = new_feats + + pad_masks = torch.zeros(self.length - feat_len).bool() + if "masks" in results.keys(): + results["masks"] = torch.cat((results["masks"], pad_masks), dim=0) + else: + results["masks"] = torch.cat((torch.ones(feat_len).bool(), pad_masks), dim=0) + return results + + +@PIPELINES.register_module() +class ChannelReduction: + """Select features along the channel dimension.""" + + def __init__(self, in_channels, index): + self.in_channels = in_channels + self.index = index + assert len(self.index) == 2 + + def __call__(self, results): + assert isinstance(results["feats"], torch.Tensor) + assert results["feats"].shape[1] == self.in_channels # [T,C] + + # select the features + results["feats"] = results["feats"][:, self.index[0] : self.index[1]] + return results diff --git a/OpenTAD/opentad/datasets/transforms/loading.py b/OpenTAD/opentad/datasets/transforms/loading.py new file mode 100644 index 0000000000000000000000000000000000000000..23d2429cedd6088665617caf1dc6c9543d8c2dc7 --- /dev/null +++ b/OpenTAD/opentad/datasets/transforms/loading.py @@ -0,0 +1,263 @@ +import copy +import os +import pickle +import random +import torch +import random +import pandas as pd +import numpy as np + +from ..builder import PIPELINES +from torch.nn import functional as F + + +@PIPELINES.register_module() +class LoadFeats: + def __init__(self, feat_format, prefix="", suffix=""): + self.feat_format = feat_format + self.prefix = prefix + self.suffix = suffix + # check feat format + if isinstance(self.feat_format, str): + self.check_feat_format(self.feat_format) + elif isinstance(self.feat_format, list): + for feat_format in self.feat_format: + self.check_feat_format(feat_format) + + def check_feat_format(self, feat_format): + assert feat_format in ["npy", "npz", "pt", "csv", "pkl"], print(f"not support {feat_format}") + + def read_from_tensor(self, file_path): + feats = torch.load(file_path).float() + return feats + + def read_from_npy(self, file_path): + feats = np.load(file_path).astype(np.float32) + return feats + + def read_from_npz(self, file_path): + feats = np.load(file_path)["feats"].astype(np.float32) + return feats + + def read_from_csv(self, file_path): + feats = pd.read_csv(file_path, dtype="float32").to_numpy() + feats = feats.astype(np.float32) + return feats + + def read_from_pkl(self, file_path): + feats = pickle.load(open(file_path, "rb")) + feats = feats.astype(np.float32) + return feats + + def load_single_feat(self, file_path, feat_format): + try: + if feat_format == "npy": + feats = self.read_from_npy(file_path) + elif self.feat_format == "npz": + feats = self.read_from_npz(file_path) + elif feat_format == "pt": + feats = self.read_from_tensor(file_path) + elif feat_format == "csv": + feats = self.read_from_csv(file_path) + elif feat_format == "pkl": + feats = self.read_from_pkl(file_path) + except: + print("Missing data:", file_path) + exit() + return feats + + def __call__(self, results): + video_name = results["video_name"] + + if isinstance(results["data_path"], str): + file_path = os.path.join(results["data_path"], f"{self.prefix}{video_name}{self.suffix}.{self.feat_format}") + feats = self.load_single_feat(file_path, self.feat_format) + elif isinstance(results["data_path"], list): + feats = [] + + # check if the feat_format is a list + if isinstance(self.feat_format, str): + self.feat_format = [self.feat_format] * len(results["data_path"]) + + for data_path, feat_format in zip(results["data_path"], self.feat_format): + file_path = os.path.join(data_path, f"{self.prefix}{video_name}{self.suffix}.{feat_format}") + feats.append(self.load_single_feat(file_path, feat_format)) + + max_len = max([feat.shape[0] for feat in feats]) + for i in range(len(feats)): + if feats[i].shape[0] != max_len: + # assume the first dimension is T + tmp_feat = F.interpolate( + torch.Tensor(feats[i]).permute(1, 0).unsqueeze(0), + size=max_len, + mode="linear", + align_corners=False, + ).squeeze(0) + feats[i] = tmp_feat.permute(1, 0).numpy() + feats = np.concatenate(feats, axis=1) + + # sample the feature + sample_stride = results.get("sample_stride", 1) + if sample_stride > 1: + feats = feats[::sample_stride] + + results["feats"] = feats + return results + + def __repr__(self): + repr_str = f"{self.__class__.__name__}(" f"feat_format={self.feat_format}" + return repr_str + + +@PIPELINES.register_module() +class SlidingWindowTrunc: + """This is used for sliding window dataset, which will give a window start and window end in the result dict, + and we will extract the window features, also pad to fixed length""" + + def __init__(self, with_mask=True): + self.with_mask = with_mask + + def __call__(self, results): + assert "window_size" in results.keys(), "should have window_size as a key" + assert isinstance(results["feats"], torch.Tensor) + window_size = results["window_size"] + + feats_length = results["feats"].shape[0] + start_idx = min(results["feature_start_idx"], feats_length) + end_idx = min(results["feature_end_idx"] + 1, feats_length) + + window_feats = results["feats"][start_idx:end_idx] + valid_len = window_feats.shape[0] + + # if the valid window is smaller than window size, pad with -1 + if valid_len < window_size: + pad_data = torch.zeros(window_size - valid_len, window_feats.shape[1]) + window_feats = torch.cat((window_feats, pad_data), dim=0) + + # if we need padding mask (valid is 1, pad is 0) + if self.with_mask: + if valid_len < window_size: + masks = torch.cat([torch.ones(valid_len), torch.zeros(window_size - valid_len)]) + else: + masks = torch.ones(window_size) + results["masks"] = masks.bool() + + results["feats"] = window_feats.float() + return results + + +@PIPELINES.register_module() +class RandomTrunc: + """Crops features within a window such that they have a large overlap with ground truth segments. + Withing the cropping ratio, the length is sampled.""" + + def __init__( + self, + trunc_len, + trunc_thresh, + crop_ratio=None, + max_num_trials=200, + has_action=True, + no_trunc=False, + pad_value=0, + channel_first=False, + ): + self.trunc_len = trunc_len + self.trunc_thresh = trunc_thresh + self.crop_ratio = crop_ratio + self.max_num_trials = max_num_trials + self.has_action = has_action + self.no_trunc = no_trunc + self.pad_value = pad_value + self.channel_first = channel_first + + def trunc_features(self, feats, gt_segments, gt_labels, offset): + feat_len = feats.shape[0] + num_segs = gt_segments.shape[0] + + trunc_len = self.trunc_len + if feat_len <= self.trunc_len: + if self.crop_ratio == None: # do nothing + return feats, gt_segments, gt_labels + else: # randomly crop the seq by setting trunc_len to a value in [l, r] + trunc_len = random.randint( + max(round(self.crop_ratio[0] * feat_len), 1), + min(round(self.crop_ratio[1] * feat_len), feat_len), + ) + # corner case + if feat_len == trunc_len: + return feats, gt_segments, gt_labels + + # try a few times till a valid truncation with at least one action + for _ in range(self.max_num_trials): + # sample a random truncation of the video feats + st = random.randint(0, feat_len - trunc_len) + ed = st + trunc_len + window = torch.as_tensor([st, ed], dtype=torch.float32) + + # compute the intersection between the sampled window and all segments + window = window[None].repeat(num_segs, 1) + left = torch.maximum(window[:, 0] - offset, gt_segments[:, 0]) + right = torch.minimum(window[:, 1] + offset, gt_segments[:, 1]) + inter = (right - left).clamp(min=0) + area_segs = torch.abs(gt_segments[:, 1] - gt_segments[:, 0]) + inter_ratio = inter / area_segs + + # only select those segments over the thresh + seg_idx = inter_ratio >= self.trunc_thresh + + if self.no_trunc: + # with at least one action and not truncating any actions + seg_trunc_idx = (inter_ratio > 0.0) & (inter_ratio < 1.0) + if (seg_idx.sum().item() > 0) and (seg_trunc_idx.sum().item() == 0): + break + elif self.has_action: + # with at least one action + if seg_idx.sum().item() > 0: + break + else: + # without any constraints + break + + feats = feats[st:ed, :] # [T,C] + gt_segments = torch.stack((left[seg_idx], right[seg_idx]), dim=1) # [N,2] in feature grids + gt_segments = gt_segments - st # shift the time stamps due to truncation + gt_labels = gt_labels[seg_idx] # [N] + return feats, gt_segments, gt_labels + + def pad_features(self, feats): + feat_len = feats.shape[0] + if feat_len < self.trunc_len: + feats_pad = torch.ones((self.trunc_len - feat_len,) + feats.shape[1:]) * self.pad_value + feats = torch.cat([feats, feats_pad], dim=0) + masks = torch.cat([torch.ones(feat_len), torch.zeros(self.trunc_len - feat_len)]) + return feats, masks + else: + return feats, torch.ones(feat_len) + + def __call__(self, results): + assert isinstance(results["feats"], torch.Tensor) + offset = 0 + + if self.channel_first: + results["feats"] = results["feats"].transpose(0, 1) # [C,T] -> [T,C] + + # truncate the features + feats, gt_segments, gt_labels = self.trunc_features( + results["feats"], + results["gt_segments"], + results["gt_labels"], + offset, + ) + + # pad the features to the fixed length + feats, masks = self.pad_features(feats) + + results["feats"] = feats.float() + results["masks"] = masks.bool() + results["gt_segments"] = gt_segments + results["gt_labels"] = gt_labels + + if self.channel_first: + results["feats"] = results["feats"].transpose(0, 1) # [T,C] -> [C,T] + return results diff --git a/OpenTAD/opentad/evaluations/__init__.py b/OpenTAD/opentad/evaluations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..794aa8315d13d7a7ac5ba9ece76563c250217923 --- /dev/null +++ b/OpenTAD/opentad/evaluations/__init__.py @@ -0,0 +1,5 @@ +from .builder import build_evaluator +from .mAP import mAP +from .recall import Recall + +__all__ = ["build_evaluator", "mAP", "Recall"] diff --git a/OpenTAD/opentad/evaluations/builder.py b/OpenTAD/opentad/evaluations/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..3c5b515ea2734553e5b355d62dc373afd6ec6f27 --- /dev/null +++ b/OpenTAD/opentad/evaluations/builder.py @@ -0,0 +1,30 @@ +from mmengine.registry import Registry + +EVALUATORS = Registry("evaluators") + + +def build_evaluator(cfg): + """Build evaluator.""" + return EVALUATORS.build(cfg) + + +def remove_duplicate_annotations(ants, tol=1e-3): + # remove duplicate annotations (same category and starting/ending time) + valid_events = [] + for event in ants: + s, e, l = event["segment"][0], event["segment"][1], event["label"] + # here, we add removing the events whose duration is 0, (HACS) + if e - s <= 0: + continue + valid = True + for p_event in valid_events: + if ( + (abs(s - p_event["segment"][0]) <= tol) + and (abs(e - p_event["segment"][1]) <= tol) + and (l == p_event["label"]) + ): + valid = False + break + if valid: + valid_events.append(event) + return valid_events diff --git a/OpenTAD/opentad/evaluations/mAP.py b/OpenTAD/opentad/evaluations/mAP.py new file mode 100644 index 0000000000000000000000000000000000000000..ce26f168efb4117649dc6d8cf9caf3f954b7c32e --- /dev/null +++ b/OpenTAD/opentad/evaluations/mAP.py @@ -0,0 +1,336 @@ +import json +import numpy as np +import pandas as pd +import multiprocessing as mp + +from .builder import EVALUATORS, remove_duplicate_annotations + + +@EVALUATORS.register_module() +class mAP: + def __init__( + self, + ground_truth_filename, + prediction_filename, + subset, + tiou_thresholds, + blocked_videos=None, + thread=16, + ): + super().__init__() + + if not ground_truth_filename: + raise IOError("Please input a valid ground truth file.") + if not prediction_filename: + raise IOError("Please input a valid prediction file.") + + self.subset = subset + self.tiou_thresholds = tiou_thresholds + self.gt_fields = ["database"] + self.pred_fields = ["results"] + self.thread = thread # multi-process workers + + # Get blocked videos + if blocked_videos is None: + self.blocked_videos = list() + else: + with open(blocked_videos) as json_file: + self.blocked_videos = json.load(json_file) + + # Import ground truth and predictions. + self.ground_truth, self.activity_index = self._import_ground_truth(ground_truth_filename) + self.prediction = self._import_prediction(prediction_filename) + + def _import_ground_truth(self, ground_truth_filename): + """Reads ground truth file, checks if it is well formatted, and returns + the ground truth instances and the activity classes. + + Parameters + ---------- + ground_truth_filename : str + Full path to the ground truth json file. + + Outputs + ------- + ground_truth : df + Data frame containing the ground truth instances. + activity_index : dict + Dictionary containing class index. + """ + with open(ground_truth_filename, "r") as fobj: + data = json.load(fobj) + # Checking format + if not all([field in list(data.keys()) for field in self.gt_fields]): + raise IOError("Please input a valid ground truth file.") + + # Read ground truth data. + activity_index, cidx = {}, 0 + video_lst, t_start_lst, t_end_lst, label_lst = [], [], [], [] + for videoid, v in data["database"].items(): + if self.subset != v["subset"]: + continue + if videoid in self.blocked_videos: + continue + + # remove duplicated instances following ActionFormer + v_anno = remove_duplicate_annotations(v["annotations"]) + + for ann in v_anno: + if ann["label"] not in activity_index: + activity_index[ann["label"]] = cidx + cidx += 1 + video_lst.append(videoid) + t_start_lst.append(float(ann["segment"][0])) + t_end_lst.append(float(ann["segment"][1])) + label_lst.append(activity_index[ann["label"]]) + + ground_truth = pd.DataFrame( + { + "video-id": video_lst, + "t-start": t_start_lst, + "t-end": t_end_lst, + "label": label_lst, + } + ) + return ground_truth, activity_index + + def _import_prediction(self, prediction_filename): + """Reads prediction file, checks if it is well formatted, and returns + the prediction instances. + + Parameters + ---------- + prediction_filename : str + Full path to the prediction json file. + + Outputs + ------- + prediction : df + Data frame containing the prediction instances. + """ + # if prediction_filename is a string, then json load + if isinstance(prediction_filename, str): + with open(prediction_filename, "r") as fobj: + data = json.load(fobj) + elif isinstance(prediction_filename, dict): + data = prediction_filename + else: + raise IOError(f"Type of prediction file is {type(prediction_filename)}.") + + # Checking format... + if not all([field in list(data.keys()) for field in self.pred_fields]): + raise IOError("Please input a valid prediction file.") + + # Read predictions. + video_lst, t_start_lst, t_end_lst = [], [], [] + label_lst, score_lst = [], [] + for video_id, v in data["results"].items(): + if video_id in self.blocked_videos: + continue + for result in v: + try: + label = self.activity_index[result["label"]] + except: + # this is because the predicted label is not in annotation + # such as the some classes only exists in train split, but not in val split + label = len(self.activity_index) + video_lst.append(video_id) + t_start_lst.append(float(result["segment"][0])) + t_end_lst.append(float(result["segment"][1])) + label_lst.append(label) + score_lst.append(result["score"]) + prediction = pd.DataFrame( + { + "video-id": video_lst, + "t-start": t_start_lst, + "t-end": t_end_lst, + "label": label_lst, + "score": score_lst, + } + ) + return prediction + + def wrapper_compute_average_precision(self, cidx_list): + """Computes average precision for a sub class list.""" + for cidx in cidx_list: + gt_idx = self.ground_truth["label"] == cidx + pred_idx = self.prediction["label"] == cidx + self.result_dict[cidx] = compute_average_precision_detection( + self.ground_truth.loc[gt_idx].reset_index(drop=True), + self.prediction.loc[pred_idx].reset_index(drop=True), + tiou_thresholds=self.tiou_thresholds, + ) + + def multi_thread_compute_average_precision(self): + self.result_dict = mp.Manager().dict() + + num_total = len(self.activity_index.values()) + num_activity_per_thread = num_total // self.thread + 1 + + processes = [] + for tid in range(self.thread): + num_start = int(tid * num_activity_per_thread) + num_end = min(num_start + num_activity_per_thread, num_total) + + p = mp.Process( + target=self.wrapper_compute_average_precision, + args=(list(self.activity_index.values())[num_start:num_end],), + ) + p.start() + processes.append(p) + + for p in processes: + p.join() + + ap = np.zeros((len(self.tiou_thresholds), len(self.activity_index.items()))) + for i, cidx in enumerate(self.activity_index.values()): + ap[:, cidx] = self.result_dict[i] + return ap + + def evaluate(self): + """Evaluates a prediction file. For the detection task we measure the + interpolated mean average precision to measure the performance of a + method. + """ + self.ap = self.multi_thread_compute_average_precision() + + self.mAPs = self.ap.mean(axis=1) + + self.average_mAP = self.mAPs.mean() + + metric_dict = dict(average_mAP=self.average_mAP) + for tiou, mAP in zip(self.tiou_thresholds, self.mAPs): + metric_dict[f"mAP@{tiou}"] = mAP + return metric_dict + + def logging(self, logger=None): + if logger == None: + pprint = print + else: + pprint = logger.info + + pprint("Loaded annotations from {} subset.".format(self.subset)) + pprint("Number of ground truth instances: {}".format(len(self.ground_truth))) + pprint("Number of predictions: {}".format(len(self.prediction))) + pprint("Fixed threshold for tiou score: {}".format(self.tiou_thresholds)) + pprint("Average-mAP: {:>4.2f} (%)".format(self.average_mAP * 100)) + for tiou, mAP in zip(self.tiou_thresholds, self.mAPs): + pprint("mAP at tIoU {:.2f} is {:>4.2f}%".format(tiou, mAP * 100)) + + +def compute_average_precision_detection(ground_truth, prediction, tiou_thresholds=np.linspace(0.5, 0.95, 10)): + """Compute average precision (detection task) between ground truth and + predictions data frames. If multiple predictions occurs for the same + predicted segment, only the one with highest score is matches as + true positive. This code is greatly inspired by Pascal VOC devkit. + + Parameters + ---------- + ground_truth : df + Data frame containing the ground truth instances. + Required fields: ['video-id', 't-start', 't-end'] + prediction : df + Data frame containing the prediction instances. + Required fields: ['video-id, 't-start', 't-end', 'score'] + tiou_thresholds : 1darray, optional + Temporal intersection over union threshold. + + Outputs + ------- + ap : float + Average precision score. + """ + npos = float(len(ground_truth)) + lock_gt = np.ones((len(tiou_thresholds), len(ground_truth))) * -1 + # Sort predictions by decreasing score order. + sort_idx = prediction["score"].values.argsort()[::-1] + prediction = prediction.loc[sort_idx].reset_index(drop=True) + + # Initialize true positive and false positive vectors. + tp = np.zeros((len(tiou_thresholds), len(prediction))) + fp = np.zeros((len(tiou_thresholds), len(prediction))) + + # Adaptation to query faster + ground_truth_gbvn = ground_truth.groupby("video-id") + + # Assigning true positive to truly grount truth instances. + for idx, this_pred in prediction.iterrows(): + try: + # Check if there is at least one ground truth in the video associated. + ground_truth_videoid = ground_truth_gbvn.get_group(this_pred["video-id"]) + except Exception as e: + fp[:, idx] = 1 + continue + + this_gt = ground_truth_videoid.reset_index() + tiou_arr = segment_iou(this_pred[["t-start", "t-end"]].values, this_gt[["t-start", "t-end"]].values) + # We would like to retrieve the predictions with highest tiou score. + tiou_sorted_idx = tiou_arr.argsort()[::-1] + for tidx, tiou_thr in enumerate(tiou_thresholds): + for jdx in tiou_sorted_idx: + if tiou_arr[jdx] < tiou_thr: + fp[tidx, idx] = 1 + break + if lock_gt[tidx, this_gt.loc[jdx]["index"]] >= 0: + continue + # Assign as true positive after the filters above. + tp[tidx, idx] = 1 + lock_gt[tidx, this_gt.loc[jdx]["index"]] = idx + break + + if fp[tidx, idx] == 0 and tp[tidx, idx] == 0: + fp[tidx, idx] = 1 + + ap = np.zeros(len(tiou_thresholds)) + + for tidx in range(len(tiou_thresholds)): + # Computing prec-rec + this_tp = np.cumsum(tp[tidx, :]).astype(float) + this_fp = np.cumsum(fp[tidx, :]).astype(float) + rec = this_tp / npos + prec = this_tp / (this_tp + this_fp) + ap[tidx] = interpolated_prec_rec(prec, rec) + return ap + + +def segment_iou(target_segment, candidate_segments): + """Compute the temporal intersection over union between a + target segment and all the test segments. + + Parameters + ---------- + target_segment : 1d array + Temporal target segment containing [starting, ending] times. + candidate_segments : 2d array + Temporal candidate segments containing N x [starting, ending] times. + + Outputs + ------- + tiou : 1d array + Temporal intersection over union score of the N's candidate segments. + """ + tt1 = np.maximum(target_segment[0], candidate_segments[:, 0]) + tt2 = np.minimum(target_segment[1], candidate_segments[:, 1]) + # Intersection including Non-negative overlap score. + segments_intersection = (tt2 - tt1).clip(0) + # Segment union. + segments_union = ( + (candidate_segments[:, 1] - candidate_segments[:, 0]) + + (target_segment[1] - target_segment[0]) + - segments_intersection + ) + # Compute overlap as the ratio of the intersection + # over union of two segments. + tIoU = segments_intersection.astype(float) / segments_union.clip(1e-8) + return tIoU + + +def interpolated_prec_rec(prec, rec): + """Interpolated AP - VOCdevkit from VOC 2011.""" + mprec = np.hstack([[0], prec, [0]]) + mrec = np.hstack([[0], rec, [1]]) + for i in range(len(mprec) - 1)[::-1]: + mprec[i] = max(mprec[i], mprec[i + 1]) + idx = np.where(mrec[1::] != mrec[0:-1])[0] + 1 + ap = np.sum((mrec[idx] - mrec[idx - 1]) * mprec[idx]) + return ap diff --git a/OpenTAD/opentad/evaluations/recall.py b/OpenTAD/opentad/evaluations/recall.py new file mode 100644 index 0000000000000000000000000000000000000000..d9f28d500f91863a827798b93970e04870097cc5 --- /dev/null +++ b/OpenTAD/opentad/evaluations/recall.py @@ -0,0 +1,326 @@ +import json +import numpy as np +import pandas as pd + +from .builder import EVALUATORS, remove_duplicate_annotations +from .mAP import segment_iou + + +@EVALUATORS.register_module() +class Recall: + def __init__( + self, + ground_truth_filename, + prediction_filename, + subset, + tiou_thresholds, + topk=[1, 5, 10, 100], + max_avg_nr_proposals=100, + blocked_videos=None, + ): + super().__init__() + + if not ground_truth_filename: + raise IOError("Please input a valid ground truth file.") + if not prediction_filename: + raise IOError("Please input a valid prediction file.") + + self.subset = subset + self.tiou_thresholds = tiou_thresholds + self.max_avg_nr_proposals = max_avg_nr_proposals + self.topk = [int(k) for k in topk] + self.gt_fields = ["database"] + self.pred_fields = ["results"] + + # Get blocked videos + if blocked_videos is None: + self.blocked_videos = list() + else: + with open(blocked_videos) as json_file: + self.blocked_videos = json.load(json_file) + + # Import ground truth and proposals. + self.ground_truth, self.activity_index = self._import_ground_truth(ground_truth_filename) + self.proposal = self._import_proposal(prediction_filename) + + def _import_ground_truth(self, ground_truth_filename): + """Reads ground truth file, checks if it is well formatted, and returns + the ground truth instances and the activity classes. + Parameters + ---------- + ground_truth_filename : str + Full path to the ground truth json file. + Outputs + ------- + ground_truth : df + Data frame containing the ground truth instances. + activity_index : dict + Dictionary containing class index. + """ + with open(ground_truth_filename, "r") as fobj: + data = json.load(fobj) + # Checking format + if not all([field in list(data.keys()) for field in self.gt_fields]): + raise IOError("Please input a valid ground truth file.") + + # Read ground truth data. + activity_index, cidx = {}, 0 + video_lst, t_start_lst, t_end_lst, label_lst = [], [], [], [] + for videoid, v in data["database"].items(): + if self.subset != v["subset"]: + continue + if videoid in self.blocked_videos: + continue + + # remove duplicated instances following ActionFormer + v_anno = remove_duplicate_annotations(v["annotations"]) + + for ann in v_anno: + if ann["label"] not in activity_index: + activity_index[ann["label"]] = cidx + cidx += 1 + video_lst.append(videoid) + t_start_lst.append(float(ann["segment"][0])) + t_end_lst.append(float(ann["segment"][1])) + label_lst.append(activity_index[ann["label"]]) + + ground_truth = pd.DataFrame( + { + "video-id": video_lst, + "t-start": t_start_lst, + "t-end": t_end_lst, + "label": label_lst, + } + ) + return ground_truth, activity_index + + def _import_proposal(self, proposal_filename): + """Reads proposal file, checks if it is well formatted, and returns + the proposal instances. + Parameters + ---------- + proposal_filename : str + Full path to the proposal json file. + Outputs + ------- + proposal : df + Data frame containing the proposal instances. + """ + # if prediction_filename is a string, then json load + if isinstance(proposal_filename, str): + with open(proposal_filename, "r") as fobj: + data = json.load(fobj) + elif isinstance(proposal_filename, dict): + data = proposal_filename + else: + raise IOError(f"Type of prediction file is {type(proposal_filename)}.") + + # Checking format... + if not all([field in list(data.keys()) for field in self.pred_fields]): + raise IOError("Please input a valid proposal file.") + + # Read predictions. + video_lst, t_start_lst, t_end_lst = [], [], [] + score_lst = [] + for videoid, v in data["results"].items(): + if videoid in self.blocked_videos: + continue + for result in v: + video_lst.append(videoid) + t_start_lst.append(float(result["segment"][0])) + t_end_lst.append(float(result["segment"][1])) + score_lst.append(result["score"]) + proposal = pd.DataFrame( + { + "video-id": video_lst, + "t-start": t_start_lst, + "t-end": t_end_lst, + "score": score_lst, + } + ) + return proposal + + def evaluate(self): + """Evaluates a prediction file. For the detection task we measure the + interpolated mean average precision to measure the performance of a + method. + """ + recall, avg_recall, proposals_per_video = average_recall_vs_avg_nr_proposals( + self.ground_truth, + self.proposal, + max_avg_nr_proposals=self.max_avg_nr_proposals, + tiou_thresholds=self.tiou_thresholds, + ) + + area_under_curve = np.trapz(avg_recall, proposals_per_video) + + self.recall = recall + self.avg_recall = avg_recall + self.proposals_per_video = proposals_per_video + self.auc = float(area_under_curve) / proposals_per_video[-1] + + metric_dict = dict(AUC=self.auc) + for k in self.topk: + metric_dict[f"AR@{k}"] = np.mean(self.recall[:, k - 1]) + return metric_dict + + def logging(self, logger=None): + if logger == None: + pprint = print + else: + pprint = logger.info + + pprint("Loaded annotations from {} subset.".format(self.subset)) + pprint("Number of ground truth instances: {}".format(len(self.ground_truth))) + pprint("Number of predictions: {}".format(len(self.proposal))) + pprint("Fixed threshold for tiou score: {}".format(self.tiou_thresholds)) + pprint("AUC: {:>4.2f} (%)".format(self.auc * 100)) + for k in self.topk: + pprint("AR@{:3d} is {:>4.2f}%".format(k, np.mean(self.recall[:, k - 1]) * 100)) + + +def average_recall_vs_avg_nr_proposals( + ground_truth, + proposals, + max_avg_nr_proposals=None, + tiou_thresholds=np.linspace(0.5, 0.95, 10), +): + """Computes the average recall given an average number + of proposals per video. + Parameters + ---------- + ground_truth : df + Data frame containing the ground truth instances. + Required fields: ['video-id', 't-start', 't-end'] + proposal : df + Data frame containing the proposal instances. + Required fields: ['video-id, 't-start', 't-end', 'score'] + tiou_thresholds : 1darray, optional + array with tiou thresholds. + Outputs + ------- + recall : 2darray + recall[i,j] is recall at ith tiou threshold at the jth average number of average number of proposals per video. + average_recall : 1darray + recall averaged over a list of tiou threshold. This is equivalent to recall.mean(axis=0). + proposals_per_video : 1darray + average number of proposals per video. + """ + + # Get list of videos. + video_lst = ground_truth["video-id"].unique() + + if not max_avg_nr_proposals: + max_avg_nr_proposals = float(proposals.shape[0]) / video_lst.shape[0] + + ratio = max_avg_nr_proposals * float(video_lst.shape[0]) / proposals.shape[0] + + # Adaptation to query faster + ground_truth_gbvn = ground_truth.groupby("video-id") + proposals_gbvn = proposals.groupby("video-id") + + # For each video, computes tiou scores among the retrieved proposals. + score_lst = [] + total_nr_proposals = 0 + for videoid in video_lst: + # Get ground-truth instances associated to this video. + ground_truth_videoid = ground_truth_gbvn.get_group(videoid) + this_video_ground_truth = ground_truth_videoid.loc[:, ["t-start", "t-end"]].values + + # Get proposals for this video. + try: + proposals_videoid = proposals_gbvn.get_group(videoid) + this_video_proposals = proposals_videoid.loc[:, ["t-start", "t-end"]].values + + # Sort proposals by score. + sort_idx = proposals_videoid["score"].argsort()[::-1] + this_video_proposals = this_video_proposals[sort_idx, :] + except: + n = this_video_ground_truth.shape[0] + score_lst.append(np.zeros((n, 1))) + continue + + if this_video_proposals.shape[0] == 0: + n = this_video_ground_truth.shape[0] + score_lst.append(np.zeros((n, 1))) + continue + + if this_video_proposals.ndim != 2: + this_video_proposals = np.expand_dims(this_video_proposals, axis=0) + if this_video_ground_truth.ndim != 2: + this_video_ground_truth = np.expand_dims(this_video_ground_truth, axis=0) + + nr_proposals = np.minimum(int(this_video_proposals.shape[0] * ratio), this_video_proposals.shape[0]) + total_nr_proposals += nr_proposals + this_video_proposals = this_video_proposals[:nr_proposals, :] + + # Compute tiou scores. + tiou = wrapper_segment_iou(this_video_proposals, this_video_ground_truth) + score_lst.append(tiou) + + # Given that the length of the videos is really varied, we + # compute the number of proposals in terms of a ratio of the total + # proposals retrieved, i.e. average recall at a percentage of proposals + # retrieved per video. + + # Computes average recall. + # pcn_lst = np.arange(1, 101) / 100.0 * (max_avg_nr_proposals * float(video_lst.shape[0]) / total_nr_proposals) + pcn_lst = ( + np.arange(1, max_avg_nr_proposals + 1) + / max_avg_nr_proposals + * (max_avg_nr_proposals * float(video_lst.shape[0]) / total_nr_proposals) + ) + matches = np.empty((video_lst.shape[0], pcn_lst.shape[0])) + positives = np.empty(video_lst.shape[0]) + recall = np.empty((len(tiou_thresholds), pcn_lst.shape[0])) + # Iterates over each tiou threshold. + for ridx, tiou in enumerate(tiou_thresholds): + # Inspect positives retrieved per video at different + # number of proposals (percentage of the total retrieved). + for i, score in enumerate(score_lst): + # Total positives per video. + positives[i] = score.shape[0] + # Find proposals that satisfies minimum tiou threshold. + true_positives_tiou = score >= tiou + # Get number of proposals as a percentage of total retrieved. + pcn_proposals = np.minimum((score.shape[1] * pcn_lst).astype(np.int), score.shape[1]) + + for j, nr_proposals in enumerate(pcn_proposals): + # Compute the number of matches for each percentage of the proposals + matches[i, j] = np.count_nonzero((true_positives_tiou[:, :nr_proposals]).sum(axis=1)) + + # Computes recall given the set of matches per video. + recall[ridx, :] = matches.sum(axis=0) / positives.sum() + + # Recall is averaged. + avg_recall = recall.mean(axis=0) + + # Get the average number of proposals per video. + proposals_per_video = pcn_lst * (float(total_nr_proposals) / video_lst.shape[0]) + + return recall, avg_recall, proposals_per_video + + +def wrapper_segment_iou(target_segments, candidate_segments): + """Compute intersection over union btw segments + Parameters + ---------- + target_segments : ndarray + 2-dim array in format [m x 2:=[init, end]] + candidate_segments : ndarray + 2-dim array in format [n x 2:=[init, end]] + Outputs + ------- + tiou : ndarray + 2-dim array [n x m] with IOU ratio. + Note: It assumes that candidate-segments are more scarce that target-segments + """ + if candidate_segments.ndim != 2 or target_segments.ndim != 2: + raise ValueError("Dimension of arguments is incorrect") + + n, m = candidate_segments.shape[0], target_segments.shape[0] + tiou = np.empty((n, m)) + for i in range(m): + tiou[:, i] = segment_iou(target_segments[i, :], candidate_segments) + + return tiou diff --git a/OpenTAD/opentad/models/__init__.py b/OpenTAD/opentad/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b06dcd3f27f4a2ab98f6fb4a8bf1b3ae6f003f --- /dev/null +++ b/OpenTAD/opentad/models/__init__.py @@ -0,0 +1,11 @@ +from .builder import build_detector +from .detectors import * +from .backbones import * +from .projections import * +from .necks import * +from .dense_heads import * +from .roi_heads import * +from .losses import * +from .transformer import * + +__all__ = ["build_detector"] diff --git a/OpenTAD/opentad/models/backbones/__init__.py b/OpenTAD/opentad/models/backbones/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2eb8671d800215dee27d8b520861ca03f73189a --- /dev/null +++ b/OpenTAD/opentad/models/backbones/__init__.py @@ -0,0 +1,11 @@ +from .backbone_wrapper import BackboneWrapper +from .r2plus1d_tsp import ResNet2Plus1d_TSP +from .re2tal_swin import SwinTransformer3D_inv +from .re2tal_slowfast import ResNet3dSlowFast_inv + +__all__ = [ + "BackboneWrapper", + "ResNet2Plus1d_TSP", + "SwinTransformer3D_inv", + "ResNet3dSlowFast_inv", +] diff --git a/OpenTAD/opentad/models/backbones/backbone_wrapper.py b/OpenTAD/opentad/models/backbones/backbone_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..5b563043772c7da621bdc4d751bc4e72d9f651f7 --- /dev/null +++ b/OpenTAD/opentad/models/backbones/backbone_wrapper.py @@ -0,0 +1,118 @@ +import copy +import torch +import torch.nn as nn +from torch.nn.modules.batchnorm import _BatchNorm + +from mmengine.dataset import Compose +from mmengine.registry import MODELS as MM_BACKBONES +from mmengine.runner import load_checkpoint + +BACKBONES = MM_BACKBONES + + +class BackboneWrapper(nn.Module): + def __init__(self, cfg): + super(BackboneWrapper, self).__init__() + custom_cfg = cfg.custom + model_cfg = copy.deepcopy(cfg) + model_cfg.pop("custom") + + # build the backbone + self.model = BACKBONES.build(model_cfg) + + # custom settings: pretrained checkpoint, post_processing_pipeline, norm_eval, freeze_backbone + # 1. load the pretrained model + if hasattr(custom_cfg, "pretrain") and custom_cfg.pretrain is not None: + load_checkpoint(self.model, custom_cfg.pretrain, map_location="cpu") + else: + print( + "Warning: no pretrain path is provided, the backbone will be randomly initialized,\ + unless you have initialized the weights in the model.py." + ) + + # 2. pre_processing_pipeline + if hasattr(custom_cfg, "pre_processing_pipeline"): + self.pre_processing_pipeline = Compose(custom_cfg.pre_processing_pipeline) + else: + self.pre_processing_pipeline = None + + # 3. post_processing_pipeline for pooling and other operations + if hasattr(custom_cfg, "post_processing_pipeline"): + self.post_processing_pipeline = Compose(custom_cfg.post_processing_pipeline) + else: + self.post_processing_pipeline = None + + # 4. norm_eval: set all norm layers to eval mode + self.norm_eval = getattr(custom_cfg, "norm_eval", True) + + # 5. freeze_backbone: whether to freeze the backbone, default is False + self.freeze_backbone = getattr(custom_cfg, "freeze_backbone", False) + + print("freeze_backbone: {}, norm_eval: {}".format(self.freeze_backbone, self.norm_eval)) + + def forward(self, frames, masks=None): + # two types: snippet or frame + + # snippet: 3D backbone, [bs, T, 3, clip_len, H, W] + # frame: 3D backbone, [bs, 1, 3, T, H, W] + + # set all normalization layers + self.set_norm_layer() + + # data preprocessing: normalize mean and std + frames, _ = self.model.data_preprocessor.preprocess( + self.tensor_to_list(frames), # need list input + data_samples=None, + training=False, # for blending, which is not used in openTAD + ) + + # pre_processing_pipeline: + if self.pre_processing_pipeline is not None: + frames = self.pre_processing_pipeline(dict(frames=frames))["frames"] + + # flatten the batch dimension and num_segs dimension + batches, num_segs = frames.shape[0:2] + frames = frames.flatten(0, 1) # [bs*num_seg, ...] + + # go through the video backbone + if self.freeze_backbone: # freeze everything even in training + with torch.no_grad(): + features = self.model.backbone(frames) + + else: # let the model.train() or model.eval() decide whether to freeze + features = self.model.backbone(frames) + + # unflatten and pool the features + if isinstance(features, (tuple, list)): + features = torch.cat([self.unflatten_and_pool_features(f, batches, num_segs) for f in features], dim=1) + else: + features = self.unflatten_and_pool_features(features, batches, num_segs) + + # apply mask + if masks is not None and features.dim() == 3: + features = features * masks.unsqueeze(1).detach().float() + + # make sure detector has the float32 input + features = features.to(torch.float32) + return features + + def tensor_to_list(self, tensor): + return [t for t in tensor] + + def unflatten_and_pool_features(self, features, batches, num_segs): + # unflatten the batch dimension and num_segs dimension + features = features.unflatten(dim=0, sizes=(batches, num_segs)) # [bs, num_seg, ...] + + # convert the feature to [B,C,T]: pooling and other operations + if self.post_processing_pipeline is not None: + features = self.post_processing_pipeline(dict(feats=features))["feats"] + return features + + def set_norm_layer(self): + if self.norm_eval: + for m in self.modules(): + if isinstance(m, (nn.LayerNorm, nn.GroupNorm, _BatchNorm)): + m.eval() + + for param in m.parameters(): + param.requires_grad = False diff --git a/OpenTAD/opentad/models/backbones/r2plus1d_tsp.py b/OpenTAD/opentad/models/backbones/r2plus1d_tsp.py new file mode 100644 index 0000000000000000000000000000000000000000..182b2df8a95ddb06187e4d921ac6a208c6754a7b --- /dev/null +++ b/OpenTAD/opentad/models/backbones/r2plus1d_tsp.py @@ -0,0 +1,148 @@ +import torch +import torch.nn as nn +from torch.nn.modules.batchnorm import _BatchNorm +from torchvision.models.video.resnet import VideoResNet, R2Plus1dStem, BasicBlock +from torch.utils import checkpoint as cp +from mmengine.registry import MODELS + + +@MODELS.register_module() +class ResNet2Plus1d_TSP(VideoResNet): + """ResNet (2+1)d backbone. + This model is proposed in `A Closer Look at Spatiotemporal Convolutions for + Action Recognition `_ + """ + + def __init__( + self, + layers=[3, 4, 6, 3], + pretrained=None, + norm_eval=True, + with_cp=False, + frozen_stages=-1, # depth 34 + ): + super().__init__( + block=BasicBlockCP if with_cp else BasicBlock, + conv_makers=[Conv2Plus1D] * 4, + layers=layers, + stem=R2Plus1dStem, + ) + + # We need exact Caffe2 momentum for BatchNorm scaling + for m in self.modules(): + if isinstance(m, torch.nn.BatchNorm3d): + m.eps = 1e-3 + m.momentum = 0.9 + + self.fc = nn.Sequential() + + if pretrained != None: + checkpoint = torch.load(pretrained, map_location="cpu") + backbone_dict = {k[9:]: v for k, v in checkpoint["model"].items() if "fc" not in k} + self.load_state_dict(backbone_dict) + print("load pretrained model from {}".format(pretrained)) + + self.frozen_stages = frozen_stages + self.norm_eval = norm_eval + + def _freeze_stages(self): + """Prevent all the parameters from being optimized before + ``self.frozen_stages``.""" + if self.frozen_stages >= 0: + self.stem.eval() + for m in self.stem.modules(): + for param in m.parameters(): + param.requires_grad = False + + for i in range(1, self.frozen_stages + 1): + m = getattr(self, f"layer{i}") + m.eval() + for param in m.parameters(): + param.requires_grad = False + + def _norm_eval(self): + if self.norm_eval: + for m in self.modules(): + if isinstance(m, _BatchNorm): + m.eval() + + def forward(self, x): + self._freeze_stages() + self._norm_eval() + + x = self.stem(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + return x + + +class Conv2Plus1D(nn.Sequential): + def __init__(self, in_planes, out_planes, midplanes, stride=1, padding=1): + midplanes = (in_planes * out_planes * 3 * 3 * 3) // (in_planes * 3 * 3 + 3 * out_planes) + super(Conv2Plus1D, self).__init__( + nn.Conv3d( + in_planes, + midplanes, + kernel_size=(1, 3, 3), + stride=(1, stride, stride), + padding=(0, padding, padding), + bias=False, + ), + nn.BatchNorm3d(midplanes), + nn.ReLU(inplace=True), + nn.Conv3d( + midplanes, + out_planes, + kernel_size=(3, 1, 1), + stride=(stride, 1, 1), + padding=(padding, 0, 0), + bias=False, + ), + ) + + @staticmethod + def get_downsample_stride(stride): + return (stride, stride, stride) + + +class BasicBlockCP(nn.Module): + expansion = 1 + + def __init__(self, inplanes, planes, conv_builder, stride=1, downsample=None): + midplanes = (inplanes * planes * 3 * 3 * 3) // (inplanes * 3 * 3 + 3 * planes) + + super(BasicBlockCP, self).__init__() + self.conv1 = nn.Sequential( + conv_builder(inplanes, planes, midplanes, stride), + nn.BatchNorm3d(planes), + nn.ReLU(inplace=True), + ) + self.conv2 = nn.Sequential(conv_builder(planes, planes, midplanes), nn.BatchNorm3d(planes)) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + def _inner_forward(x): + """Forward wrapper for utilizing checkpoint.""" + residual = x + + out = self.conv1(x) + out = self.conv2(out) + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + + return out + + if x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + + out = self.relu(out) + return out diff --git a/OpenTAD/opentad/models/backbones/re2tal_slowfast.py b/OpenTAD/opentad/models/backbones/re2tal_slowfast.py new file mode 100644 index 0000000000000000000000000000000000000000..947a623aba7595847cdf3bdf6658dba15ef60573 --- /dev/null +++ b/OpenTAD/opentad/models/backbones/re2tal_slowfast.py @@ -0,0 +1,1422 @@ +from typing import OrderedDict +import torch +import torch.nn as nn +import torch.utils.checkpoint as cp +from torch.cuda.amp import custom_fwd, custom_bwd +from torch.nn.modules.utils import _ntuple, _triple +from mmcv.cnn import ConvModule, NonLocal3d, build_activation_layer +from mmengine.model.weight_init import kaiming_init +from mmengine.runner.checkpoint import _load_checkpoint, load_checkpoint, load_state_dict +from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm +from mmaction.registry import MODELS + + +class BasicBlock3d(nn.Module): + """BasicBlock 3d block for ResNet3D. + + Args: + inplanes (int): Number of channels for the input in first conv3d layer. + planes (int): Number of channels produced by some norm/conv3d layers. + spatial_stride (int): Spatial stride in the conv3d layer. Default: 1. + temporal_stride (int): Temporal stride in the conv3d layer. Default: 1. + dilation (int): Spacing between kernel elements. Default: 1. + downsample (nn.Module | None): Downsample layer. Default: None. + style (str): ``pytorch`` or ``caffe``. If set to "pytorch", the + stride-two layer is the 3x3 conv layer, otherwise the stride-two + layer is the first 1x1 conv layer. Default: 'pytorch'. + inflate (bool): Whether to inflate kernel. Default: True. + non_local (bool): Determine whether to apply non-local module in this + block. Default: False. + non_local_cfg (dict): Config for non-local module. Default: ``dict()``. + conv_cfg (dict): Config dict for convolution layer. + Default: ``dict(type='Conv3d')``. + norm_cfg (dict): Config for norm layers. required keys are ``type``, + Default: ``dict(type='BN3d')``. + act_cfg (dict): Config dict for activation layer. + Default: ``dict(type='ReLU')``. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + """ + + expansion = 1 + + def __init__( + self, + inplanes, + planes, + spatial_stride=1, + temporal_stride=1, + dilation=1, + downsample=None, + style="pytorch", + inflate=True, + non_local=False, + non_local_cfg=dict(), + conv_cfg=dict(type="Conv3d"), + norm_cfg=dict(type="BN3d"), + act_cfg=dict(type="ReLU"), + with_cp=False, + **kwargs, + ): + super().__init__() + assert style in ["pytorch", "caffe"] + # make sure that only ``inflate_style`` is passed into kwargs + assert set(kwargs).issubset(["inflate_style"]) + + self.inplanes = inplanes + self.planes = planes + self.spatial_stride = spatial_stride + self.temporal_stride = temporal_stride + self.dilation = dilation + self.style = style + self.inflate = inflate + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.with_cp = with_cp + self.non_local = non_local + self.non_local_cfg = non_local_cfg + + self.conv1_stride_s = spatial_stride + self.conv2_stride_s = 1 + self.conv1_stride_t = temporal_stride + self.conv2_stride_t = 1 + + if self.inflate: + conv1_kernel_size = (3, 3, 3) + conv1_padding = (1, dilation, dilation) + conv2_kernel_size = (3, 3, 3) + conv2_padding = (1, 1, 1) + else: + conv1_kernel_size = (1, 3, 3) + conv1_padding = (0, dilation, dilation) + conv2_kernel_size = (1, 3, 3) + conv2_padding = (0, 1, 1) + + self.conv1 = ConvModule( + inplanes, + planes, + conv1_kernel_size, + stride=(self.conv1_stride_t, self.conv1_stride_s, self.conv1_stride_s), + padding=conv1_padding, + dilation=(1, dilation, dilation), + bias=False, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + ) + + self.conv2 = ConvModule( + planes, + planes * self.expansion, + conv2_kernel_size, + stride=(self.conv2_stride_t, self.conv2_stride_s, self.conv2_stride_s), + padding=conv2_padding, + bias=False, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=None, + ) + + self.downsample = downsample + self.relu = build_activation_layer(self.act_cfg) + + if self.non_local: + self.non_local_block = NonLocal3d(self.conv2.norm.num_features, **self.non_local_cfg) + + def forward(self, x): + """Defines the computation performed at every call.""" + + def _inner_forward(x): + """Forward wrapper for utilizing checkpoint.""" + identity = x + + out = self.conv1(x) + out = self.conv2(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out = out + identity + return out + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + out = self.relu(out) + + if self.non_local: + out = self.non_local_block(out) + + return out + + +class Bottleneck3d_inv_F(nn.Module): + """Invertible Bottleneck 3d block F for ResNet3D. + + Args: + inplanes (int): Number of channels for the input in first conv3d layer. + planes (int): Number of channels produced by some norm/conv3d layers. + spatial_stride (int): Spatial stride in the conv3d layer. Default: 1. + temporal_stride (int): Temporal stride in the conv3d layer. Default: 1. + dilation (int): Spacing between kernel elements. Default: 1. + downsample (nn.Module | None): Downsample layer. Default: None. + style (str): ``pytorch`` or ``caffe``. If set to "pytorch", the + stride-two layer is the 3x3 conv layer, otherwise the stride-two + layer is the first 1x1 conv layer. Default: 'pytorch'. + inflate (bool): Whether to inflate kernel. Default: True. + inflate_style (str): ``3x1x1`` or ``3x3x3``. which determines the + kernel sizes and padding strides for conv1 and conv2 in each block. + Default: '3x1x1'. + non_local (bool): Determine whether to apply non-local module in this + block. Default: False. + non_local_cfg (dict): Config for non-local module. Default: ``dict()``. + conv_cfg (dict): Config dict for convolution layer. + Default: ``dict(type='Conv3d')``. + norm_cfg (dict): Config for norm layers. required keys are ``type``, + Default: ``dict(type='BN3d')``. + act_cfg (dict): Config dict for activation layer. + Default: ``dict(type='ReLU')``. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + """ + + expansion = 4 + + def __init__( + self, + inplanes, + planes, + spatial_stride=1, + temporal_stride=1, + dilation=1, + style="pytorch", + inflate=True, + inflate_style="3x1x1", + non_local=False, + non_local_cfg=dict(), + conv_cfg=dict(type="Conv3d"), + norm_cfg=dict(type="BN3d"), + act_cfg=dict(type="ReLU"), + with_cp=False, + ): + super().__init__() + assert style in ["pytorch", "caffe"] + assert inflate_style in ["3x1x1", "3x3x3"] + + self.inplanes = inplanes + self.planes = planes + self.spatial_stride = spatial_stride + self.temporal_stride = temporal_stride + self.dilation = dilation + self.style = style + self.inflate = inflate + self.inflate_style = inflate_style + self.norm_cfg = norm_cfg + self.conv_cfg = conv_cfg + self.act_cfg = act_cfg + self.with_cp = with_cp + self.non_local = non_local + self.non_local_cfg = non_local_cfg + + if self.style == "pytorch": + self.conv1_stride_s = 1 + self.conv2_stride_s = spatial_stride + self.conv1_stride_t = 1 + self.conv2_stride_t = temporal_stride + else: + self.conv1_stride_s = spatial_stride + self.conv2_stride_s = 1 + self.conv1_stride_t = temporal_stride + self.conv2_stride_t = 1 + + if self.inflate: + if inflate_style == "3x1x1": + conv1_kernel_size = (3, 1, 1) + conv1_padding = (1, 0, 0) + conv2_kernel_size = (1, 3, 3) + conv2_padding = (0, dilation, dilation) + else: + conv1_kernel_size = (1, 1, 1) + conv1_padding = (0, 0, 0) + conv2_kernel_size = (3, 3, 3) + conv2_padding = (1, dilation, dilation) + else: + conv1_kernel_size = (1, 1, 1) + conv1_padding = (0, 0, 0) + conv2_kernel_size = (1, 3, 3) + conv2_padding = (0, dilation, dilation) + + self.conv1 = ConvModule( + inplanes, + planes, + conv1_kernel_size, + stride=(self.conv1_stride_t, self.conv1_stride_s, self.conv1_stride_s), + padding=conv1_padding, + bias=False, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + ) + + self.conv2 = ConvModule( + planes, + planes, + conv2_kernel_size, + stride=(self.conv2_stride_t, self.conv2_stride_s, self.conv2_stride_s), + padding=conv2_padding, + dilation=(1, dilation, dilation), + bias=False, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + ) + + self.conv3 = ConvModule( + planes, + planes * self.expansion, + 1, + bias=False, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + # No activation in the third ConvModule for bottleneck + act_cfg=None, + ) + + self.relu = build_activation_layer(self.act_cfg) + + def forward(self, x): + """Defines the computation performed at every call.""" + + out = self.conv1(x) + out = self.conv2(out) + out = self.conv3(out) + + out = self.relu(out) + + return out + + +class Bottleneck3d_inv(nn.Module): + expansion = 4 + + def __init__( + self, + inplanes, + planes, + spatial_stride=1, + temporal_stride=1, + dilation=1, + downsample=None, + style="pytorch", + inflate=True, + inflate_style="3x1x1", + non_local=False, + non_local_cfg=dict(), + conv_cfg=dict(type="Conv3d"), + norm_cfg=dict(type="BN3d"), + act_cfg=dict(type="ReLU"), + with_cp=False, + ): + super().__init__() + + Fm = Bottleneck3d_inv_F( + inplanes, + planes, + spatial_stride=spatial_stride, + temporal_stride=temporal_stride, + dilation=dilation, + style=style, + inflate=inflate, + inflate_style=inflate_style, + non_local=non_local, + non_local_cfg=non_local_cfg, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + with_cp=with_cp, + ) + self.downsample = downsample + + if self.downsample is None: + self.inv_block = InvFuncWrapper(Fm, split_dim=1) + else: + self.Fm = Fm + + def forward(self, x): + if self.downsample is None: + out = self.inv_block(x) + else: + out = self.Fm(x) + identity = self.downsample(x) + out = out + identity + + out = torch.cat((out, out), dim=1) + + return out + + def backward_pass(self, y1, y2, dy1, dy2): + return self.inv_block.backward_pass(y1=y1, y2=y2, dy1=dy1, dy2=dy2) + + +class InvFuncWrapper(nn.Module): + def __init__(self, Fm, split_dim=-1): + super(InvFuncWrapper, self).__init__() + """ This uses NICE's invertible functions. + """ + self.Fm = Fm + self.split_dim = split_dim + + def forward(self, x): + """ + Forward: + y1 = x1 + y2 = x2 + Fm(x1) + """ + x1, x2 = torch.chunk(x, 2, dim=self.split_dim) + x1, x2 = x1.contiguous(), x2.contiguous() + + y1 = x1 + y2 = x2 + self.Fm(x1) + + y = torch.cat([y2, y1], dim=self.split_dim) + return y + + def inverse(self, y): + """ + Inverse: + x1 = y1 + x2 = y2 - Fm(y1) + """ + y2, y1 = torch.chunk(y, 2, dim=self.split_dim) + y2, y1 = y2.contiguous(), y1.contiguous() + + x1 = y1 + x2 = y2 - self.Fm(y1) + + x = torch.cat([x1, x2], dim=self.split_dim) + + return x + + def backward_pass(self, y1, y2, dy1, dy2): + """This uses NICE's invertible functions. + Forward: + y1 = x1 + y2 = x2 + Fm(y1) + Inverse: + x1 = y1 + x2 = y2 - Fm(y1) + """ + + with torch.enable_grad(): + y1.requires_grad = True + Fy1 = self.Fm(y1) + Fy1.backward(dy2, retain_graph=True) + + with torch.no_grad(): + x2 = y2 - Fy1 + del Fy1 + dx1 = dy1 + y1.grad + y1.grad = None + + with torch.no_grad(): + x1 = y1 + dx2 = dy2 + x2 = x2.detach() + + return x1, x2, dx1, dx2 + + +class RevBackProp(torch.autograd.Function): + @staticmethod + @custom_fwd + def forward(ctx, x, blocks): + for blk in blocks: + x = blk(x) + + all_tensors = [x.detach()] + ctx.save_for_backward(*all_tensors) + ctx.blocks = blocks + + return x + + @staticmethod + @custom_bwd + def backward(ctx, dy): + # retrieve params from ctx for backward + y = ctx.saved_tensors[0] + blocks = ctx.blocks + + dy2, dy1 = torch.chunk(dy, 2, dim=1) + y2, y1 = torch.chunk(y, 2, dim=1) + + for i, blk in enumerate(blocks[::-1]): + if i > 0: + y2, y1 = y1, y2 + dy2, dy1 = dy1, dy2 + + y1, y2, dy1, dy2 = blk.backward_pass(y1=y1, y2=y2, dy1=dy1, dy2=dy2) + + dx = torch.cat([dy1, dy2], dim=1) + del y1, y2, dy1, dy2 + return dx, None + + +class BasicLayer(nn.Module): + """A basic layer in resnet. Each layer contains multiple blocks. + Multiple (usually 4) layers of different resolutions form a resnet pathway. + """ + + def __init__( + self, + lateral, + channel_ratio, + expansion, + block, + inplanes, + planes, + blocks, + spatial_stride=1, + temporal_stride=1, + dilation=1, + style="pytorch", + inflate=1, + inflate_style="3x1x1", + non_local=0, + non_local_cfg=dict(), + conv_cfg=None, + norm_cfg=None, + act_cfg=None, + with_cp=False, + inv_mode="vanilla", + ): + super().__init__() + + self.inv_mode = inv_mode + + inflate = inflate if not isinstance(inflate, int) else (inflate,) * blocks + non_local = non_local if not isinstance(non_local, int) else (non_local,) * blocks + assert len(inflate) == blocks and len(non_local) == blocks + if lateral: + lateral_inplanes = inplanes * 2 // channel_ratio + else: + lateral_inplanes = 0 + if spatial_stride != 1 or (inplanes + lateral_inplanes) != planes * expansion: + downsample = ConvModule( + inplanes + lateral_inplanes, + planes * expansion, + kernel_size=1, + stride=(temporal_stride, spatial_stride, spatial_stride), + bias=False, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None, + ) + else: + downsample = None + + self.blocks = nn.ModuleList() + self.blocks.append( + block( + inplanes + lateral_inplanes, + planes, + spatial_stride, + temporal_stride, + dilation, + downsample, + style=style, + inflate=(inflate[0] == 1), + inflate_style=inflate_style, + non_local=(non_local[0] == 1), + non_local_cfg=non_local_cfg, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + with_cp=with_cp, + ) + ) + inplanes = planes * block.expansion + + for i in range(1, blocks): + self.blocks.append( + block( + inplanes, + planes, + 1, + 1, + dilation, + style=style, + inflate=(inflate[i] == 1), + inflate_style=inflate_style, + non_local=(non_local[i] == 1), + non_local_cfg=non_local_cfg, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + with_cp=with_cp, + ) + ) + + def forward(self, x): + x = self.blocks[0](x) + + if self.inv_mode == "vanilla": + for blk in self.blocks[1:]: + x = blk(x) + elif self.inv_mode == "custom_backprop": + x = RevBackProp.apply(x, self.blocks[1:]) + + _, C, _, _, _ = x.shape + C = int(C / 2) + x = (x[:, :C, :, :, :] + x[:, C:, :, :, :]) / 2 + + return x + + +class ResNet3d_inv(nn.Module): + """ResNet 3d backbone. + + Args: + depth (int): Depth of resnet, from {18, 34, 50, 101, 152}. + pretrained (str | None): Name of pretrained model. + stage_blocks (tuple | None): Set number of stages for each res layer. + Default: None. + pretrained2d (bool): Whether to load pretrained 2D model. + Default: True. + in_channels (int): Channel num of input features. Default: 3. + base_channels (int): Channel num of stem output features. Default: 64. + out_indices (Sequence[int]): Indices of output feature. Default: (3, ). + num_stages (int): Resnet stages. Default: 4. + spatial_strides (Sequence[int]): + Spatial strides of residual blocks of each stage. + Default: ``(1, 2, 2, 2)``. + temporal_strides (Sequence[int]): + Temporal strides of residual blocks of each stage. + Default: ``(1, 1, 1, 1)``. + dilations (Sequence[int]): Dilation of each stage. + Default: ``(1, 1, 1, 1)``. + conv1_kernel (Sequence[int]): Kernel size of the first conv layer. + Default: ``(3, 7, 7)``. + conv1_stride_s (int): Spatial stride of the first conv layer. + Default: 2. + conv1_stride_t (int): Temporal stride of the first conv layer. + Default: 1. + pool1_stride_s (int): Spatial stride of the first pooling layer. + Default: 2. + pool1_stride_t (int): Temporal stride of the first pooling layer. + Default: 1. + with_pool2 (bool): Whether to use pool2. Default: True. + style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two + layer is the 3x3 conv layer, otherwise the stride-two layer is + the first 1x1 conv layer. Default: 'pytorch'. + frozen_stages (int): Stages to be frozen (all param fixed). -1 means + not freezing any parameters. Default: -1. + inflate (Sequence[int]): Inflate Dims of each block. + Default: (1, 1, 1, 1). + inflate_style (str): ``3x1x1`` or ``3x3x3``. which determines the + kernel sizes and padding strides for conv1 and conv2 in each block. + Default: '3x1x1'. + conv_cfg (dict): Config for conv layers. required keys are ``type`` + Default: ``dict(type='Conv3d')``. + norm_cfg (dict): Config for norm layers. required keys are ``type`` and + ``requires_grad``. + Default: ``dict(type='BN3d', requires_grad=True)``. + act_cfg (dict): Config dict for activation layer. + Default: ``dict(type='ReLU', inplace=True)``. + norm_eval (bool): Whether to set BN layers to eval mode, namely, freeze + running stats (mean and var). Default: False. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + non_local (Sequence[int]): Determine whether to apply non-local module + in the corresponding block of each stages. Default: (0, 0, 0, 0). + non_local_cfg (dict): Config for non-local module. Default: ``dict()``. + zero_init_residual (bool): + Whether to use zero initialization for residual block, + Default: True. + kwargs (dict, optional): Key arguments for "make_res_layer". + """ + + arch_settings = { + 18: (BasicBlock3d, (2, 2, 2, 2)), + 34: (BasicBlock3d, (3, 4, 6, 3)), + 50: (Bottleneck3d_inv, (3, 4, 6, 3)), + 101: (Bottleneck3d_inv, (3, 4, 23, 3)), + 152: (Bottleneck3d_inv, (3, 8, 36, 3)), + } + + def __init__( + self, + depth, + pretrained, + stage_blocks=None, + pretrained2d=True, + in_channels=3, + num_stages=4, + base_channels=64, + out_indices=(3,), + spatial_strides=(1, 2, 2, 2), + temporal_strides=(1, 1, 1, 1), + dilations=(1, 1, 1, 1), + conv1_kernel=(3, 7, 7), + conv1_stride_s=2, + conv1_stride_t=1, + pool1_stride_s=2, + pool1_stride_t=1, + with_pool2=True, + style="pytorch", + frozen_stages=-1, + inflate=(1, 1, 1, 1), + inflate_style="3x1x1", + conv_cfg=dict(type="Conv3d"), + norm_cfg=dict(type="BN3d", requires_grad=True), + act_cfg=dict(type="ReLU", inplace=True), + norm_eval=False, + with_cp=False, + inv_mode=["custom_backprop", "custom_backprop", "custom_backprop", "custom_backprop"], + non_local=(0, 0, 0, 0), + non_local_cfg=dict(), + zero_init_residual=True, + **kwargs, + ): + super().__init__() + if depth not in self.arch_settings: + raise KeyError(f"invalid depth {depth} for resnet") + self.depth = depth + self.pretrained = pretrained + self.pretrained2d = pretrained2d + self.in_channels = in_channels + self.base_channels = base_channels + self.num_stages = num_stages + assert 1 <= num_stages <= 4 + self.stage_blocks = stage_blocks + self.out_indices = out_indices + assert max(out_indices) < num_stages + self.spatial_strides = spatial_strides + self.temporal_strides = temporal_strides + self.dilations = dilations + assert len(spatial_strides) == len(temporal_strides) == len(dilations) == num_stages + if self.stage_blocks is not None: + assert len(self.stage_blocks) == num_stages + + self.conv1_kernel = conv1_kernel + self.conv1_stride_s = conv1_stride_s + self.conv1_stride_t = conv1_stride_t + self.pool1_stride_s = pool1_stride_s + self.pool1_stride_t = pool1_stride_t + self.with_pool2 = with_pool2 + self.style = style + self.frozen_stages = frozen_stages + self.stage_inflations = _ntuple(num_stages)(inflate) + self.non_local_stages = _ntuple(num_stages)(non_local) + self.inflate_style = inflate_style + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.norm_eval = norm_eval + self.with_cp = with_cp + self.zero_init_residual = zero_init_residual + + self.block, stage_blocks = self.arch_settings[depth] + + if self.stage_blocks is None: + self.stage_blocks = stage_blocks[:num_stages] + + self.inplanes = self.base_channels + + self.non_local_cfg = non_local_cfg + + self._make_stem_layer() + + self.res_layers = [] + for i, num_blocks in enumerate(self.stage_blocks): + spatial_stride = spatial_strides[i] + temporal_stride = temporal_strides[i] + dilation = dilations[i] + planes = self.base_channels * 2**i + res_layer = BasicLayer( + self.lateral, + self.channel_ratio, + self.block.expansion, + self.block, + self.inplanes, + planes, + num_blocks, + spatial_stride=spatial_stride, + temporal_stride=temporal_stride, + dilation=dilation, + style=self.style, + norm_cfg=self.norm_cfg, + conv_cfg=self.conv_cfg, + act_cfg=self.act_cfg, + non_local=self.non_local_stages[i], + non_local_cfg=self.non_local_cfg, + inflate=self.stage_inflations[i], + inflate_style=self.inflate_style, + with_cp=with_cp, + inv_mode=inv_mode[i], + **kwargs, + ) + self.inplanes = planes * self.block.expansion + layer_name = f"layer{i + 1}" + self.add_module(layer_name, res_layer) + self.res_layers.append(layer_name) + + self.feat_dim = self.block.expansion * self.base_channels * 2 ** (len(self.stage_blocks) - 1) + + @staticmethod + def _inflate_conv_params(conv3d, state_dict_2d, module_name_2d, inflated_param_names): + """Inflate a conv module from 2d to 3d. + + Args: + conv3d (nn.Module): The destination conv3d module. + state_dict_2d (OrderedDict): The state dict of pretrained 2d model. + module_name_2d (str): The name of corresponding conv module in the + 2d model. + inflated_param_names (list[str]): List of parameters that have been + inflated. + """ + weight_2d_name = module_name_2d + ".weight" + + conv2d_weight = state_dict_2d[weight_2d_name] + kernel_t = conv3d.weight.data.shape[2] + + new_weight = conv2d_weight.data.unsqueeze(2).expand_as(conv3d.weight) / kernel_t + conv3d.weight.data.copy_(new_weight) + inflated_param_names.append(weight_2d_name) + + if getattr(conv3d, "bias") is not None: + bias_2d_name = module_name_2d + ".bias" + conv3d.bias.data.copy_(state_dict_2d[bias_2d_name]) + inflated_param_names.append(bias_2d_name) + + @staticmethod + def _inflate_bn_params(bn3d, state_dict_2d, module_name_2d, inflated_param_names): + """Inflate a norm module from 2d to 3d. + + Args: + bn3d (nn.Module): The destination bn3d module. + state_dict_2d (OrderedDict): The state dict of pretrained 2d model. + module_name_2d (str): The name of corresponding bn module in the + 2d model. + inflated_param_names (list[str]): List of parameters that have been + inflated. + """ + for param_name, param in bn3d.named_parameters(): + param_2d_name = f"{module_name_2d}.{param_name}" + param_2d = state_dict_2d[param_2d_name] + param.data.copy_(param_2d) + inflated_param_names.append(param_2d_name) + + for param_name, param in bn3d.named_buffers(): + param_2d_name = f"{module_name_2d}.{param_name}" + # some buffers like num_batches_tracked may not exist in old + # checkpoints + if param_2d_name in state_dict_2d: + param_2d = state_dict_2d[param_2d_name] + param.data.copy_(param_2d) + inflated_param_names.append(param_2d_name) + + @staticmethod + def _inflate_weights(self): + """Inflate the resnet2d parameters to resnet3d. + + The differences between resnet3d and resnet2d mainly lie in an extra + axis of conv kernel. To utilize the pretrained parameters in 2d model, + the weight of conv2d models should be inflated to fit in the shapes of + the 3d counterpart. + """ + + state_dict_r2d = _load_checkpoint(self.pretrained) + if "state_dict" in state_dict_r2d: + state_dict_r2d = state_dict_r2d["state_dict"] + + inflated_param_names = [] + for name, module in self.named_modules(): + if isinstance(module, ConvModule): + # we use a ConvModule to wrap conv+bn+relu layers, thus the + # name mapping is needed + if "downsample" in name: + # layer{X}.{Y}.downsample.conv->layer{X}.{Y}.downsample.0 + original_conv_name = name + ".0" + # layer{X}.{Y}.downsample.bn->layer{X}.{Y}.downsample.1 + original_bn_name = name + ".1" + else: + # layer{X}.{Y}.conv{n}.conv->layer{X}.{Y}.conv{n} + original_conv_name = name + # layer{X}.{Y}.conv{n}.bn->layer{X}.{Y}.bn{n} + original_bn_name = name.replace("conv", "bn") + if original_conv_name + ".weight" not in state_dict_r2d: + print(f"Module not exist in the state_dict_r2d" f": {original_conv_name}") + else: + shape_2d = state_dict_r2d[original_conv_name + ".weight"].shape + shape_3d = module.conv.weight.data.shape + if shape_2d != shape_3d[:2] + shape_3d[3:]: + print( + f"Weight shape mismatch for " + f": {original_conv_name} : " + f"3d weight shape: {shape_3d}; " + f"2d weight shape: {shape_2d}. " + ) + else: + self._inflate_conv_params(module.conv, state_dict_r2d, original_conv_name, inflated_param_names) + + if original_bn_name + ".weight" not in state_dict_r2d: + print(f"Module not exist in the state_dict_r2d" f": {original_bn_name}") + else: + self._inflate_bn_params(module.bn, state_dict_r2d, original_bn_name, inflated_param_names) + + # check if any parameters in the 2d checkpoint are not loaded + remaining_names = set(state_dict_r2d.keys()) - set(inflated_param_names) + if remaining_names: + print(f"These parameters in the 2d checkpoint are not loaded" f": {remaining_names}") + + def inflate_weights(self): + self._inflate_weights(self) + + def _make_stem_layer(self): + """Construct the stem layers consists of a conv+norm+act module and a + pooling layer.""" + self.conv1 = ConvModule( + self.in_channels, + self.base_channels, + kernel_size=self.conv1_kernel, + stride=(self.conv1_stride_t, self.conv1_stride_s, self.conv1_stride_s), + padding=tuple([(k - 1) // 2 for k in _triple(self.conv1_kernel)]), + bias=False, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + ) + + self.maxpool = nn.MaxPool3d( + kernel_size=(1, 3, 3), + stride=(self.pool1_stride_t, self.pool1_stride_s, self.pool1_stride_s), + padding=(0, 1, 1), + ) + + self.pool2 = nn.MaxPool3d(kernel_size=(2, 1, 1), stride=(2, 1, 1)) + + def _freeze_stages(self): + """Prevent all the parameters from being optimized before + ``self.frozen_stages``.""" + if self.frozen_stages >= 0: + self.conv1.eval() + for param in self.conv1.parameters(): + param.requires_grad = False + + for i in range(1, self.frozen_stages + 1): + m = getattr(self, f"layer{i}") + m.eval() + for param in m.parameters(): + param.requires_grad = False + + @staticmethod + def _init_weights(self, pretrained=None): + """Initiate the parameters either from existing checkpoint or from + scratch. + + Args: + pretrained (str | None): The path of the pretrained weight. Will + override the original `pretrained` if set. The arg is added to + be compatible with mmdet. Default: None. + """ + if pretrained: + self.pretrained = pretrained + if isinstance(self.pretrained, str): + if self.pretrained2d: + # Inflate 2D model into 3D model. + self.inflate_weights() + + else: + # Directly load 3D model. + load_checkpoint(self, self.pretrained, strict=False) + + def init_weights(self, pretrained=None): + self._init_weights(self, pretrained) + + def forward(self, x): + """Defines the computation performed at every call. + + Args: + x (torch.Tensor): The input data. + + Returns: + torch.Tensor: The feature of the input + samples extracted by the backbone. + """ + x = self.conv1(x) + x = self.maxpool(x) + outs = [] + for i, layer_name in enumerate(self.res_layers): + res_layer = getattr(self, layer_name) + x = res_layer(x) + if i == 0 and self.with_pool2: + x = self.pool2(x) + if i in self.out_indices: + outs.append(x) + if len(outs) == 1: + return outs[0] + + return tuple(outs) + + def train(self, mode=True): + """Set the optimization status when training.""" + super().train(mode) + self._freeze_stages() + if mode and self.norm_eval: + for m in self.modules(): + if isinstance(m, _BatchNorm): + m.eval() + + +class ResNet3dPathway(ResNet3d_inv): + """A pathway of Slowfast based on ResNet3d. + + Args: + *args (arguments): Arguments same as :class:``ResNet3d``. + lateral (bool): Determines whether to enable the lateral connection + from another pathway. Default: False. + speed_ratio (int): Speed ratio indicating the ratio between time + dimension of the fast and slow pathway, corresponding to the + ``alpha`` in the paper. Default: 8. + channel_ratio (int): Reduce the channel number of fast pathway + by ``channel_ratio``, corresponding to ``beta`` in the paper. + Default: 8. + fusion_kernel (int): The kernel size of lateral fusion. + Default: 5. + **kwargs (keyword arguments): Keywords arguments for ResNet3d. + """ + + def __init__( + self, + *args, + lateral=False, + speed_ratio=8, + channel_ratio=8, + fusion_kernel=5, + **kwargs, + ): + self.lateral = lateral + self.speed_ratio = speed_ratio + self.channel_ratio = channel_ratio + self.fusion_kernel = fusion_kernel + super().__init__(*args, **kwargs) + self.inplanes = self.base_channels + if self.lateral: + self.conv1_lateral = ConvModule( + self.inplanes // self.channel_ratio, + # https://arxiv.org/abs/1812.03982, the + # third type of lateral connection has out_channel: + # 2 * \beta * C + self.inplanes * 2 // self.channel_ratio, + kernel_size=(fusion_kernel, 1, 1), + stride=(self.speed_ratio, 1, 1), + padding=((fusion_kernel - 1) // 2, 0, 0), + bias=False, + conv_cfg=self.conv_cfg, + norm_cfg=None, + act_cfg=None, + ) + + self.lateral_connections = [] + for i in range(len(self.stage_blocks)): + planes = self.base_channels * 2**i + self.inplanes = planes * self.block.expansion + + if lateral and i != self.num_stages - 1: + # no lateral connection needed in final stage + lateral_name = f"layer{(i + 1)}_lateral" + setattr( + self, + lateral_name, + ConvModule( + self.inplanes // self.channel_ratio, + self.inplanes * 2 // self.channel_ratio, + kernel_size=(fusion_kernel, 1, 1), + stride=(self.speed_ratio, 1, 1), + padding=((fusion_kernel - 1) // 2, 0, 0), + bias=False, + conv_cfg=self.conv_cfg, + norm_cfg=None, + act_cfg=None, + ), + ) + self.lateral_connections.append(lateral_name) + + def inflate_weights(self): + """Inflate the resnet2d parameters to resnet3d pathway. + + The differences between resnet3d and resnet2d mainly lie in an extra + axis of conv kernel. To utilize the pretrained parameters in 2d model, + the weight of conv2d models should be inflated to fit in the shapes of + the 3d counterpart. For pathway the ``lateral_connection`` part should + not be inflated from 2d weights. + """ + + state_dict_r2d = _load_checkpoint(self.pretrained) + if "state_dict" in state_dict_r2d: + state_dict_r2d = state_dict_r2d["state_dict"] + + inflated_param_names = [] + for name, module in self.named_modules(): + if "lateral" in name: + continue + if isinstance(module, ConvModule): + # we use a ConvModule to wrap conv+bn+relu layers, thus the + # name mapping is needed + if "downsample" in name: + # layer{X}.{Y}.downsample.conv->layer{X}.{Y}.downsample.0 + original_conv_name = name + ".0" + # layer{X}.{Y}.downsample.bn->layer{X}.{Y}.downsample.1 + original_bn_name = name + ".1" + else: + # layer{X}.{Y}.conv{n}.conv->layer{X}.{Y}.conv{n} + original_conv_name = name + # layer{X}.{Y}.conv{n}.bn->layer{X}.{Y}.bn{n} + original_bn_name = name.replace("conv", "bn") + if original_conv_name + ".weight" not in state_dict_r2d: + print(f"Module not exist in the state_dict_r2d" f": {original_conv_name}") + else: + self._inflate_conv_params( + module.conv, + state_dict_r2d, + original_conv_name, + inflated_param_names, + ) + if original_bn_name + ".weight" not in state_dict_r2d: + print(f"Module not exist in the state_dict_r2d" f": {original_bn_name}") + else: + self._inflate_bn_params( + module.bn, + state_dict_r2d, + original_bn_name, + inflated_param_names, + ) + + # check if any parameters in the 2d checkpoint are not loaded + remaining_names = set(state_dict_r2d.keys()) - set(inflated_param_names) + if remaining_names: + print(f"These parameters in the 2d checkpoint are not loaded" f": {remaining_names}") + + def _inflate_conv_params(self, conv3d, state_dict_2d, module_name_2d, inflated_param_names): + """Inflate a conv module from 2d to 3d. + + The differences of conv modules betweene 2d and 3d in Pathway + mainly lie in the inplanes due to lateral connections. To fit the + shapes of the lateral connection counterpart, it will expand + parameters by concatting conv2d parameters and extra zero paddings. + + Args: + conv3d (nn.Module): The destination conv3d module. + state_dict_2d (OrderedDict): The state dict of pretrained 2d model. + module_name_2d (str): The name of corresponding conv module in the + 2d model. + inflated_param_names (list[str]): List of parameters that have been + inflated. + """ + weight_2d_name = module_name_2d + ".weight" + conv2d_weight = state_dict_2d[weight_2d_name] + old_shape = conv2d_weight.shape + new_shape = conv3d.weight.data.shape + kernel_t = new_shape[2] + if new_shape[1] != old_shape[1]: + # Inplanes may be different due to lateral connections + new_channels = new_shape[1] - old_shape[1] + pad_shape = old_shape + pad_shape = pad_shape[:1] + (new_channels,) + pad_shape[2:] + # Expand parameters by concat extra channels + conv2d_weight = torch.cat( + ( + conv2d_weight, + torch.zeros(pad_shape).type_as(conv2d_weight).to(conv2d_weight.device), + ), + dim=1, + ) + new_weight = conv2d_weight.data.unsqueeze(2).expand_as(conv3d.weight) / kernel_t + conv3d.weight.data.copy_(new_weight) + inflated_param_names.append(weight_2d_name) + + if getattr(conv3d, "bias") is not None: + bias_2d_name = module_name_2d + ".bias" + conv3d.bias.data.copy_(state_dict_2d[bias_2d_name]) + inflated_param_names.append(bias_2d_name) + + def _freeze_stages(self): + """Prevent all the parameters from being optimized before + `self.frozen_stages`.""" + if self.frozen_stages >= 0: + self.conv1.eval() + for param in self.conv1.parameters(): + param.requires_grad = False + + for i in range(1, self.frozen_stages + 1): + m = getattr(self, f"layer{i}") + m.eval() + for param in m.parameters(): + param.requires_grad = False + + if i != len(self.res_layers) and self.lateral: + # No fusion needed in the final stage + lateral_name = self.lateral_connections[i - 1] + conv_lateral = getattr(self, lateral_name) + conv_lateral.eval() + for param in conv_lateral.parameters(): + param.requires_grad = False + + def init_weights(self, pretrained=None): + """Initiate the parameters either from existing checkpoint or from + scratch.""" + if pretrained: + self.pretrained = pretrained + + # Override the init_weights of i3d + super().init_weights() + for module_name in self.lateral_connections: + layer = getattr(self, module_name) + for m in layer.modules(): + if isinstance(m, (nn.Conv3d, nn.Conv2d)): + kaiming_init(m) + + +pathway_cfg = { + "resnet3d": ResNet3dPathway, + # TODO: BNInceptionPathway +} + + +def build_pathway(cfg, *args, **kwargs): + """Build pathway. + + Args: + cfg (None or dict): cfg should contain: + - type (str): identify conv layer type. + + Returns: + nn.Module: Created pathway. + """ + if not (isinstance(cfg, dict) and "type" in cfg): + raise TypeError('cfg must be a dict containing the key "type"') + cfg_ = cfg.copy() + + pathway_type = cfg_.pop("type") + if pathway_type not in pathway_cfg: + raise KeyError(f"Unrecognized pathway type {pathway_type}") + + pathway_cls = pathway_cfg[pathway_type] + pathway = pathway_cls(*args, **kwargs, **cfg_) + + return pathway + + +@MODELS.register_module() +class ResNet3dSlowFast_inv(nn.Module): + """Slowfast backbone. + + This module is proposed in `SlowFast Networks for Video Recognition + `_ + + Args: + pretrained (str): The file path to a pretrained model. + resample_rate (int): A large temporal stride ``resample_rate`` + on input frames. The actual resample rate is calculated by + multipling the ``interval`` in ``SampleFrames`` in the + pipeline with ``resample_rate``, equivalent to the :math:`\\tau` + in the paper, i.e. it processes only one out of + ``resample_rate * interval`` frames. Default: 8. + speed_ratio (int): Speed ratio indicating the ratio between time + dimension of the fast and slow pathway, corresponding to the + :math:`\\alpha` in the paper. Default: 8. + channel_ratio (int): Reduce the channel number of fast pathway + by ``channel_ratio``, corresponding to :math:`\\beta` in the paper. + Default: 8. + slow_pathway (dict): Configuration of slow branch, should contain + necessary arguments for building the specific type of pathway + and: + type (str): type of backbone the pathway bases on. + lateral (bool): determine whether to build lateral connection + for the pathway.Default: + + .. code-block:: Python + + dict(type='ResNetPathway', + lateral=True, depth=50, pretrained=None, + conv1_kernel=(1, 7, 7), dilations=(1, 1, 1, 1), + conv1_stride_t=1, pool1_stride_t=1, inflate=(0, 0, 1, 1)) + + fast_pathway (dict): Configuration of fast branch, similar to + `slow_pathway`. Default: + + .. code-block:: Python + + dict(type='ResNetPathway', + lateral=False, depth=50, pretrained=None, base_channels=8, + conv1_kernel=(5, 7, 7), conv1_stride_t=1, pool1_stride_t=1) + """ + + def __init__( + self, + pretrained, + pretrain_type="resnet_3d", # "resnet_2d", 'resnet_3d', 'inv_resnet_3d' + resample_rate=8, + speed_ratio=8, + channel_ratio=8, + slow_pathway=dict( + type="resnet3d", + depth=50, + pretrained=None, + lateral=True, + conv1_kernel=(1, 7, 7), + dilations=(1, 1, 1, 1), + conv1_stride_t=1, + pool1_stride_t=1, + inflate=(0, 0, 1, 1), + frozen_stages=-1, + ), + fast_pathway=dict( + type="resnet3d", + depth=50, + pretrained=None, + lateral=False, + base_channels=8, + conv1_kernel=(5, 7, 7), + conv1_stride_t=1, + pool1_stride_t=1, + frozen_stages=-1, + ), + inv_mode=["custom_backprop", "custom_backprop", "custom_backprop", "custom_backprop"], + ): + super().__init__() + self.pretrained = pretrained + self.pretrain_type = pretrain_type + self.resample_rate = resample_rate + self.speed_ratio = speed_ratio + self.channel_ratio = channel_ratio + + if slow_pathway["lateral"]: + slow_pathway["speed_ratio"] = speed_ratio + slow_pathway["channel_ratio"] = channel_ratio + + slow_pathway["inv_mode"] = inv_mode + fast_pathway["inv_mode"] = inv_mode + self.slow_path = build_pathway(slow_pathway) + self.fast_path = build_pathway(fast_pathway) + + def init_weights(self, pretrained=None): + """Initiate the parameters either from existing checkpoint or from + scratch.""" + if pretrained: + self.pretrained = pretrained + + if isinstance(self.pretrained, str): + print(f"load model from: {self.pretrained}") + + if self.pretrain_type == "inv_resnet_3d": + self.load_frm_inv_resnet3d() + elif self.pretrain_type == "resnet_3d": + self.load_frm_resnet3d() + elif self.pretrain_type == "resnet_2d": + raise NotImplemented("Loading resent2d pretrained model is not implemented") + else: + # Directly load 3D model. + load_checkpoint(self, self.pretrained, strict=True) + elif self.pretrained is None: + # Init two branch seperately. + self.fast_path.init_weights() + self.slow_path.init_weights() + else: + raise TypeError("pretrained must be a str or None") + + def load_frm_resnet3d(self): + checkpoint = torch.load(self.pretrained, map_location="cpu") + state_dict = checkpoint["state_dict"] + + state_dict_new = OrderedDict() + for k in state_dict.keys(): + k_new = k + + if "backbone" in k: + k_new = k.split(".")[1:] + k_new = ".".join(k_new) + + if ("layer" in k_new) and ("lateral" not in k_new): + k_new = k_new.split(".") + k_new.insert(2, "blocks") + + if not "downsample" in k: + if "0" in k_new: + k_new.insert(4, "Fm") + else: + k_new.insert(4, "inv_block.Fm") + + k_new = ".".join(k_new) + + state_dict_new[k_new] = state_dict[k] + + msg = load_state_dict(self, state_dict_new, False) + print(msg) + print(f"=> loaded successfully '{self.pretrained}'") + del checkpoint + del state_dict_new + torch.cuda.empty_cache() + + def load_frm_inv_resnet3d(self): + checkpoint = torch.load(self.pretrained, map_location="cpu") + state_dict = checkpoint["state_dict"] + + state_dict_new = OrderedDict() + for k in state_dict.keys(): + k_new = k + + if "backbone" in k: + k_new = k.split(".")[1:] + k_new = ".".join(k_new) + + state_dict_new[k_new] = state_dict[k] + + msg = load_state_dict(self, state_dict_new, False) + print(msg) + print(f"=> loaded successfully '{self.pretrained}'") + del checkpoint + del state_dict_new + torch.cuda.empty_cache() + + def forward(self, x): + """Defines the computation performed at every call. + + Args: + x (torch.Tensor): The input data. + + Returns: + tuple[torch.Tensor]: The feature of the input samples extracted + by the backbone. + """ + x_slow = nn.functional.interpolate(x, mode="nearest", scale_factor=(1.0 / self.resample_rate, 1.0, 1.0)) + x_slow = self.slow_path.conv1(x_slow) + x_slow = self.slow_path.maxpool(x_slow) + + x_fast = nn.functional.interpolate( + x, + mode="nearest", + scale_factor=(1.0 / (self.resample_rate // self.speed_ratio), 1.0, 1.0), + ) + x_fast = self.fast_path.conv1(x_fast) + x_fast = self.fast_path.maxpool(x_fast) + + if self.slow_path.lateral: + x_fast_lateral = self.slow_path.conv1_lateral(x_fast) + x_slow = torch.cat((x_slow, x_fast_lateral), dim=1) + + for i, layer_name in enumerate(self.slow_path.res_layers): + res_layer = getattr(self.slow_path, layer_name) + x_slow = res_layer(x_slow) + res_layer_fast = getattr(self.fast_path, layer_name) + x_fast = res_layer_fast(x_fast) + if i != len(self.slow_path.res_layers) - 1 and self.slow_path.lateral: + # No fusion needed in the final stage + lateral_name = self.slow_path.lateral_connections[i] + conv_lateral = getattr(self.slow_path, lateral_name) + x_fast_lateral = conv_lateral(x_fast) + x_slow = torch.cat((x_slow, x_fast_lateral), dim=1) + + return (x_slow, x_fast) diff --git a/OpenTAD/opentad/models/backbones/re2tal_swin.py b/OpenTAD/opentad/models/backbones/re2tal_swin.py new file mode 100644 index 0000000000000000000000000000000000000000..ccac61cc447d92f6d14548dd625a301b1af37db2 --- /dev/null +++ b/OpenTAD/opentad/models/backbones/re2tal_swin.py @@ -0,0 +1,718 @@ +import sys + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +from torch.cuda.amp import custom_fwd, custom_bwd +from einops import rearrange + +from mmcv.cnn import build_norm_layer +from mmcv.cnn.bricks import DropPath +from mmaction.registry import MODELS +from mmaction.models.backbones.swin import ( + PatchEmbed3D, + PatchMerging, + WindowAttention3D, + Mlp, + get_window_size, + compute_mask, + window_partition, + window_reverse, +) + + +def seed_cuda(): + # randomize seeds, use cuda generator if available + if hasattr(torch.cuda, "default_generators") and len(torch.cuda.default_generators) > 0: + # GPU + device_idx = torch.cuda.current_device() + seed = torch.cuda.default_generators[device_idx].seed() + else: + # CPU + seed = int(torch.seed() % sys.maxsize) + return seed + + +def create_coupling(Fm, Gm=None, coupling="additive", implementation_fwd=-1, implementation_bwd=-1, split_dim=1): + if coupling == "additive": + fn = AdditiveCoupling( + Fm, + Gm, + implementation_fwd=implementation_fwd, + implementation_bwd=implementation_bwd, + split_dim=split_dim, + ) + else: + raise NotImplementedError("Unknown coupling method: %s" % coupling) + return fn + + +class AdditiveCoupling(nn.Module): + def __init__(self, Fm, Gm=None, implementation_fwd=-1, implementation_bwd=-1, split_dim=1): + """ + This computes the output :math:`y` on forward given input :math:`x` and arbitrary modules :math:`Fm` and :math:`Gm` according to: + + :math:`(x1, x2) = x` + :math:`y1 = x1 + Fm(x2)` + :math:`y2 = x2 + Gm(y1)` + :math:`y = (y1, y2)` + + """ + super(AdditiveCoupling, self).__init__() + + self.Gm = Gm + self.Fm = Fm + self.split_dim = split_dim + + def forward(self, x, mask_matrix): + x1, x2 = torch.chunk(x, 2, dim=self.split_dim) + fmd = self.Fm(x2, mask_matrix) + y1 = x1 + fmd + del x1 + + gmd = self.Gm(y1) + y2 = x2 + gmd + del x2 + + out = torch.cat([y1, y2], dim=self.split_dim) + return out + + def inverse(self, y, mask_matrix): + y1, y2 = torch.chunk(y, 2, dim=self.split_dim) + y1, y2 = y1.contiguous(), y2.contiguous() + gmd = self.Gm.forward(y1) + x2 = y2 - gmd + fmd = self.Fm.forward(x2, mask_matrix) + x1 = y1 - fmd + x = torch.cat([x1, x2], dim=self.split_dim) + + return x + + def backward_pass_inverse(self, Y_1, Y_2, mask_matrix): + """ + equations: + Y_1 = X_1 + F(X_2), F = Attention + Y_2 = X_2 + G(Y_1), G = MLP + + equations for recomputing the activations: + X_2 = Y_2 - G(Y_1), G = MLP + X_1 = Y_1 - F(X_2), F = Attention + """ + with torch.enable_grad(): + Y_1.requires_grad = True + g_Y_1 = self.Gm(Y_1) + + with torch.no_grad(): + X_2 = Y_2 - g_Y_1 + + with torch.enable_grad(): + X_2.requires_grad = True + f_X_2 = self.Fm(X_2, mask_matrix) + + with torch.no_grad(): + X_1 = Y_1 - f_X_2 + + del Y_2 + + # Return tensors to do back propagation on the graph. + return X_1, X_2, Y_1, g_Y_1, f_X_2 + + def backward_pass_grads(self, X_2, Y_1, g_Y_1, f_X_2, dY_1, dY_2): + with torch.enable_grad(): + g_Y_1.backward(dY_2) + del g_Y_1 + + with torch.no_grad(): + dY_1 = dY_1 + Y_1.grad + Y_1.grad = None + del Y_1 + + with torch.enable_grad(): + f_X_2.backward(dY_1) + del f_X_2 + + with torch.no_grad(): + dY_2 = dY_2 + X_2.grad + X_2.grad = None + + return dY_1, dY_2 + + def backward_pass(self, Y_1, Y_2, dY_1, dY_2, mask_matrix): + """ + equations: + Y_1 = X_1 + F(X_2), F = Attention + Y_2 = X_2 + G(Y_1), G = MLP + + equations for recomputing of activations: + X_2 = Y_2 - G(Y_1), G = MLP + X_1 = Y_1 - F(X_2), F = Attention + """ + with torch.enable_grad(): + Y_1.requires_grad = True + g_Y_1 = self.Gm(Y_1) + g_Y_1.backward(dY_2, retain_graph=True) + + with torch.no_grad(): + X_2 = Y_2 - g_Y_1 + del g_Y_1 + dY_1 = dY_1 + Y_1.grad + Y_1.grad = None + + with torch.enable_grad(): + X_2.requires_grad = True + f_X_2 = self.Fm(X_2, mask_matrix) + f_X_2.backward(dY_1, retain_graph=True) + + with torch.no_grad(): + X_1 = Y_1 - f_X_2 + del f_X_2, Y_1 + dY_2 = dY_2 + X_2.grad + X_2.grad = None + X_2 = X_2.detach() + + return X_1, X_2, dY_1, dY_2 + + +class RevBackProp(torch.autograd.Function): + @staticmethod + @custom_fwd + def forward(ctx, x, attn_mask, blocks): + for blk in blocks: + x = blk(x, attn_mask) + + all_tensors = [x.detach(), attn_mask.detach()] + ctx.save_for_backward(*all_tensors) + ctx.blocks = blocks + return x + + @staticmethod + @custom_bwd + def backward(ctx, dy): + # retrieve params from ctx for backward + Y, mask_matrix = ctx.saved_tensors + blocks = ctx.blocks + + dY_1, dY_2 = torch.chunk(dy, 2, dim=-1) + Y_1, Y_2 = torch.chunk(Y, 2, dim=-1) + + for _, blk in enumerate(blocks[::-1]): + Y_1, Y_2, dY_1, dY_2 = blk.backward_pass(Y_1=Y_1, Y_2=Y_2, dY_1=dY_1, dY_2=dY_2, mask_matrix=mask_matrix) + + dx = torch.cat([dY_1, dY_2], dim=-1) + del Y_1, Y_2, dY_1, dY_2 + return dx, None, None + + +class RevBackPropStream(RevBackProp): + @staticmethod + def backward(ctx, dy): + Y, mask_matrix = ctx.saved_tensors + blocks = ctx.blocks + + dY_1, dY_2 = torch.chunk(dy, 2, dim=-1) + Y_1, Y_2 = torch.chunk(Y, 2, dim=-1) + + # Run backward staggered on two streams + s1 = torch.cuda.Stream(device=Y_1.device) + s2 = torch.cuda.Stream(device=Y_1.device) + torch.cuda.synchronize() + + # Initial pass + with torch.cuda.stream(s1): + blk = blocks[-1] + X_1, X_2, Y_1, g_Y_1, f_X_2 = blk.backward_pass_inverse(Y_1=Y_1, Y_2=Y_2, mask_matrix=mask_matrix) + s2.wait_stream(s1) + + # Stagger streams based on iteration + for i, (this_blk, next_blk) in enumerate(zip(blocks[1:][::-1], blocks[:-1][::-1])): + if i % 2 == 0: + stream1 = s1 + stream2 = s2 + else: + stream1 = s2 + stream2 = s1 + + with torch.cuda.stream(stream1): + dY_1, dY_2 = this_blk.backward_pass_grads( + X_2=X_2, Y_1=Y_1, g_Y_1=g_Y_1, f_X_2=f_X_2, dY_1=dY_1, dY_2=dY_2 + ) + stream2.wait_stream(stream1) + del Y_1, g_Y_1, f_X_2 + with torch.cuda.stream(stream2): + X_1, X_2, Y_1, g_Y_1, f_X_2 = next_blk.backward_pass_inverse(Y_1=X_1, Y_2=X_2, mask_matrix=mask_matrix) + + stream1.wait_stream(stream2) + + # Last iteration + with torch.cuda.stream(stream2): + dY_1, dY_2 = blocks[0].backward_pass_grads(X_2=X_2, Y_1=Y_1, g_Y_1=g_Y_1, f_X_2=f_X_2, dY_1=dY_1, dY_2=dY_2) + + torch.cuda.current_stream().wait_stream(s1) + torch.cuda.current_stream().wait_stream(s2) + + dx = torch.cat([dY_1, dY_2], dim=-1) + + del X_1, X_2, Y_1, Y_2, dY_1, dY_2, g_Y_1, f_X_2 + return dx, None, None + + +class SwinTransformerBlock3D_F(nn.Module): + def __init__( + self, + dim, + num_heads, + window_size=(2, 7, 7), + shift_size=(0, 0, 0), + qkv_bias=True, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=None, + norm_cfg=dict(type="LN"), + with_cp=False, + ): + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.with_cp = with_cp + self.drop_path = drop_path + self.seeds = {} + self.seeds["droppath"] = seed_cuda() + + assert 0 <= self.shift_size[0] < self.window_size[0], "shift_size must in 0-window_size" + assert 0 <= self.shift_size[1] < self.window_size[1], "shift_size must in 0-window_size" + assert 0 <= self.shift_size[2] < self.window_size[2], "shift_size must in 0-window_size" + + self.norm1 = build_norm_layer(norm_cfg, dim)[1] + self.attn = WindowAttention3D( + dim, + window_size=self.window_size, + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=drop, + ) + + def forward_part1(self, x, mask_matrix): + B, D, H, W, C = x.shape + window_size, shift_size = get_window_size((D, H, W), self.window_size, self.shift_size) + + x = self.norm1(x) + # pad feature maps to multiples of window size + pad_l = pad_t = pad_d0 = 0 + pad_d1 = (window_size[0] - D % window_size[0]) % window_size[0] + pad_b = (window_size[1] - H % window_size[1]) % window_size[1] + pad_r = (window_size[2] - W % window_size[2]) % window_size[2] + x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b, pad_d0, pad_d1)) + _, Dp, Hp, Wp, _ = x.shape + # cyclic shift + if any(i > 0 for i in shift_size): + shifted_x = torch.roll(x, shifts=(-shift_size[0], -shift_size[1], -shift_size[2]), dims=(1, 2, 3)) + attn_mask = mask_matrix + else: + shifted_x = x + attn_mask = None + # partition windows + x_windows = window_partition(shifted_x, window_size) # B*nW, Wd*Wh*Ww, C + # W-MSA/SW-MSA + attn_windows = self.attn(x_windows, mask=attn_mask) # B*nW, Wd*Wh*Ww, C + # merge windows + attn_windows = attn_windows.view(-1, *(window_size + (C,))) + shifted_x = window_reverse(attn_windows, window_size, B, Dp, Hp, Wp) # B D' H' W' C + # reverse cyclic shift + if any(i > 0 for i in shift_size): + x = torch.roll(shifted_x, shifts=(shift_size[0], shift_size[1], shift_size[2]), dims=(1, 2, 3)) + else: + x = shifted_x + + if pad_d1 > 0 or pad_r > 0 or pad_b > 0: + x = x[:, :D, :H, :W, :].contiguous() + return x + + def forward(self, x, mask_matrix): + if self.with_cp: + x = checkpoint.checkpoint(self.forward_part1, x, mask_matrix) + else: + x = self.forward_part1(x, mask_matrix) + torch.manual_seed(self.seeds["droppath"]) + x = self.drop_path(x) + return x + + +class SwinTransformerBlock3D_G(nn.Module): + def __init__( + self, + dim, + mlp_ratio=4.0, + drop=0.0, + drop_path=None, + act_cfg=dict(type="GELU"), + norm_cfg=dict(type="LN"), + with_cp=False, + ): + super().__init__() + self.dim = dim + self.mlp_ratio = mlp_ratio + self.with_cp = with_cp + self.drop_path = drop_path + self.seeds = {} + self.seeds["droppath"] = seed_cuda() + + self.norm2 = build_norm_layer(norm_cfg, dim)[1] + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_cfg=act_cfg, + drop=drop, + ) + + def forward_part2(self, x): + torch.manual_seed(self.seeds["droppath"]) + return self.drop_path(self.mlp(self.norm2(x))) + + def forward(self, x): + if self.with_cp: + x = checkpoint.checkpoint(self.forward_part2, x) + else: + x = self.forward_part2(x) + + return x + + +class SwinTransformerBlock3D(nn.Module): + """Swin Transformer Block. + + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (tuple[int]): Window size. + shift_size (tuple[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=(2, 7, 7), + shift_size=(0, 0, 0), + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + act_cfg=dict(type="GELU"), + norm_cfg=dict(type="LN"), + with_cp=False, + ): + 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 + self.with_cp = with_cp + + drop_path_in = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + fm = SwinTransformerBlock3D_F( + dim=dim, + num_heads=num_heads, + window_size=window_size, + shift_size=shift_size, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop, + attn_drop=attn_drop, + drop_path=drop_path_in, + norm_cfg=norm_cfg, + with_cp=with_cp, + ) + gm = SwinTransformerBlock3D_G( + dim=dim, + mlp_ratio=mlp_ratio, + drop=drop, + drop_path=drop_path_in, + act_cfg=act_cfg, + norm_cfg=norm_cfg, + with_cp=with_cp, + ) + + self.inv_block = create_coupling(Fm=fm, Gm=gm, coupling="additive", split_dim=4) + + def forward(self, x, mask_matrix): + """Forward function. + + Args: + x: Input feature, tensor size (B, D, H, W, C). + mask_matrix: Attention mask for cyclic shift. + """ + x = self.inv_block(x, mask_matrix) + return x + + def backward_pass(self, Y_1, Y_2, dY_1, dY_2, mask_matrix): + return self.inv_block.backward_pass(Y_1=Y_1, Y_2=Y_2, dY_1=dY_1, dY_2=dY_2, mask_matrix=mask_matrix) + + def backward_pass_inverse(self, Y_1, Y_2, mask_matrix): + return self.inv_block.backward_pass_inverse(Y_1=Y_1, Y_2=Y_2, mask_matrix=mask_matrix) + + def backward_pass_grads(self, X_2, Y_1, g_Y_1, f_X_2, dY_1, dY_2): + return self.inv_block.backward_pass_grads(X_2=X_2, Y_1=Y_1, g_Y_1=g_Y_1, f_X_2=f_X_2, dY_1=dY_1, dY_2=dY_2) + + +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 (tuple[int]): Local window size. Default: (1,7,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 + """ + + def __init__( + self, + dim, + depth, + num_heads, + window_size=(1, 7, 7), + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + act_cfg=dict(type="GELU"), + norm_cfg=dict(type="LN"), + downsample=None, + with_cp=False, + inv_mode="custom_backprop", + ): + super().__init__() + self.window_size = window_size + self.shift_size = tuple(i // 2 for i in window_size) + self.depth = depth + self.with_cp = with_cp + + # build blocks + self.blocks = nn.ModuleList( + [ + SwinTransformerBlock3D( + dim=dim, + num_heads=num_heads, + window_size=window_size, + shift_size=(0, 0, 0) if (i % 2 == 0) else self.shift_size, + 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_cfg=norm_cfg, + act_cfg=act_cfg, + with_cp=with_cp, + ) + for i in range(depth) + ] + ) + self.inv_mode = inv_mode + self.downsample = downsample + if self.downsample is not None: + self.downsample = downsample(embed_dims=dim, norm_cfg=norm_cfg) + + def forward(self, x): + """Forward function. + + Args: + x: Input feature, tensor size (B, C, D, H, W). + """ + x = torch.cat((x, x), dim=1) + + # calculate attention mask for SW-MSA + B, C, D, H, W = x.shape + window_size, shift_size = get_window_size((D, H, W), self.window_size, self.shift_size) + x = rearrange(x, "b c d h w -> b d h w c") + Dp = int(np.ceil(D / window_size[0])) * window_size[0] + Hp = int(np.ceil(H / window_size[1])) * window_size[1] + Wp = int(np.ceil(W / window_size[2])) * window_size[2] + attn_mask = compute_mask(Dp, Hp, Wp, window_size, shift_size, x.device) + + if self.inv_mode == "vanilla": + x = self.compute_for_inv_blocks(x, attn_mask) + elif self.inv_mode == "custom_backprop": + x = RevBackProp.apply(x, attn_mask, self.blocks) + elif self.inv_mode == "stream_backprop": + x = RevBackPropStream.apply(x, attn_mask, self.blocks) + + x = x.view(B, D, H, W, -1) + + C = int(C / 2) + x = (x[:, :, :, :, :C] + x[:, :, :, :, C:]) / 2 + + if self.downsample is not None: + x = self.downsample(x) + x = rearrange(x, "b d h w c -> b c d h w") + return x + + def compute_for_inv_blocks(self, x, attn_mask): + for blk in self.blocks: + x = blk(x, attn_mask) + return x + + +@MODELS.register_module() +class SwinTransformer3D_inv(nn.Module): + """Swin Transformer backbone. + A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - + https://arxiv.org/pdf/2103.14030 + + Args: + patch_size (int | tuple(int)): Patch size. Default: (4,4,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: Truee + 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: Normalization layer. Default: nn.LayerNorm. + patch_norm (bool): If True, add normalization after patch embedding. Default: False. + frozen_stages (int): Stages to be frozen (stop grad and set eval mode). + -1 means not freezing any parameters. + """ + + def __init__( + self, + patch_size=(4, 4, 4), + in_chans=3, + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=(2, 7, 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, + act_cfg=dict(type="GELU"), + norm_cfg=dict(type="LN"), + patch_norm=False, + frozen_stages=-1, + with_cp=False, + inv_mode=["custom_backprop", "custom_backprop", "custom_backprop", "custom_backprop"], + norm_eval=True, + ): + super().__init__() + + self.num_layers = len(depths) + self.embed_dim = embed_dim + self.patch_norm = patch_norm + self.frozen_stages = frozen_stages + self.norm_eval = norm_eval + self.window_size = window_size + self.patch_size = patch_size + + # split image into non-overlapping patches + self.patch_embed = PatchEmbed3D( + patch_size=patch_size, + in_channels=in_chans, + embed_dims=embed_dim, + norm_cfg=norm_cfg if self.patch_norm else None, + conv_cfg=dict(type="Conv3d"), + ) + + 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() + for i_layer in range(self.num_layers): + layer = BasicLayer( + dim=int(embed_dim * 2**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])], + act_cfg=act_cfg, + norm_cfg=norm_cfg, + downsample=PatchMerging if i_layer < self.num_layers - 1 else None, + with_cp=with_cp, + inv_mode=inv_mode[i_layer], + ) + self.layers.append(layer) + + self.num_features = int(embed_dim * 2 ** (self.num_layers - 1)) + + # add a norm layer for each output + self.norm3 = build_norm_layer(norm_cfg, self.num_features)[1] + + def forward(self, x): + """Forward function.""" + x = self.patch_embed(x) + + x = self.pos_drop(x) + for layer in self.layers: + x = layer(x.contiguous()) + + x = rearrange(x, "n c d h w -> n d h w c") + x = self.norm3(x) + x = rearrange(x, "n d h w c -> n c d h w") + return x # [b,c,t,h,w] + + 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: + self.pos_drop.eval() + for i in range(0, self.frozen_stages): + m = self.layers[i] + m.eval() + for param in m.parameters(): + param.requires_grad = False + + def train(self, mode=True): + """Convert the model into training mode while keep layers freezed.""" + super(SwinTransformer3D_inv, self).train(mode) + self._freeze_stages() + + if mode and self.norm_eval: + for m in self.modules(): + if isinstance(m, nn.LayerNorm): + m.eval() diff --git a/OpenTAD/opentad/models/bricks/__init__.py b/OpenTAD/opentad/models/bricks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f42d277ab9351feb365327a9f9b35fd8923fc76c --- /dev/null +++ b/OpenTAD/opentad/models/bricks/__init__.py @@ -0,0 +1,18 @@ +from .conv import ConvModule +from .gcnext import GCNeXt +from .misc import Scale +from .transformer import TransformerBlock, AffineDropPath +from .bottleneck import ConvNeXtV1Block, ConvNeXtV2Block, ConvFormerBlock +from .sgp import SGPBlock + +__all__ = [ + "ConvModule", + "GCNeXt", + "Scale", + "TransformerBlock", + "AffineDropPath", + "SGPBlock", + "ConvNeXtV1Block", + "ConvNeXtV2Block", + "ConvFormerBlock", +] diff --git a/OpenTAD/opentad/models/bricks/bottleneck.py b/OpenTAD/opentad/models/bricks/bottleneck.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b701688fcba0057a6ca0477426b8e72f79483f --- /dev/null +++ b/OpenTAD/opentad/models/bricks/bottleneck.py @@ -0,0 +1,276 @@ +import math +import torch +import torch.nn as nn + +from .conv import ConvModule +from .transformer import DropPath, AffineDropPath + + +class Bottleneck(nn.Module): + def __init__( + self, + in_channels, + out_channels, + stride=1, + cardinality=1, + base_width=64, + norm_cfg=None, + drop_path=0, + expansion=4, + ): + super(Bottleneck, self).__init__() + + planes = out_channels / expansion + width = int(math.floor(planes * (base_width / 64)) * cardinality) + + self.conv_bn_act_1 = ConvModule( + in_channels, + width, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + + self.conv_bn_act_2 = ConvModule( + width, + width, + kernel_size=3, + stride=stride, + padding=1, + conv_cfg=dict(groups=cardinality), + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + + self.conv_bn_3 = ConvModule( + width, + out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + ) + + self.act3 = nn.ReLU(inplace=True) + + if stride > 1 or in_channels != out_channels: + self.downsample = ConvModule( + in_channels, + out_channels, + kernel_size=1, + stride=stride, + norm_cfg=norm_cfg, + ) + else: + self.downsample = None + + self.drop_path = AffineDropPath(out_channels, drop_prob=drop_path) if drop_path > 0 else nn.Identity() + + def forward(self, x, mask=None): + shortcut, shortcut_mask = x, mask + + x, mask = self.conv_bn_act_1(x, mask) + x, mask = self.conv_bn_act_2(x, mask) + x, mask = self.conv_bn_3(x, mask) + + if self.drop_path is not None: + x = self.drop_path(x) + + if self.downsample is not None: + shortcut, shortcut_mask = self.downsample(shortcut, shortcut_mask) + x += shortcut + x = self.act3(x) + return x, mask + + +class ConvNeXtV1Block(nn.Module): + # this follows the implementation of ConvNext V1 design + def __init__(self, dim, kernel_size=3, stride=1, expansion_ratio=4, drop_path=0): + super().__init__() + + # depthwise conv + self.dw_conv = nn.Conv1d( + dim, + dim, + kernel_size=kernel_size, + stride=stride, + padding=kernel_size // 2, + groups=dim, + ) + self.norm = nn.LayerNorm(dim, eps=1e-6) + + # pointwise conv + self.pw_conv1 = nn.Linear(dim, expansion_ratio * dim) # pointwise/1x1 convs, implemented with linear layers + self.act = nn.GELU() + self.pw_conv2 = nn.Linear(expansion_ratio * dim, dim) + + # drop path + self.drop_path = AffineDropPath(dim, drop_prob=drop_path) if drop_path > 0 else nn.Identity() + + # residual + if stride > 1: + self.shortcut = nn.MaxPool1d(kernel_size=kernel_size, stride=stride, padding=kernel_size // 2) + else: + self.shortcut = nn.Identity() + + # init weights + self.apply(self.__init_weights__) + + def __init_weights__(self, module): + if isinstance(module, (nn.Conv1d, nn.Linear)): + # use pytorch's default init + nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5)) + # set nn.Conv1d bias term to 0 + if module.bias is not None: + nn.init.constant_(module.bias, 0.0) + elif isinstance(module, nn.LayerNorm): + nn.init.constant_(module.weight, 1.0) + nn.init.constant_(module.bias, 0.0) + + def forward(self, x, mask=None): + residual = x + + x = self.dw_conv(x) + x = x.permute(0, 2, 1) # (N, C, T) -> (N, T, C) + x = self.norm(x) + x = self.pw_conv1(x) + x = self.act(x) + x = self.pw_conv2(x) + x = x.permute(0, 2, 1) # (N, T, C) -> (N, C, T) + + x = self.shortcut(residual) + self.drop_path(x) + + if mask == None: + return x + else: + mask = self.shortcut(mask.float()).bool() + x = x * mask.unsqueeze(1).float().detach() + return x, mask + + +class ConvNeXtV2Block(nn.Module): + # this follows the implementation of ConvNext V2 design + + def __init__(self, dim, kernel_size=3, stride=1, expansion_ratio=4, drop_path=0): + super().__init__() + + # depthwise conv + self.dw_conv = nn.Conv1d( + dim, + dim, + kernel_size=kernel_size, + stride=stride, + padding=kernel_size // 2, + groups=dim, + ) + self.norm = nn.LayerNorm(dim, eps=1e-6) + + # pointwise conv + self.pw_conv1 = nn.Linear(dim, expansion_ratio * dim) # pointwise/1x1 convs, implemented with linear layers + self.act = nn.GELU() + self.grn = GRN(4 * dim) # new in ConvNeXtV2 + self.pw_conv2 = nn.Linear(expansion_ratio * dim, dim) + + # drop path + self.drop_path = AffineDropPath(dim, drop_prob=drop_path) if drop_path > 0 else nn.Identity() + + # residual + if stride > 1: + self.shortcut = nn.MaxPool1d(kernel_size=kernel_size, stride=stride, padding=kernel_size // 2) + else: + self.shortcut = nn.Identity() + + # init weights + self.apply(self.__init_weights__) + + def __init_weights__(self, module): + if isinstance(module, (nn.Conv1d, nn.Linear)): + # use pytorch's default init + nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5)) + # set nn.Conv1d bias term to 0 + if module.bias is not None: + nn.init.constant_(module.bias, 0.0) + elif isinstance(module, nn.LayerNorm): + nn.init.constant_(module.weight, 1.0) + nn.init.constant_(module.bias, 0.0) + + def forward(self, x, mask=None): + residual = x + + x = self.dw_conv(x) + x = x.permute(0, 2, 1) # (N, C, T) -> (N, T, C) + x = self.norm(x) + x = self.pw_conv1(x) + x = self.act(x) + x = self.grn(x) + x = self.pw_conv2(x) + x = x.permute(0, 2, 1) # (N, T, C) -> (N, C, T) + + x = self.shortcut(residual) + self.drop_path(x) + + if mask == None: + return x + else: + mask = self.shortcut(mask.float()).bool() + x = x * mask.unsqueeze(1).float().detach() + return x, mask + + +class GRN(nn.Module): + """GRN (Global Response Normalization) layer""" + + def __init__(self, dim): + super().__init__() + self.gamma = nn.Parameter(torch.zeros(1, 1, dim)) + self.beta = nn.Parameter(torch.zeros(1, 1, dim)) + + def forward(self, x): + Gx = torch.norm(x, p=2, dim=1, keepdim=True) + Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6) + return self.gamma * (x * Nx) + self.beta + x + + +class ConvFormerBlock(nn.Module): + def __init__(self, dim, kernel_size=3, expansion_ratio=4, drop_path=0): + super().__init__() + + self.norm1 = nn.LayerNorm(dim, eps=1e-6) + self.conv = nn.Conv1d( + dim, + dim, + kernel_size=kernel_size, + stride=1, + padding=kernel_size // 2, + ) + + self.norm2 = nn.LayerNorm(dim, eps=1e-6) + self.mlp = nn.Sequential( + nn.Linear(dim, expansion_ratio * dim), + nn.GELU(), + nn.Linear(expansion_ratio * dim, dim), + ) + + # drop path + self.drop_path = AffineDropPath(dim, drop_prob=drop_path) if drop_path > 0 else nn.Identity() + + # init weights + self.apply(self.__init_weights__) + + def __init_weights__(self, module): + if isinstance(module, (nn.Conv1d, nn.Linear)): + # use pytorch's default init + nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5)) + # set nn.Conv1d bias term to 0 + if module.bias is not None: + nn.init.constant_(module.bias, 0.0) + elif isinstance(module, nn.LayerNorm): + nn.init.constant_(module.weight, 1.0) + nn.init.constant_(module.bias, 0.0) + + def forward(self, x, mask=None): + x = x + self.drop_path(self.conv(self.norm1(x.permute(0, 2, 1)).permute(0, 2, 1))) + x = x + self.drop_path(self.mlp(self.norm2(x.permute(0, 2, 1))).permute(0, 2, 1)) + + if mask == None: + return x + else: + x = x * mask.unsqueeze(1).float().detach() + return x, mask diff --git a/OpenTAD/opentad/models/bricks/conv.py b/OpenTAD/opentad/models/bricks/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..dbab9c2c87b0df28f1b69e037e372e2b4b4c6302 --- /dev/null +++ b/OpenTAD/opentad/models/bricks/conv.py @@ -0,0 +1,112 @@ +import copy +import math +import torch.nn.functional as F +import torch.nn as nn +from ..builder import MODELS + + +@MODELS.register_module() +class ConvModule(nn.Module): + def __init__( + self, + in_channels, + out_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=None, + norm_cfg=None, + act_cfg=None, # default to none to remind, act_cfg=dict(type="relu"), + ): + super().__init__() + # norm config + assert norm_cfg is None or isinstance(norm_cfg, dict) + self.with_norm = norm_cfg is not None + + # conv config + conv_cfg_base = dict( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + ) + + if self.with_norm: + conv_cfg_base["bias"] = False # bias is not necessary with a normalization layer + + assert conv_cfg is None or isinstance(conv_cfg, dict) + if conv_cfg is not None: # update conv_cfg_base + conv_cfg_base.update(conv_cfg) + + # build conv layer + self.conv = nn.Conv1d(**conv_cfg_base) + + # build norm layer + if self.with_norm: + norm_cfg = copy.copy(norm_cfg) # make a copy + norm_type = norm_cfg["type"] + norm_cfg.pop("type") + self.norm_type = norm_type + + if norm_type == "BN": + self.norm = nn.BatchNorm1d(num_features=out_channels, **norm_cfg) + elif norm_type == "GN": + self.norm = nn.GroupNorm(num_channels=out_channels, **norm_cfg) + elif norm_type == "LN": + self.norm = nn.LayerNorm(out_channels) + + # build activation layer + assert act_cfg is None or isinstance(act_cfg, dict) + self.with_act = act_cfg is not None + + if self.with_act: + act_cfg = copy.copy(act_cfg) # make a copy + act_type = act_cfg["type"] + act_cfg.pop("type") + + if act_type == "relu": + self.act = nn.ReLU(inplace=True, **act_cfg) + else: # other type + self.act = eval(act_type)(**act_cfg) + + # init weights + self.apply(self.__init_weights__) + + def __init_weights__(self, module): + if isinstance(module, nn.Conv1d): + # use pytorch's default init + nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5)) + # set nn.Conv1d bias term to 0 + if module.bias is not None: + nn.init.constant_(module.bias, 0.0) + elif isinstance(module, (nn.BatchNorm1d, nn.GroupNorm, nn.LayerNorm)): + nn.init.constant_(module.weight, 1.0) + nn.init.constant_(module.bias, 0.0) + + def forward(self, x, mask=None): + x = self.conv(x) + + if mask is not None: # masking before the norm + if mask.shape[-1] != x.shape[-1]: + mask = ( + F.interpolate(mask.unsqueeze(1).to(x.dtype), size=x.size(-1), mode="nearest") + .squeeze(1) + .to(mask.dtype) + ) + x = x * mask.unsqueeze(1).float().detach() # [B,C,T] + + if self.with_norm: + if self.norm_type == "LN": + x = self.norm(x.permute(0, 2, 1)).permute(0, 2, 1) + else: + x = self.norm(x) + + if self.with_act: + x = self.act(x) + + if mask is not None: # masking the output + x = x * mask.unsqueeze(1).float().detach() # [B,C,T] + return x, mask + else: + return x diff --git a/OpenTAD/opentad/models/bricks/deform_conv1d.py b/OpenTAD/opentad/models/bricks/deform_conv1d.py new file mode 100644 index 0000000000000000000000000000000000000000..5c17d370f9fa25145725c1eb292dab90ec302c57 --- /dev/null +++ b/OpenTAD/opentad/models/bricks/deform_conv1d.py @@ -0,0 +1,123 @@ +import math +import torch +from torch import nn, Tensor +from torch.nn.parameter import Parameter +from torch.nn import init +from typing import Optional + +import torch.nn as nn +from torchvision.ops.deform_conv import deform_conv2d + + +def deform_conv1d( + input: Tensor, # shape [B,in_channels,T_in] + offset: Tensor, # shape [B,kernel_size_t,T_out] + weight: Tensor, # shape [out_channels,in_channels,kernel_size_t] + bias: Optional[Tensor] = None, # shape [out_channels] + stride: int = 1, + padding: int = 0, + dilation: int = 1, + mask: Optional[Tensor] = None, # not implemented yet +) -> Tensor: + assert mask == None, "mask is not implemented yet" + + input2d = input.unsqueeze(-1) # [B,in_channels,T_in,1] + offset2d = torch.zeros_like(offset).repeat(1, 2, 1).unsqueeze(-1) # [B,2*kernel_size_t*1,T_out,1] + offset2d[:, 0::2, :, 0] += offset # add offset to H dimension + weight2d = weight.unsqueeze(-1) # [out_channels,in_channels,kernel_size_t,1] + + out_2d = deform_conv2d( + input=input2d, + offset=offset2d, + weight=weight2d, + bias=bias, + stride=(stride, 1), + padding=(padding, 0), + dilation=(dilation, 1), + mask=mask, + ) + out = out_2d.squeeze(-1) # [B,out_channels,T_out] + return out + + +class DeformConv1d(nn.Module): + """We use torchvision.ops.deform_conv2d to implement deform_conv1d.""" + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + stride: int = 1, + padding: int = 0, + dilation: int = 1, + groups: int = 1, + bias: bool = True, + ): + super().__init__() + + if in_channels % groups != 0: + raise ValueError("in_channels must be divisible by groups") + if out_channels % groups != 0: + raise ValueError("out_channels must be divisible by groups") + + self.in_channels = in_channels + self.out_channels = out_channels + self.kernel_size = kernel_size + self.stride = stride + self.padding = padding + self.dilation = dilation + self.groups = groups + + self.weight = Parameter(torch.empty(out_channels, in_channels // groups, self.kernel_size)) + + if bias: + self.bias = Parameter(torch.empty(out_channels)) + else: + self.register_parameter("bias", None) + + self.reset_parameters() + + def reset_parameters(self) -> None: + init.kaiming_uniform_(self.weight, a=math.sqrt(5)) + + if self.bias is not None: + fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight) + bound = 1 / math.sqrt(fan_in) + init.uniform_(self.bias, -bound, bound) + + def forward(self, input: Tensor, offset: Tensor, mask: Optional[Tensor] = None) -> Tensor: + """ + Args: + input (Tensor[batch_size, in_channels, in_length]): input tensor + offset (Tensor[batch_size, offset_groups * kernel_length, out_length]): + offsets to be applied for each position in the convolution kernel. + mask (Tensor[batch_size, offset_groups * kernel_length, out_length]): + masks to be applied for each position in the convolution kernel. + """ + return deform_conv1d( + input, + offset, + self.weight, + self.bias, + stride=self.stride, + padding=self.padding, + dilation=self.dilation, + mask=mask, + ) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"{self.in_channels}" + f", {self.out_channels}" + f", kernel_size={self.kernel_size}" + f", stride={self.stride}" + ) + s += f", padding={self.padding}" if self.padding != 0 else "" + s += f", dilation={self.dilation}" if self.dilation != 1 else "" + s += f", groups={self.groups}" if self.groups != 1 else "" + s += ", bias=False" if self.bias is None else "" + s += ")" + + return s diff --git a/OpenTAD/opentad/models/bricks/gcn.py b/OpenTAD/opentad/models/bricks/gcn.py new file mode 100644 index 0000000000000000000000000000000000000000..894fa5c4396c867ad58073229a9430e36104a267 --- /dev/null +++ b/OpenTAD/opentad/models/bricks/gcn.py @@ -0,0 +1,118 @@ +import torch +import torch.nn as nn +from ..builder import MODELS + + +# dynamic graph from knn +def knn(x, y=None, k=10): + if y is None: + y = x + dif = torch.sum((x.unsqueeze(2) - y.unsqueeze(3)) ** 2, dim=1) + idx_org = dif.topk(k=k, dim=-1, largest=False)[1] + + return idx_org + + +def get_neigh_idx_semantic(x, n_neigh): + B, _, num_prop_v = x.shape + neigh_idx = knn(x, k=n_neigh).to(dtype=torch.float32) + shift = torch.tensor(range(B), dtype=torch.float32, device=x.device) * num_prop_v + shift = shift[:, None, None].repeat(1, num_prop_v, n_neigh) + neigh_idx = (neigh_idx + shift).view(-1) + return neigh_idx + + +class NeighConv(nn.Module): + def __init__(self, feat_channels, num_neigh, nfeat_mode, agg_type, edge_weight): + super(NeighConv, self).__init__() + self.num_neigh = num_neigh + self.nfeat_mode = nfeat_mode + self.agg_type = agg_type + self.edge_weight = edge_weight + + self.mlp = nn.Linear(feat_channels * 2, feat_channels) + + def forward(self, x): + bs, C, num_frm = x.shape + neigh_idx = get_neigh_idx_semantic(x, self.num_neigh) + + feat_prop = x.permute(0, 2, 1).reshape(-1, C) + feat_neigh = feat_prop[neigh_idx.to(torch.long)] + f_neigh_temp = feat_neigh.view(-1, self.num_neigh, feat_neigh.shape[-1]) + + if self.nfeat_mode == "feat_ctr": + feat_neigh = torch.cat( + ( + feat_neigh.view(-1, self.num_neigh, feat_prop.size(-1)), + feat_prop.view(-1, 1, feat_prop.size(-1)).repeat(1, self.num_neigh, 1), + ), + dim=-1, + ) + elif self.nfeat_mode == "dif_ctr": + feat_prop = feat_prop.view(-1, 1, feat_prop.size(-1)).repeat(1, self.num_neigh, 1) + diff = feat_neigh.view(-1, self.num_neigh, feat_prop.size(-1)) - feat_prop + feat_neigh = torch.cat((diff, feat_prop), dim=-1) + elif self.nfeat_mode == "feat": + feat_neigh = feat_neigh.view(-1, self.num_neigh, feat_prop.size(-1)) + + feat_neigh_out = self.mlp(feat_neigh) + if self.edge_weight == "true": + weight = torch.matmul(f_neigh_temp, feat_prop.unsqueeze(2)) + weight_denom1 = torch.sqrt(torch.sum(f_neigh_temp * f_neigh_temp, dim=2, keepdim=True)) + weight_denom2 = torch.sqrt(torch.sum(feat_prop.unsqueeze(2) * feat_prop.unsqueeze(2), dim=1, keepdim=True)) + weight = (weight / torch.matmul(weight_denom1, weight_denom2)).squeeze(2) + feat_neigh_out = feat_neigh_out * weight.unsqueeze(2) + + if self.agg_type == "max": + feat_neigh_out = feat_neigh_out.max(dim=1, keepdim=False)[0] + elif self.agg_type == "mean": + feat_neigh_out = feat_neigh_out.mean(dim=1, keepdim=False) + return feat_neigh_out.view(bs, num_frm, -1).permute(0, 2, 1) + + +class xGN(nn.Module): + def __init__( + self, + feat_channels, + stride, + gcn_kwargs=dict(num_neigh=10, nfeat_mode="feat_ctr", agg_type="max", edge_weight="false"), + ): + super(xGN, self).__init__() + + self.tconv1 = nn.Conv1d( + in_channels=feat_channels, + out_channels=feat_channels, + kernel_size=3, + stride=1, + padding=1, + groups=1, + ) + + self.nconv1 = NeighConv(feat_channels, **gcn_kwargs) + + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool1d(kernel_size=3, stride=stride, padding=1) + + def forward(self, x, mask=None): + """ + Args: + x: Feature from previous layer, tensor size (B, C, T) + Returns: + output: tensor size (B, C, T) + """ + + # CNN + c_out = self.tconv1(x) + + # GCN + g_out = self.nconv1(x) + + out = self.relu(c_out + g_out) + out = self.maxpool(out) + + if mask is not None: + mask = self.maxpool(mask.float()).bool() + out = out * mask.unsqueeze(1).to(out.dtype).detach() + return out, mask + else: + return out diff --git a/OpenTAD/opentad/models/bricks/gcnext.py b/OpenTAD/opentad/models/bricks/gcnext.py new file mode 100644 index 0000000000000000000000000000000000000000..5037583ac79cd66748fb292f7ecf80b449b99540 --- /dev/null +++ b/OpenTAD/opentad/models/bricks/gcnext.py @@ -0,0 +1,108 @@ +# copy from https://github.dev/frostinassiky/gtad/blob/3f145d5d3a8ce7ac8d2b985934dbb575ca1b7981/gtad_lib/models.py +import torch +import torch.nn as nn +import numpy as np +from ..builder import MODELS + + +@MODELS.register_module() +class GCNeXt(nn.Module): + def __init__(self, in_channels, out_channels, k=3, groups=32): + super().__init__() + + width_group = 4 + self.k = k + self.groups = groups + + width = width_group * groups + # temporal graph + self.tconvs = nn.Sequential( + nn.Conv1d(in_channels, width, kernel_size=1), + nn.ReLU(True), + nn.Conv1d(width, width, kernel_size=3, groups=groups, padding=1), + nn.ReLU(True), + nn.Conv1d(width, out_channels, kernel_size=1), + ) + # semantic graph + self.sconvs = nn.Sequential( + nn.Conv2d(in_channels * 2, width, kernel_size=1), + nn.ReLU(True), + nn.Conv2d(width, width, kernel_size=1, groups=groups), + nn.ReLU(True), + nn.Conv2d(width, out_channels, kernel_size=1), + ) + + self.relu = nn.ReLU(True) + + def forward(self, x, masks=None): + identity = x # residual + tout = self.tconvs(x) # conv on temporal graph + + x_f = get_graph_feature(x, k=self.k, style=1) # (bs,ch,100) -> (bs, 2ch, 100, k) + sout = self.sconvs(x_f) # conv on semantic graph + sout = sout.max(dim=-1, keepdim=False)[0] # (bs, ch, 100, k) -> (bs, ch, 100) + + out = tout + identity + sout # fusion + if masks != None: + return self.relu(out) * masks.unsqueeze(1).float().detach(), masks + else: + return self.relu(out) + + +# dynamic graph from knn +def knn(x, y=None, k=10): + """ + :param x: BxCxN + :param y: BxCxM + :param k: scalar + :return: BxMxk + """ + if y is None: + y = x + inner = -2 * torch.matmul(y.transpose(2, 1), x) + xx = torch.sum(x**2, dim=1, keepdim=True) + yy = torch.sum(y**2, dim=1, keepdim=True) + pairwise_distance = -xx - inner - yy.transpose(2, 1) + _, idx = pairwise_distance.topk(k=k, dim=-1) # (batch_size, num_points, k) + return idx + + +# get graph feature +def get_graph_feature(x, prev_x=None, k=20, idx_knn=None, r=-1, style=0): + """ + :param x: + :param prev_x: + :param k: + :param idx: + :param r: output downsampling factor (-1 for no downsampling) + :param style: method to get graph feature + :return: + """ + batch_size = x.size(0) + num_points = x.size(2) # if prev_x is None else prev_x.size(2) + x = x.view(batch_size, -1, num_points) + if idx_knn is None: + idx_knn = knn(x=x, y=prev_x, k=k) # (batch_size, num_points, k) + else: + k = idx_knn.shape[-1] + # print(idx_knn.shape) + device = x.device # torch.device('cuda') + idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1) * num_points + idx = idx_knn + idx_base + idx = idx.view(-1) + _, num_dims, _ = x.size() + x = x.transpose(2, 1).contiguous() # (batch_size, num_points, num_dims) -> (batch_size*num_points, num_dims) + feature = x.view(batch_size * num_points, -1)[idx, :] + feature = feature.view(batch_size, num_points, k, num_dims) + x = x.view(batch_size, num_points, 1, num_dims).repeat(1, 1, k, 1) + if style == 0: # use offset as feature + feature = torch.cat((feature - x, x), dim=3).permute(0, 3, 1, 2) + elif style == 1: # use feature as feature + feature = torch.cat((feature, x), dim=3).permute(0, 3, 1, 2) + else: # style == 2: + feature = feature.permute(0, 3, 1, 2) + # downsample if needed + if r != -1: + select_idx = torch.from_numpy(np.random.choice(feature.size(2), feature.size(2) // r, replace=False)) + feature = feature[:, :, select_idx.to(device=device), :] + return feature.contiguous() diff --git a/OpenTAD/opentad/models/bricks/misc.py b/OpenTAD/opentad/models/bricks/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..b5b66a60055d7fabd4ce8433f2cf573dccefc72c --- /dev/null +++ b/OpenTAD/opentad/models/bricks/misc.py @@ -0,0 +1,21 @@ +import torch +import torch.nn as nn + + +class Scale(nn.Module): + """ + Multiply the output regression range by a learnable constant value + """ + + def __init__(self, init_value=1.0): + """ + init_value : initial value for the scalar + """ + super().__init__() + self.scale = nn.Parameter(torch.tensor(init_value, dtype=torch.float32), requires_grad=True) + + def forward(self, x): + """ + input -> scale * input + """ + return x * self.scale diff --git a/OpenTAD/opentad/models/bricks/norm.py b/OpenTAD/opentad/models/bricks/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..b37234001a1eb6f81074f1f6018a7b86c16fe1d1 --- /dev/null +++ b/OpenTAD/opentad/models/bricks/norm.py @@ -0,0 +1,32 @@ +import torch.nn as nn +from einops.layers.torch import Rearrange + + +class NormModule(nn.Module): + def __init__(self, norm_type, norm_dim, **kwargs): # ["BN,"GN","LN"] + super().__init__() + + assert norm_type in ["BN", "GN", "LN"] + + if norm_type == "BN": + self.norm = nn.BatchNorm1d(num_features=norm_dim, **kwargs) + elif norm_type == "GN": + self.norm = nn.GroupNorm(num_channels=norm_dim, **kwargs) + elif norm_type == "LN": + self.norm = nn.Sequential( + Rearrange("b c t -> b t c"), + nn.LayerNorm(norm_dim), + Rearrange("b t c-> b c t"), + ) + + def forward(self, x): + return self.norm(x) + + +class LayerNorm(nn.LayerNorm): + def __init__(self, *args, **kwarg): + super().__init__(*args, **kwarg) + + def forward(self, x): + assert x.dim() == 3 + return super().forward(x.permute(0, 2, 1)).permute(0, 2, 1) diff --git a/OpenTAD/opentad/models/bricks/sgp.py b/OpenTAD/opentad/models/bricks/sgp.py new file mode 100644 index 0000000000000000000000000000000000000000..35be1e49160a2547d29b642094b0a78a777c42fd --- /dev/null +++ b/OpenTAD/opentad/models/bricks/sgp.py @@ -0,0 +1,123 @@ +import torch +import torch.nn.functional as F +import torch.nn as nn + +from .transformer import AffineDropPath + + +class SGPBlock(nn.Module): + """ + A simple conv block similar to the basic block used in ResNet + """ + + def __init__( + self, + n_embd, # dimension of the input features + kernel_size=3, # conv kernel size + n_ds_stride=1, # downsampling stride for the current layer + k=1.5, # k + group=1, # group for cnn + n_out=None, # output dimension, if None, set to input dim + n_hidden=None, # hidden dim for mlp + path_pdrop=0.0, # drop path rate + act_layer=nn.GELU, # nonlinear activation used after conv, default ReLU, + downsample_type="max", + init_conv_vars=1, # init gaussian variance for the weight + ): + super().__init__() + self.kernel_size = kernel_size + self.stride = n_ds_stride + + if n_out is None: + n_out = n_embd + + self.ln = nn.LayerNorm(n_embd) + self.gn = nn.GroupNorm(16, n_embd) + + assert kernel_size % 2 == 1 + # add 1 to avoid have the same size as the instant-level branch + up_size = round((kernel_size + 1) * k) + up_size = up_size + 1 if up_size % 2 == 0 else up_size + + self.psi = nn.Conv1d(n_embd, n_embd, kernel_size, stride=1, padding=kernel_size // 2, groups=n_embd) + self.fc = nn.Conv1d(n_embd, n_embd, 1, stride=1, padding=0, groups=n_embd) + self.convw = nn.Conv1d(n_embd, n_embd, kernel_size, stride=1, padding=kernel_size // 2, groups=n_embd) + self.convkw = nn.Conv1d(n_embd, n_embd, up_size, stride=1, padding=up_size // 2, groups=n_embd) + self.global_fc = nn.Conv1d(n_embd, n_embd, 1, stride=1, padding=0, groups=n_embd) + + # input + if n_ds_stride > 1: + if downsample_type == "max": + kernel_size, stride, padding = n_ds_stride + 1, n_ds_stride, (n_ds_stride + 1) // 2 + self.downsample = nn.MaxPool1d(kernel_size, stride=stride, padding=padding) + self.stride = stride + elif downsample_type == "avg": + self.downsample = nn.Sequential( + nn.AvgPool1d(n_ds_stride, stride=n_ds_stride, padding=0), + nn.Conv1d(n_embd, n_embd, 1, 1, 0), + ) + self.stride = n_ds_stride + else: + raise NotImplementedError("downsample type error") + else: + self.downsample = nn.Identity() + self.stride = 1 + + # two layer mlp + if n_hidden is None: + n_hidden = 4 * n_embd # default + if n_out is None: + n_out = n_embd + + self.mlp = nn.Sequential( + nn.Conv1d(n_embd, n_hidden, 1, groups=group), + act_layer(), + nn.Conv1d(n_hidden, n_out, 1, groups=group), + ) + + # drop path + if path_pdrop > 0.0: + self.drop_path_out = AffineDropPath(n_embd, drop_prob=path_pdrop) + self.drop_path_mlp = AffineDropPath(n_out, drop_prob=path_pdrop) + else: + self.drop_path_out = nn.Identity() + self.drop_path_mlp = nn.Identity() + + self.act = act_layer() + self.reset_params(init_conv_vars=init_conv_vars) + + def reset_params(self, init_conv_vars=0): + torch.nn.init.normal_(self.psi.weight, 0, init_conv_vars) + torch.nn.init.normal_(self.fc.weight, 0, init_conv_vars) + torch.nn.init.normal_(self.convw.weight, 0, init_conv_vars) + torch.nn.init.normal_(self.convkw.weight, 0, init_conv_vars) + torch.nn.init.normal_(self.global_fc.weight, 0, init_conv_vars) + torch.nn.init.constant_(self.psi.bias, 0) + torch.nn.init.constant_(self.fc.bias, 0) + torch.nn.init.constant_(self.convw.bias, 0) + torch.nn.init.constant_(self.convkw.bias, 0) + torch.nn.init.constant_(self.global_fc.bias, 0) + + def forward(self, x, mask): + B, C, T = x.shape + x = self.downsample(x) + + out_mask = F.interpolate( + mask.unsqueeze(1).to(x.dtype), + size=torch.div(T, self.stride, rounding_mode="trunc"), + mode="nearest", + ).detach() + + out = self.ln(x.permute(0, 2, 1)).permute(0, 2, 1) + psi = self.psi(out) + fc = self.fc(out) + convw = self.convw(out) + convkw = self.convkw(out) + phi = torch.relu(self.global_fc(out.mean(dim=-1, keepdim=True))) + out = fc * phi + (convw + convkw) * psi + out + + out = x * out_mask + self.drop_path_out(out) + # FFN + out = out + self.drop_path_mlp(self.mlp(self.gn(out))) + + return out, out_mask.squeeze(1).bool() diff --git a/OpenTAD/opentad/models/bricks/transformer.py b/OpenTAD/opentad/models/bricks/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..288fe0d7700d452bb1f3bc20d0ebe86ce91782b6 --- /dev/null +++ b/OpenTAD/opentad/models/bricks/transformer.py @@ -0,0 +1,599 @@ +import math +import torch +import torch.nn.functional as F +import torch.nn as nn + +from .conv import ConvModule +from ..builder import MODELS + + +@MODELS.register_module() +class TransformerBlock(nn.Module): + """ + Adapted from https://github.com/happyharrycn/actionformer_release/blob/main/libs/modeling/blocks.py#L644 + + Originally modified from https://github.com/karpathy/minGPT/blob/master/mingpt/model.py + """ + + def __init__( + self, + in_channels, # dimension of the input features + n_head, # number of attention heads + n_ds_strides=(1, 1), # downsampling strides for q & x, k & v + n_out=None, # output dimension, if None, set to input dim + n_hidden=None, # dimension of the hidden layer in MLP + act_layer=nn.GELU, # nonlinear activation used in MLP, default GELU + attn_pdrop=0.0, # dropout rate for the attention map + proj_pdrop=0.0, # dropout rate for the projection / MLP + path_pdrop=0.0, # drop path rate + mha_win_size=-1, # > 0 to use window mha + ): + super().__init__() + assert len(n_ds_strides) == 2 + + # layer norm for order (B C T) + self.ln1 = nn.LayerNorm(in_channels) + self.ln2 = nn.LayerNorm(in_channels) + + # specify the attention module + if mha_win_size > 1: + self.attn = LocalMaskedMHCA( + in_channels, + n_head, + window_size=mha_win_size, + n_qx_stride=n_ds_strides[0], + n_kv_stride=n_ds_strides[1], + attn_pdrop=attn_pdrop, + proj_pdrop=proj_pdrop, + ) + else: + self.attn = MaskedMHCA( + in_channels, + n_head, + n_qx_stride=n_ds_strides[0], + n_kv_stride=n_ds_strides[1], + attn_pdrop=attn_pdrop, + proj_pdrop=proj_pdrop, + ) + + # input + if n_ds_strides[0] > 1: + kernel_size, stride, padding = n_ds_strides[0] + 1, n_ds_strides[0], (n_ds_strides[0] + 1) // 2 + self.pool_skip = nn.MaxPool1d(kernel_size, stride=stride, padding=padding) + else: + self.pool_skip = nn.Identity() + + # two layer mlp + if n_hidden is None: + n_hidden = 4 * in_channels # default + if n_out is None: + n_out = in_channels + # ok to use conv1d here with stride=1 + self.mlp = nn.Sequential( + nn.Conv1d(in_channels, n_hidden, 1), + act_layer(), + nn.Dropout(proj_pdrop, inplace=True), + nn.Conv1d(n_hidden, n_out, 1), + nn.Dropout(proj_pdrop, inplace=True), + ) + + # drop path + if path_pdrop > 0.0: + self.drop_path_attn = AffineDropPath(in_channels, drop_prob=path_pdrop) + self.drop_path_mlp = AffineDropPath(n_out, drop_prob=path_pdrop) + else: + self.drop_path_attn = nn.Identity() + self.drop_path_mlp = nn.Identity() + + def forward(self, x, mask): + # pre-LN transformer: https://arxiv.org/pdf/2002.04745.pdf + out, out_mask = self.attn(self.ln1(x.permute(0, 2, 1)).permute(0, 2, 1), mask) + out_mask_float = out_mask.to(out.dtype) + out = self.pool_skip(x) * out_mask_float.unsqueeze(1) + self.drop_path_attn(out) + # FFN + out = out + self.drop_path_mlp( + self.mlp(self.ln2(out.permute(0, 2, 1)).permute(0, 2, 1)) * out_mask_float.unsqueeze(1) + ) + return out, out_mask + + +@MODELS.register_module() +class MaskedMHCA(nn.Module): + """ + Multi Head Conv Attention with mask + + Add a depthwise convolution within a standard MHA + The extra conv op can be used to + (1) encode relative position information (replace position encoding); + (2) downsample the features if needed; + (3) match the feature channels + + Note: With current implementation, the downsample feature will be aligned + to every s+1 time step, where s is the downsampling stride. This allows us + to easily interpolate the corresponding positional embeddings. + + Modified from https://github.com/karpathy/minGPT/blob/master/mingpt/model.py + """ + + def __init__( + self, + n_embd, # dimension of the output features + n_head, # number of heads in multi-head self-attention + n_qx_stride=1, # downsampling stride for query and input + n_kv_stride=1, # downsampling stride for key and value + attn_pdrop=0.0, # dropout rate for the attention map + proj_pdrop=0.0, # dropout rate for projection op + ): + super().__init__() + assert n_embd % n_head == 0 + self.n_embd = n_embd + self.n_head = n_head + self.n_channels = n_embd // n_head + self.scale = 1.0 / math.sqrt(self.n_channels) + + # conv/pooling operations + assert (n_qx_stride == 1) or (n_qx_stride % 2 == 0) + assert (n_kv_stride == 1) or (n_kv_stride % 2 == 0) + self.n_qx_stride = n_qx_stride + self.n_kv_stride = n_kv_stride + + # query conv (depthwise) + kernel_size = self.n_qx_stride + 1 if self.n_qx_stride > 1 else 3 + stride, padding = self.n_kv_stride, kernel_size // 2 + self.query_conv = ConvModule( + self.n_embd, + self.n_embd, + kernel_size=kernel_size, + stride=stride, + padding=padding, + conv_cfg=dict(groups=n_embd, bias=False), + ) + self.query_norm = nn.LayerNorm(self.n_embd) + + # key, value conv (depthwise) + kernel_size = self.n_kv_stride + 1 if self.n_kv_stride > 1 else 3 + stride, padding = self.n_kv_stride, kernel_size // 2 + self.key_conv = ConvModule( + self.n_embd, + self.n_embd, + kernel_size=kernel_size, + stride=stride, + padding=padding, + conv_cfg=dict(groups=n_embd, bias=False), + ) + self.key_norm = nn.LayerNorm(self.n_embd) + + self.value_conv = ConvModule( + self.n_embd, + self.n_embd, + kernel_size=kernel_size, + stride=stride, + padding=padding, + conv_cfg=dict(groups=n_embd, bias=False), + ) + self.value_norm = nn.LayerNorm(self.n_embd) + + # key, query, value projections for all heads + # it is OK to ignore masking, as the mask will be attached on the attention + self.key = nn.Conv1d(self.n_embd, self.n_embd, 1) + self.query = nn.Conv1d(self.n_embd, self.n_embd, 1) + self.value = nn.Conv1d(self.n_embd, self.n_embd, 1) + + # regularization + self.attn_drop = nn.Dropout(attn_pdrop) + self.proj_drop = nn.Dropout(proj_pdrop) + + # output projection + self.proj = nn.Conv1d(self.n_embd, self.n_embd, 1) + + def forward(self, x, mask): + # x: batch size, feature channel, sequence length, + # mask: batch size, 1, sequence length (bool) + B, C, T = x.size() + + # query conv -> (B, nh * hs, T') + q, qx_mask = self.query_conv(x, mask) + q = self.query_norm(q.permute(0, 2, 1)).permute(0, 2, 1) + # key, value conv -> (B, nh * hs, T'') + k, kv_mask = self.key_conv(x, mask) + k = self.key_norm(k.permute(0, 2, 1)).permute(0, 2, 1) + v, _ = self.value_conv(x, mask) + v = self.value_norm(v.permute(0, 2, 1)).permute(0, 2, 1) + + # projections + q = self.query(q) + k = self.key(k) + v = self.value(v) + + # move head forward to be the batch dim + # (B, nh * hs, T'/T'') -> (B, nh, T'/T'', hs) + k = k.view(B, self.n_head, self.n_channels, -1).transpose(2, 3) + q = q.view(B, self.n_head, self.n_channels, -1).transpose(2, 3) + v = v.view(B, self.n_head, self.n_channels, -1).transpose(2, 3) + + # self-attention: (B, nh, T', hs) x (B, nh, hs, T'') -> (B, nh, T', T'') + att = (q * self.scale) @ k.transpose(-2, -1) + # prevent q from attending to invalid tokens + att = att.masked_fill(torch.logical_not(kv_mask[:, None, None, :]), float("-inf")) + # softmax attn + att = F.softmax(att, dim=-1) + att = self.attn_drop(att) + # (B, nh, T', T'') x (B, nh, T'', hs) -> (B, nh, T', hs) + out = att @ (v * kv_mask[:, None, :, None].to(v.dtype)) + # re-assemble all head outputs side by side + out = out.transpose(2, 3).contiguous().view(B, C, -1) + + # output projection + skip connection + out = self.proj_drop(self.proj(out)) * qx_mask.unsqueeze(1).to(out.dtype) + return out, qx_mask + + +@MODELS.register_module() +class LocalMaskedMHCA(nn.Module): + """ + Local Multi Head Conv Attention with mask + + Add a depthwise convolution within a standard MHA + The extra conv op can be used to + (1) encode relative position information (replace position encoding); + (2) downsample the features if needed; + (3) match the feature channels + + Note: With current implementation, the downsample feature will be aligned + to every s+1 time step, where s is the downsampling stride. This allows us + to easily interpolate the corresponding positional embeddings. + + The implementation is fairly tricky, code reference from + https://github.com/huggingface/transformers/blob/master/src/transformers/models/longformer/modeling_longformer.py + """ + + def __init__( + self, + n_embd, # dimension of the output features + n_head, # number of heads in multi-head self-attention + window_size, # size of the local attention window + n_qx_stride=1, # downsampling stride for query and input + n_kv_stride=1, # downsampling stride for key and value + attn_pdrop=0.0, # dropout rate for the attention map + proj_pdrop=0.0, # dropout rate for projection op + use_rel_pe=False, # use relative position encoding + ): + super().__init__() + assert n_embd % n_head == 0 + self.n_embd = n_embd + self.n_head = n_head + self.n_channels = n_embd // n_head + self.scale = 1.0 / math.sqrt(self.n_channels) + self.window_size = window_size + self.window_overlap = window_size // 2 + # must use an odd window size + assert self.window_size > 1 and self.n_head >= 1 + self.use_rel_pe = use_rel_pe + + # conv/pooling operations + assert (n_qx_stride == 1) or (n_qx_stride % 2 == 0) + assert (n_kv_stride == 1) or (n_kv_stride % 2 == 0) + self.n_qx_stride = n_qx_stride + self.n_kv_stride = n_kv_stride + + # query conv (depthwise) + kernel_size = self.n_qx_stride + 1 if self.n_qx_stride > 1 else 3 + stride, padding = self.n_kv_stride, kernel_size // 2 + self.query_conv = ConvModule( + self.n_embd, + self.n_embd, + kernel_size=kernel_size, + stride=stride, + padding=padding, + conv_cfg=dict(groups=n_embd, bias=False), + ) + self.query_norm = nn.LayerNorm(self.n_embd) + + # key, value conv (depthwise) + kernel_size = self.n_kv_stride + 1 if self.n_kv_stride > 1 else 3 + stride, padding = self.n_kv_stride, kernel_size // 2 + self.key_conv = ConvModule( + self.n_embd, + self.n_embd, + kernel_size=kernel_size, + stride=stride, + padding=padding, + conv_cfg=dict(groups=n_embd, bias=False), + ) + self.key_norm = nn.LayerNorm(self.n_embd) + + self.value_conv = ConvModule( + self.n_embd, + self.n_embd, + kernel_size=kernel_size, + stride=stride, + padding=padding, + conv_cfg=dict(groups=n_embd, bias=False), + ) + self.value_norm = nn.LayerNorm(self.n_embd) + + # key, query, value projections for all heads + # it is OK to ignore masking, as the mask will be attached on the attention + self.key = nn.Conv1d(self.n_embd, self.n_embd, 1) + self.query = nn.Conv1d(self.n_embd, self.n_embd, 1) + self.value = nn.Conv1d(self.n_embd, self.n_embd, 1) + + # regularization + self.attn_drop = nn.Dropout(attn_pdrop) + self.proj_drop = nn.Dropout(proj_pdrop) + + # output projection + self.proj = nn.Conv1d(self.n_embd, self.n_embd, 1) + + @staticmethod + def _chunk(x, window_overlap): + """convert into overlapping chunks. Chunk size = 2w, overlap size = w""" + # x: B x nh, T, hs + # non-overlapping chunks of size = 2w -> B x nh, T//2w, 2w, hs + x = x.view( + x.size(0), + x.size(1) // (window_overlap * 2), + window_overlap * 2, + x.size(2), + ) + + # use `as_strided` to make the chunks overlap with an overlap size = window_overlap + chunk_size = list(x.size()) + chunk_size[1] = chunk_size[1] * 2 - 1 + chunk_stride = list(x.stride()) + chunk_stride[1] = chunk_stride[1] // 2 + + # B x nh, #chunks = T//w - 1, 2w, hs + return x.as_strided(size=chunk_size, stride=chunk_stride) + + @staticmethod + def _pad_and_transpose_last_two_dims(x, padding): + """pads rows and then flips rows and columns""" + # padding value is not important because it will be overwritten + x = nn.functional.pad(x, padding) + x = x.view(*x.size()[:-2], x.size(-1), x.size(-2)) + return x + + @staticmethod + def _mask_invalid_locations(input_tensor, affected_seq_len): + beginning_mask_2d = input_tensor.new_ones(affected_seq_len, affected_seq_len + 1).tril().flip(dims=[0]) + beginning_mask = beginning_mask_2d[None, :, None, :] + ending_mask = beginning_mask.flip(dims=(1, 3)) + beginning_input = input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1] + beginning_mask = beginning_mask.expand(beginning_input.size()) + # `== 1` converts to bool or uint8 + beginning_input.masked_fill_(beginning_mask == 1, -float("inf")) + ending_input = input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :] + ending_mask = ending_mask.expand(ending_input.size()) + # `== 1` converts to bool or uint8 + ending_input.masked_fill_(ending_mask == 1, -float("inf")) + + @staticmethod + def _pad_and_diagonalize(x): + """ + shift every row 1 step right, converting columns into diagonals. + Example:: + chunked_hidden_states: [ 0.4983, 2.6918, -0.0071, 1.0492, + -1.8348, 0.7672, 0.2986, 0.0285, + -0.7584, 0.4206, -0.0405, 0.1599, + 2.0514, -1.1600, 0.5372, 0.2629 ] + window_overlap = num_rows = 4 + (pad & diagonalize) => + [ 0.4983, 2.6918, -0.0071, 1.0492, 0.0000, 0.0000, 0.0000 + 0.0000, -1.8348, 0.7672, 0.2986, 0.0285, 0.0000, 0.0000 + 0.0000, 0.0000, -0.7584, 0.4206, -0.0405, 0.1599, 0.0000 + 0.0000, 0.0000, 0.0000, 2.0514, -1.1600, 0.5372, 0.2629 ] + """ + total_num_heads, num_chunks, window_overlap, hidden_dim = x.size() + # total_num_heads x num_chunks x window_overlap x (hidden_dim+window_overlap+1). + x = nn.functional.pad(x, (0, window_overlap + 1)) + # total_num_heads x num_chunks x window_overlap*window_overlap+window_overlap + x = x.view(total_num_heads, num_chunks, -1) + # total_num_heads x num_chunks x window_overlap*window_overlap + x = x[:, :, :-window_overlap] + x = x.view(total_num_heads, num_chunks, window_overlap, window_overlap + hidden_dim) + x = x[:, :, :, :-1] + return x + + def _sliding_chunks_query_key_matmul(self, query, key, num_heads, window_overlap): + """ + Matrix multiplication of query and key tensors using with a sliding window attention pattern. This implementation splits the input into overlapping chunks of size 2w with an overlap of size w (window_overlap) + """ + # query / key: B*nh, T, hs + bnh, seq_len, head_dim = query.size() + batch_size = bnh // num_heads + assert seq_len % (window_overlap * 2) == 0 + assert query.size() == key.size() + + chunks_count = seq_len // window_overlap - 1 + + # B * num_heads, head_dim, #chunks=(T//w - 1), 2w + chunk_query = self._chunk(query, window_overlap) + chunk_key = self._chunk(key, window_overlap) + + # matrix multiplication + # bcxd: batch_size * num_heads x chunks x 2window_overlap x head_dim + # bcyd: batch_size * num_heads x chunks x 2window_overlap x head_dim + # bcxy: batch_size * num_heads x chunks x 2window_overlap x 2window_overlap + diagonal_chunked_attention_scores = torch.einsum("bcxd,bcyd->bcxy", (chunk_query, chunk_key)) + + # convert diagonals into columns + # B * num_heads, #chunks, 2w, 2w+1 + diagonal_chunked_attention_scores = self._pad_and_transpose_last_two_dims( + diagonal_chunked_attention_scores, padding=(0, 0, 0, 1) + ) + + # allocate space for the overall attention matrix where the chunks are combined. The last dimension + # has (window_overlap * 2 + 1) columns. The first (window_overlap) columns are the window_overlap lower triangles (attention from a word to + # window_overlap previous words). The following column is attention score from each word to itself, then + # followed by window_overlap columns for the upper triangle. + diagonal_attention_scores = diagonal_chunked_attention_scores.new_empty( + (batch_size * num_heads, chunks_count + 1, window_overlap, window_overlap * 2 + 1) + ) + + # copy parts from diagonal_chunked_attention_scores into the combined matrix of attentions + # - copying the main diagonal and the upper triangle + diagonal_attention_scores[:, :-1, :, window_overlap:] = diagonal_chunked_attention_scores[ + :, :, :window_overlap, : window_overlap + 1 + ] + diagonal_attention_scores[:, -1, :, window_overlap:] = diagonal_chunked_attention_scores[ + :, -1, window_overlap:, : window_overlap + 1 + ] + # - copying the lower triangle + diagonal_attention_scores[:, 1:, :, :window_overlap] = diagonal_chunked_attention_scores[ + :, :, -(window_overlap + 1) : -1, window_overlap + 1 : + ] + + diagonal_attention_scores[:, 0, 1:window_overlap, 1:window_overlap] = diagonal_chunked_attention_scores[ + :, 0, : window_overlap - 1, 1 - window_overlap : + ] + + # separate batch_size and num_heads dimensions again + diagonal_attention_scores = diagonal_attention_scores.view( + batch_size, num_heads, seq_len, 2 * window_overlap + 1 + ).transpose(2, 1) + + self._mask_invalid_locations(diagonal_attention_scores, window_overlap) + return diagonal_attention_scores + + def _sliding_chunks_matmul_attn_probs_value(self, attn_probs, value, num_heads, window_overlap): + """ + Same as _sliding_chunks_query_key_matmul but for attn_probs and value tensors. Returned tensor will be of the + same shape as `attn_probs` + """ + bnh, seq_len, head_dim = value.size() + batch_size = bnh // num_heads + assert seq_len % (window_overlap * 2) == 0 + assert attn_probs.size(3) == 2 * window_overlap + 1 + chunks_count = seq_len // window_overlap - 1 + # group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size 2 window overlap + + chunked_attn_probs = attn_probs.transpose(1, 2).reshape( + batch_size * num_heads, seq_len // window_overlap, window_overlap, 2 * window_overlap + 1 + ) + + # pad seq_len with w at the beginning of the sequence and another window overlap at the end + padded_value = nn.functional.pad(value, (0, 0, window_overlap, window_overlap), value=-1) + + # chunk padded_value into chunks of size 3 window overlap and an overlap of size window overlap + chunked_value_size = (batch_size * num_heads, chunks_count + 1, 3 * window_overlap, head_dim) + chunked_value_stride = padded_value.stride() + chunked_value_stride = ( + chunked_value_stride[0], + window_overlap * chunked_value_stride[1], + chunked_value_stride[1], + chunked_value_stride[2], + ) + chunked_value = padded_value.as_strided(size=chunked_value_size, stride=chunked_value_stride) + + chunked_attn_probs = self._pad_and_diagonalize(chunked_attn_probs) + + context = torch.einsum("bcwd,bcdh->bcwh", (chunked_attn_probs, chunked_value)) + return context.view(batch_size, num_heads, seq_len, head_dim) + + def forward(self, x, mask): + # x: batch size, feature channel, sequence length, + # mask: batch size, 1, sequence length (bool) + B, C, T = x.size() + + # step 1: depth convolutions + # query conv -> (B, nh * hs, T') + q, qx_mask = self.query_conv(x, mask) + q = self.query_norm(q.permute(0, 2, 1)).permute(0, 2, 1) + # key, value conv -> (B, nh * hs, T'') + k, kv_mask = self.key_conv(x, mask) + k = self.key_norm(k.permute(0, 2, 1)).permute(0, 2, 1) + v, _ = self.value_conv(x, mask) + v = self.value_norm(v.permute(0, 2, 1)).permute(0, 2, 1) + + # step 2: query, key, value transforms & reshape + # projections + q = self.query(q) + k = self.key(k) + v = self.value(v) + # (B, nh * hs, T) -> (B, nh, T, hs) + q = q.view(B, self.n_head, self.n_channels, -1).transpose(2, 3) + k = k.view(B, self.n_head, self.n_channels, -1).transpose(2, 3) + v = v.view(B, self.n_head, self.n_channels, -1).transpose(2, 3) + # view as (B * nh, T, hs) + q = q.view(B * self.n_head, -1, self.n_channels).contiguous() + k = k.view(B * self.n_head, -1, self.n_channels).contiguous() + v = v.view(B * self.n_head, -1, self.n_channels).contiguous() + + # step 3: compute local self-attention with rel pe and masking + q *= self.scale + # chunked query key attention -> B, T, nh, 2w+1 = window_size + att = self._sliding_chunks_query_key_matmul(q, k, self.n_head, self.window_overlap) + + # rel pe + if self.use_rel_pe: + att += self.rel_pe + # kv_mask -> B, T'', 1 + inverse_kv_mask = torch.logical_not(kv_mask[:, None, :, None].view(B, -1, 1)) + # 0 for valid slot, -inf for masked ones + float_inverse_kv_mask = inverse_kv_mask.type_as(q).masked_fill(inverse_kv_mask, -1e4) + # compute the diagonal mask (for each local window) + diagonal_mask = self._sliding_chunks_query_key_matmul( + float_inverse_kv_mask.new_ones(size=float_inverse_kv_mask.size()), + float_inverse_kv_mask, + 1, + self.window_overlap, + ) + att += diagonal_mask + + # ignore input masking for now + att = nn.functional.softmax(att, dim=-1) + # softmax sometimes inserts NaN if all positions are masked, replace them with 0 + att = att.masked_fill(torch.logical_not(kv_mask[:, :, None, None]), 0.0) + att = self.attn_drop(att) + + # step 4: compute attention value product + output projection + # chunked attn value product -> B, nh, T, hs + out = self._sliding_chunks_matmul_attn_probs_value(att, v, self.n_head, self.window_overlap) + # transpose to B, nh, hs, T -> B, nh*hs, T + out = out.transpose(2, 3).contiguous().view(B, C, -1) + # output projection + skip connection + out = self.proj_drop(self.proj(out)) * qx_mask.unsqueeze(1).to(out.dtype) + return out, qx_mask + + +# The follow code is modified from +# https://github.com/facebookresearch/SlowFast/blob/master/slowfast/models/common.py +def drop_path(x, drop_prob=0.0, training=False): + """ + Stochastic Depth per sample. + """ + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets + mask = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) + mask.floor_() # binarize + output = x.div(keep_prob) * mask + return output + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) + + +class AffineDropPath(nn.Module): + """ + Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks) with a per channel scaling factor (and zero init) + See: https://arxiv.org/pdf/2103.17239.pdf + """ + + def __init__(self, num_dim, drop_prob=0.0, init_scale_value=1e-4): + super().__init__() + self.scale = nn.Parameter(init_scale_value * torch.ones((1, num_dim, 1)), requires_grad=True) + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(self.scale * x, self.drop_prob, self.training) diff --git a/OpenTAD/opentad/models/builder.py b/OpenTAD/opentad/models/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..4d32ccf0d577abec3a0e0944060fc1292677acd0 --- /dev/null +++ b/OpenTAD/opentad/models/builder.py @@ -0,0 +1,70 @@ +from mmengine.registry import Registry +from .backbones import BackboneWrapper + +MODELS = Registry("models") + +PROJECTIONS = MODELS +NECKS = MODELS +ROI_EXTRACTORS = MODELS +PRIOR_GENERATORS = MODELS +PROPOSAL_GENERATORS = MODELS +HEADS = MODELS +TRANSFORMERS = MODELS +LOSSES = MODELS +DETECTORS = MODELS +MATCHERS = MODELS + + +def build_detector(cfg): + """Build detector.""" + return DETECTORS.build(cfg) + + +def build_backbone(cfg): + """Build backbone.""" + return BackboneWrapper(cfg) + + +def build_projection(cfg): + """Build projection.""" + return PROJECTIONS.build(cfg) + + +def build_neck(cfg): + """Build neck.""" + return NECKS.build(cfg) + + +def build_prior_generator(cfg): + """Build prior generator.""" + return PRIOR_GENERATORS.build(cfg) + + +def build_proposal_generator(cfg): + """Build proposal generator.""" + return PROPOSAL_GENERATORS.build(cfg) + + +def build_roi_extractor(cfg): + """Build roi extractor.""" + return ROI_EXTRACTORS.build(cfg) + + +def build_transformer(cfg): + """Build transformer in DETR-like model.""" + return TRANSFORMERS.build(cfg) + + +def build_head(cfg): + """Build head.""" + return HEADS.build(cfg) + + +def build_matcher(cfg): + """Build external classifier.""" + return MATCHERS.build(cfg) + + +def build_loss(cfg): + """Build loss.""" + return LOSSES.build(cfg) diff --git a/OpenTAD/opentad/models/dense_heads/__init__.py b/OpenTAD/opentad/models/dense_heads/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..695e01a561d101021a283160354bb973b4a13412 --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/__init__.py @@ -0,0 +1,26 @@ +from .prior_generator import AnchorGenerator, PointGenerator +from .anchor_head import AnchorHead +from .anchor_free_head import AnchorFreeHead +from .rpn_head import RPNHead +from .afsd_coarse_head import AFSDCoarseHead +from .actionformer_head import ActionFormerHead +from .tridet_head import TriDetHead +from .temporalmaxer_head import TemporalMaxerHead +from .tem_head import TemporalEvaluationHead, GCNextTemporalEvaluationHead, LocalGlobalTemporalEvaluationHead +from .vsgn_rpn_head import VSGNRPNHead + +__all__ = [ + "AnchorGenerator", + "PointGenerator", + "AnchorHead", + "AnchorFreeHead", + "RPNHead", + "AFSDCoarseHead", + "ActionFormerHead", + "TriDetHead", + "TemporalMaxerHead", + "TemporalEvaluationHead", + "GCNextTemporalEvaluationHead", + "LocalGlobalTemporalEvaluationHead", + "VSGNRPNHead", +] diff --git a/OpenTAD/opentad/models/dense_heads/actionformer_head.py b/OpenTAD/opentad/models/dense_heads/actionformer_head.py new file mode 100644 index 0000000000000000000000000000000000000000..42e78b261686801097592d53d63fc3c4ca0f8d89 --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/actionformer_head.py @@ -0,0 +1,39 @@ +from ..builder import HEADS +from .anchor_free_head import AnchorFreeHead + + +@HEADS.register_module() +class ActionFormerHead(AnchorFreeHead): + def __init__( + self, + num_classes, + in_channels, + feat_channels, + num_convs=3, + prior_generator=None, + loss=None, + loss_normalizer=100, + loss_normalizer_momentum=0.9, + center_sample="radius", + center_sample_radius=1.5, + label_smoothing=0, + cls_prior_prob=0.01, + loss_weight=1.0, + **kwargs, + ): + super().__init__( + num_classes, + in_channels, + feat_channels, + num_convs=num_convs, + cls_prior_prob=cls_prior_prob, + prior_generator=prior_generator, + loss=loss, + loss_normalizer=loss_normalizer, + loss_normalizer_momentum=loss_normalizer_momentum, + loss_weight=loss_weight, + label_smoothing=label_smoothing, + center_sample=center_sample, + center_sample_radius=center_sample_radius, + **kwargs, + ) diff --git a/OpenTAD/opentad/models/dense_heads/afsd_coarse_head.py b/OpenTAD/opentad/models/dense_heads/afsd_coarse_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e81d999b24d00f4e5754e3203f3f9c0b3dc4946e --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/afsd_coarse_head.py @@ -0,0 +1,187 @@ +import torch +import torch.nn as nn + +from ..builder import HEADS +from ..necks.afsd_neck import Unit1D + + +@HEADS.register_module() +class AFSDCoarseHead(nn.Module): + def __init__( + self, + in_channels, + out_channels, + frame_num, + fpn_strides=[4, 8, 16, 32, 64, 128], + num_classes=2, + layer_num=6, + feat_t=768 // 8, + ): + super().__init__() + + self.frame_num = frame_num + self.fpn_strides = fpn_strides + self.num_classes = num_classes + + loc_towers = [] + for i in range(2): + loc_towers.append( + nn.Sequential( + Unit1D( + in_channels=in_channels, + output_channels=out_channels, + kernel_shape=3, + stride=1, + use_bias=True, + activation_fn=None, + ), + nn.GroupNorm(32, out_channels), + nn.ReLU(inplace=True), + ) + ) + self.loc_tower = nn.Sequential(*loc_towers) + + conf_towers = [] + for i in range(2): + conf_towers.append( + nn.Sequential( + Unit1D( + in_channels=in_channels, + output_channels=out_channels, + kernel_shape=3, + stride=1, + use_bias=True, + activation_fn=None, + ), + nn.GroupNorm(32, out_channels), + nn.ReLU(inplace=True), + ) + ) + self.conf_tower = nn.Sequential(*conf_towers) + + # anchor priors + self.priors = [ + torch.Tensor([[(c + 0.5) / (feat_t // 2**i), i] for c in range(feat_t // 2**i)]).view(-1, 2) + for i in range(layer_num) + ] + + # regression head + self.loc_head = Unit1D( + in_channels=out_channels, + output_channels=2, + kernel_shape=3, + stride=1, + use_bias=True, + activation_fn=None, + ) + self.scales = nn.ModuleList([ScaleExp() for _ in range(layer_num)]) + + # classification head + self.conf_head = Unit1D( + in_channels=out_channels, + output_channels=num_classes, + kernel_shape=3, + stride=1, + use_bias=True, + activation_fn=None, + ) + + # init weights + self.init_weights() + + def init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv1d): + nn.init.normal_(m.weight, mean=0, std=0.01) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.GroupNorm): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + @torch.no_grad() + def generate_segments(self, loc, level): + t = loc.shape[1] + segments = loc / self.frame_num * t + priors = self.priors[level][:, :1].expand(loc.size(0), t, 1).to(loc.device) + new_priors = torch.round(priors * t - 0.5) + plen = segments[:, :, :1] + segments[:, :, 1:] + in_plen = torch.clamp(plen / 4.0, min=1.0) + out_plen = torch.clamp(plen / 10.0, min=1.0) + + l_segment = new_priors - segments[:, :, :1] + r_segment = new_priors + segments[:, :, 1:] + segments = torch.cat( + [ + torch.round(l_segment - out_plen), + torch.round(l_segment + in_plen), + torch.round(r_segment - in_plen), + torch.round(r_segment + out_plen), + ], + dim=-1, + ) # [B, T, 4], (0~T) + + decoded_segments = torch.cat( + [ + priors[:, :, :1] * self.frame_num - loc[:, :, :1], + priors[:, :, :1] * self.frame_num + loc[:, :, 1:], + ], + dim=-1, + ) + plen = decoded_segments[:, :, 1:] - decoded_segments[:, :, :1] + 1.0 + in_plen = torch.clamp(plen / 4.0, min=1.0) + out_plen = torch.clamp(plen / 10.0, min=1.0) + frame_segments = torch.cat( + [ + torch.round(decoded_segments[:, :, :1] - out_plen), + torch.round(decoded_segments[:, :, :1] + in_plen), + torch.round(decoded_segments[:, :, 1:] - in_plen), + torch.round(decoded_segments[:, :, 1:] + out_plen), + ], + dim=-1, + ) # [B, T, 4], (0~frame_num) + return segments, frame_segments + + def forward_train(self, pyramid_feats, **kwargs): + locs, confs = [], [] + loc_feat_list, conf_feat_list = [], [] + segments_list, frame_segments_list = [], [] + + batch_num = pyramid_feats[0].size(0) + for i, feat in enumerate(pyramid_feats): + loc_feat = self.loc_tower(feat) # [B,C,T] + conf_feat = self.conf_tower(feat) # [B,C,T] + loc_feat_list.append(loc_feat) + conf_feat_list.append(conf_feat) + + # regression head + loc = self.scales[i](self.loc_head(loc_feat)).view(batch_num, 2, -1) + loc = loc.permute(0, 2, 1).contiguous() * self.fpn_strides[i] # [B,T,2] + locs.append(loc) + + # classification head + conf = self.conf_head(conf_feat).view(batch_num, self.num_classes, -1) + conf = conf.permute(0, 2, 1).contiguous() # [B,T,num_classes] + confs.append(conf) + + # generate segments + segments, frame_segments = self.generate_segments(loc, i) + segments_list.append(segments) + frame_segments_list.append(frame_segments) + + # compute the loss in the afsd.py, not here + loc = torch.cat([o.view(batch_num, -1, 2) for o in locs], 1) # [B,K,2] + conf = torch.cat([o.view(batch_num, -1, self.num_classes) for o in confs], 1) # [B,K,num_class] + priors = torch.cat(self.priors, 0).to(loc.device).unsqueeze(0) # [1,K,2] + return loc, conf, priors[0], loc_feat_list, conf_feat_list, segments_list, frame_segments_list + + def forward_test(self, pyramid_feats, **kwargs): + return self.forward_train(pyramid_feats, **kwargs) + + +class ScaleExp(nn.Module): + def __init__(self, init_value=1.0): + super(ScaleExp, self).__init__() + self.scale = nn.Parameter(torch.FloatTensor([init_value])) + + def forward(self, input): + return torch.exp(input * self.scale) diff --git a/OpenTAD/opentad/models/dense_heads/anchor_free_head.py b/OpenTAD/opentad/models/dense_heads/anchor_free_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9c12a049da8b107604e44ffe0dd9d042528352 --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/anchor_free_head.py @@ -0,0 +1,298 @@ +import math +import torch +import torch.nn as nn +from torch.nn import functional as F + +from ..builder import HEADS, build_prior_generator, build_loss +from ..bricks import ConvModule, Scale + + +@HEADS.register_module() +class AnchorFreeHead(nn.Module): + def __init__( + self, + num_classes, + in_channels, + feat_channels, + num_convs=3, + prior_generator=None, + loss=None, + loss_normalizer=100, + loss_normalizer_momentum=0.9, + center_sample="radius", + center_sample_radius=1.5, + label_smoothing=0, + cls_prior_prob=0.01, + loss_weight=1.0, + filter_similar_gt=True, + ): + super(AnchorFreeHead, self).__init__() + + self.num_classes = num_classes + self.in_channels = in_channels + self.feat_channels = feat_channels + self.num_convs = num_convs + self.cls_prior_prob = cls_prior_prob + self.label_smoothing = label_smoothing + self.filter_similar_gt = filter_similar_gt + + self.loss_weight = loss_weight + self.center_sample = center_sample + self.center_sample_radius = center_sample_radius + self.loss_normalizer_momentum = loss_normalizer_momentum + self.register_buffer("loss_normalizer", torch.tensor(loss_normalizer)) # save in the state_dict + + # point generator + self.prior_generator = build_prior_generator(prior_generator) + + self._init_layers() + + self.cls_loss = build_loss(loss.cls_loss) + self.reg_loss = build_loss(loss.reg_loss) + + def _init_layers(self): + """Initialize layers of the head.""" + self._init_cls_convs() + self._init_reg_convs() + self._init_heads() + + def _init_cls_convs(self): + """Initialize classification conv layers of the head.""" + self.cls_convs = nn.ModuleList([]) + for i in range(self.num_convs): + self.cls_convs.append( + ConvModule( + self.in_channels if i == 0 else self.feat_channels, + self.feat_channels, + kernel_size=3, + stride=1, + padding=1, + norm_cfg=dict(type="LN"), + act_cfg=dict(type="relu"), + ) + ) + + def _init_reg_convs(self): + """Initialize bbox regression conv layers of the head.""" + self.reg_convs = nn.ModuleList([]) + for i in range(self.num_convs): + self.reg_convs.append( + ConvModule( + self.in_channels if i == 0 else self.feat_channels, + self.feat_channels, + kernel_size=3, + stride=1, + padding=1, + norm_cfg=dict(type="LN"), + act_cfg=dict(type="relu"), + ) + ) + + def _init_heads(self): + """Initialize predictor layers of the head.""" + self.cls_head = nn.Conv1d(self.feat_channels, self.num_classes, kernel_size=3, padding=1) + self.reg_head = nn.Conv1d(self.feat_channels, 2, kernel_size=3, padding=1) + self.scale = nn.ModuleList([Scale() for _ in range(len(self.prior_generator.strides))]) + + # use prior in model initialization to improve stability + # this will overwrite other weight init + if self.cls_prior_prob > 0: + bias_value = -(math.log((1 - self.cls_prior_prob) / self.cls_prior_prob)) + nn.init.constant_(self.cls_head.bias, bias_value) + + def forward_train(self, feat_list, mask_list, gt_segments, gt_labels, **kwargs): + cls_pred = [] + reg_pred = [] + + for l, (feat, mask) in enumerate(zip(feat_list, mask_list)): + cls_feat = feat + reg_feat = feat + + for i in range(self.num_convs): + cls_feat, mask = self.cls_convs[i](cls_feat, mask) + reg_feat, mask = self.reg_convs[i](reg_feat, mask) + + cls_pred.append(self.cls_head(cls_feat)) + reg_pred.append(F.relu(self.scale[l](self.reg_head(reg_feat)))) + + points = self.prior_generator(feat_list) + + losses = self.losses(cls_pred, reg_pred, mask_list, points, gt_segments, gt_labels) + return losses + + def forward_test(self, feat_list, mask_list, **kwargs): + cls_pred = [] + reg_pred = [] + + for l, (feat, mask) in enumerate(zip(feat_list, mask_list)): + cls_feat = feat + reg_feat = feat + + for i in range(self.num_convs): + cls_feat, mask = self.cls_convs[i](cls_feat, mask) + reg_feat, mask = self.reg_convs[i](reg_feat, mask) + + cls_pred.append(self.cls_head(cls_feat)) + reg_pred.append(F.relu(self.scale[l](self.reg_head(reg_feat)))) + + points = self.prior_generator(feat_list) + + # get refined proposals and scores + proposals, scores = self.get_valid_proposals_scores(points, reg_pred, cls_pred, mask_list) # list [T,2] + return proposals, scores + + def get_refined_proposals(self, points, reg_pred): + points = torch.cat(points, dim=0) # [T,4] + reg_pred = torch.cat(reg_pred, dim=-1).permute(0, 2, 1) # [B,T,2] + + start = points[:, 0][None] - reg_pred[:, :, 0] * points[:, 3][None] + end = points[:, 0][None] + reg_pred[:, :, 1] * points[:, 3][None] + proposals = torch.stack((start, end), dim=-1) # [B,T,2] + return proposals + + def get_valid_proposals_scores(self, points, reg_pred, cls_pred, mask_list): + # apply regression to get refined proposals + proposals = self.get_refined_proposals(points, reg_pred) # [B,T,2] + # proposal scores + scores = torch.cat(cls_pred, dim=-1).permute(0, 2, 1).sigmoid() # [B,T,num_classes] + + # mask out invalid, and return a list with batch size + masks = torch.cat(mask_list, dim=1) # [B,T] + new_proposals, new_scores = [], [] + for proposal, score, mask in zip(proposals, scores, masks): + new_proposals.append(proposal[mask]) # [T,2] + new_scores.append(score[mask]) # [T,num_classes] + return new_proposals, new_scores + + def losses(self, cls_pred, reg_pred, mask_list, points, gt_segments, gt_labels): + gt_cls, gt_reg = self.prepare_targets(points, gt_segments, gt_labels) + + # positive mask + gt_cls = torch.stack(gt_cls) + valid_mask = torch.cat(mask_list, dim=1) + pos_mask = torch.logical_and((gt_cls.sum(-1) > 0), valid_mask) + num_pos = pos_mask.sum().item() + + # maintain an EMA of foreground to stabilize the loss normalizer + # useful for small mini-batch training + if self.training: + self.loss_normalizer = self.loss_normalizer_momentum * self.loss_normalizer + ( + 1 - self.loss_normalizer_momentum + ) * max(num_pos, 1) + loss_normalizer = self.loss_normalizer + else: + loss_normalizer = max(num_pos, 1) + + # 1. classification loss + cls_pred = [x.permute(0, 2, 1) for x in cls_pred] + cls_pred = torch.cat(cls_pred, dim=1)[valid_mask] + gt_target = gt_cls[valid_mask] + + # optional label smoothing + gt_target *= 1 - self.label_smoothing + gt_target += self.label_smoothing / (self.num_classes + 1) + + cls_loss = self.cls_loss(cls_pred, gt_target, reduction="sum") + cls_loss /= loss_normalizer + + # 2. regression using IoU/GIoU/DIOU loss (defined on positive samples) + split_size = [reg.shape[-1] for reg in reg_pred] + gt_reg = torch.stack(gt_reg).permute(0, 2, 1).split(split_size, dim=-1) # [B,2,T] + pred_segments = self.get_refined_proposals(points, reg_pred)[pos_mask] + gt_segments = self.get_refined_proposals(points, gt_reg)[pos_mask] + if num_pos == 0: + reg_loss = pred_segments.sum() * 0 + else: + # giou loss defined on positive samples + reg_loss = self.reg_loss(pred_segments, gt_segments, reduction="sum") + reg_loss /= loss_normalizer + + if self.loss_weight > 0: + loss_weight = self.loss_weight + else: + loss_weight = cls_loss.detach() / max(reg_loss.item(), 0.01) + + return {"cls_loss": cls_loss, "reg_loss": reg_loss * loss_weight} + + @torch.no_grad() + def prepare_targets(self, points, gt_segments, gt_labels): + concat_points = torch.cat(points, dim=0) + num_pts = concat_points.shape[0] + gt_cls, gt_reg = [], [] + + for gt_segment, gt_label in zip(gt_segments, gt_labels): + num_gts = gt_segment.shape[0] + + # corner case where current sample does not have actions + if num_gts == 0: + gt_cls.append(gt_segment.new_full((num_pts, self.num_classes), 0)) + gt_reg.append(gt_segment.new_zeros((num_pts, 2))) + continue + + # compute the lengths of all segments -> F T x N + lens = gt_segment[:, 1] - gt_segment[:, 0] + lens = lens[None, :].repeat(num_pts, 1) + + # compute the distance of every point to each segment boundary + # auto broadcasting for all reg target-> F T x N x2 + gt_segs = gt_segment[None].expand(num_pts, num_gts, 2) + left = concat_points[:, 0, None] - gt_segs[:, :, 0] + right = gt_segs[:, :, 1] - concat_points[:, 0, None] + reg_targets = torch.stack((left, right), dim=-1) + + if self.center_sample == "radius": + # center of all segments F T x N + center_pts = 0.5 * (gt_segs[:, :, 0] + gt_segs[:, :, 1]) + # center sampling based on stride radius + # compute the new boundaries: + # concat_points[:, 3] stores the stride + t_mins = center_pts - concat_points[:, 3, None] * self.center_sample_radius + t_maxs = center_pts + concat_points[:, 3, None] * self.center_sample_radius + # prevent t_mins / maxs from over-running the action boundary + # left: torch.maximum(t_mins, gt_segs[:, :, 0]) + # right: torch.minimum(t_maxs, gt_segs[:, :, 1]) + # F T x N (distance to the new boundary) + cb_dist_left = concat_points[:, 0, None] - torch.maximum(t_mins, gt_segs[:, :, 0]) + cb_dist_right = torch.minimum(t_maxs, gt_segs[:, :, 1]) - concat_points[:, 0, None] + # F T x N x 2 + center_seg = torch.stack((cb_dist_left, cb_dist_right), -1) + # F T x N + inside_gt_seg_mask = center_seg.min(-1)[0] > 0 + else: + # inside an gt action + inside_gt_seg_mask = reg_targets.min(-1)[0] > 0 + + # limit the regression range for each location + max_regress_distance = reg_targets.max(-1)[0] + # F T x N + inside_regress_range = torch.logical_and( + (max_regress_distance >= concat_points[:, 1, None]), (max_regress_distance <= concat_points[:, 2, None]) + ) + + # if there are still more than one actions for one moment + # pick the one with the shortest duration (easiest to regress) + lens.masked_fill_(inside_gt_seg_mask == 0, float("inf")) + lens.masked_fill_(inside_regress_range == 0, float("inf")) + # F T x N -> F T + min_len, min_len_inds = lens.min(dim=1) + + # corner case: multiple actions with very similar durations (e.g., THUMOS14) + if self.filter_similar_gt: + min_len_mask = torch.logical_and((lens <= (min_len[:, None] + 1e-3)), (lens < float("inf"))) + else: + min_len_mask = lens < float("inf") + min_len_mask = min_len_mask.to(reg_targets.dtype) + + # cls_targets: F T x C; reg_targets F T x 2 + gt_label_one_hot = F.one_hot(gt_label.long(), self.num_classes).to(reg_targets.dtype) + cls_targets = min_len_mask @ gt_label_one_hot + # to prevent multiple GT actions with the same label and boundaries + cls_targets.clamp_(min=0.0, max=1.0) + # OK to use min_len_inds + reg_targets = reg_targets[range(num_pts), min_len_inds] + # normalization based on stride + reg_targets /= concat_points[:, 3, None] + + gt_cls.append(cls_targets) + gt_reg.append(reg_targets) + return gt_cls, gt_reg diff --git a/OpenTAD/opentad/models/dense_heads/anchor_head.py b/OpenTAD/opentad/models/dense_heads/anchor_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa496c2c79e64455ac37b41da71fbbcb919ff0f --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/anchor_head.py @@ -0,0 +1,255 @@ +import math +import torch +import torch.nn as nn +from ..builder import HEADS, build_prior_generator, build_loss +from ..bricks import ConvModule +from ..utils.bbox_tools import compute_delta, delta_to_pred +from ..utils.post_processing import batched_nms + + +@HEADS.register_module() +class AnchorHead(nn.Module): + def __init__( + self, + num_classes, + in_channels, + feat_channels, + num_convs=3, + prior_generator=None, + loss=None, + cls_prior_prob=0.01, + ): + super(AnchorHead, self).__init__() + + self.num_classes = num_classes + self.in_channels = in_channels + self.feat_channels = feat_channels + self.num_convs = num_convs + self.cls_prior_prob = cls_prior_prob + + self.scales = prior_generator.scales + self.strides = prior_generator.strides + + # anchor generator + self.prior_generator = build_prior_generator(prior_generator) + + # build layers + self._init_layers() + + # loss + self.assigner = build_loss(loss.assigner) + self.sampler = build_loss(loss.sampler) + self.cls_loss = build_loss(loss.cls_loss) + self.reg_loss = build_loss(loss.reg_loss) + + def _init_layers(self): + self.rpn_convs = nn.ModuleList([]) + for i in range(self.num_convs): + self.rpn_convs.append( + ConvModule( + self.in_channels if i == 0 else self.feat_channels, + self.feat_channels, + kernel_size=3, + padding=1, + act_cfg=dict(type="relu"), + ) + ) + + # regression + self.rpn_reg = nn.Conv1d(self.feat_channels, len(self.scales) * 2, kernel_size=1) + + # classification (no sigmoid in layers) + self.rpn_cls = nn.Conv1d(self.feat_channels, len(self.scales) * 1, kernel_size=1) + + # use prior in model initialization to improve stability + # this will overwrite other weight init + if self.cls_prior_prob > 0: + bias_value = -(math.log((1 - self.cls_prior_prob) / self.cls_prior_prob)) + torch.nn.init.constant_(self.rpn_cls.bias, bias_value) + + def forward_train(self, feat_list, mask_list, gt_segments, gt_labels, **kwargs): + cls_pred = [] + reg_pred = [] + + for feat, mask in zip(feat_list, mask_list): + for i in range(self.num_convs): + feat, mask = self.rpn_convs[i](feat, mask) + + cls_pred.append(self.rpn_cls(feat) * mask.unsqueeze(1).float()) # todo + reg_pred.append(self.rpn_reg(feat) * mask.unsqueeze(1).float()) # todo + + anchors = self.prior_generator(feat_list) # List: [k,2] 0~1 + + # loss + losses = self.losses(cls_pred, reg_pred, mask_list, anchors, gt_segments, gt_labels) + + # get proposals + proposals, _ = self._get_nms_proposal_list(anchors, mask_list, cls_pred, reg_pred) + return losses, proposals + + def forward_test(self, feat_list, mask_list): + cls_pred = [] + reg_pred = [] + + for feat, mask in zip(feat_list, mask_list): + for i in range(self.num_convs): + feat, mask = self.rpn_convs[i](feat, mask) + + cls_pred.append(self.rpn_cls(feat) * mask.unsqueeze(1).float()) + reg_pred.append(self.rpn_reg(feat) * mask.unsqueeze(1).float()) + + anchors = self.prior_generator(feat_list) # List: [k,2] 0~1 + + # get proposals + proposals, scores = self._get_nms_proposal_list(anchors, mask_list, cls_pred, reg_pred) + return proposals, scores + + def losses(self, cls_pred, reg_pred, mask_list, anchors, gt_segments, gt_labels): + bs, num_scales = cls_pred[0].shape[:2] + + cls_pred = torch.cat(cls_pred, dim=-1).permute(0, 2, 1).reshape(bs, -1) # [B,K] + reg_pred = torch.cat(reg_pred, dim=-1).permute(0, 2, 1).reshape(bs, -1, 2) # [B,K,2] + masks = torch.cat(mask_list, dim=-1).unsqueeze(-1).repeat(1, 1, num_scales).reshape(bs, -1) # [B,K] + + # get gt targets and positive negative mask + gt_cls, gt_reg, pos_idxs_list, neg_idxs_list = self.prepare_targets(anchors, masks, gt_segments, gt_labels) + + num_pos = sum([len(pos_idxs) for pos_idxs in pos_idxs_list]) + num_neg = sum([len(neg_idxs) for neg_idxs in neg_idxs_list]) + + # classification loss + sampled_cls_pred = [] + for pred, mask, pos_idxs, neg_idxs in zip(cls_pred, masks, pos_idxs_list, neg_idxs_list): + sampled_cls_pred.append(pred[mask][pos_idxs + neg_idxs]) + sampled_cls_pred = torch.cat(sampled_cls_pred, dim=0) + + loss_cls = self.cls_loss(sampled_cls_pred, gt_cls.float()) + loss_cls /= num_pos + num_neg + + # regression loss + sampled_reg_pred = [] + for pred, mask, pos_idxs in zip(reg_pred, masks, pos_idxs_list): + sampled_reg_pred.append(pred[mask][pos_idxs]) + sampled_reg_pred = torch.cat(sampled_reg_pred, dim=0) + + if num_pos == 0: # not have positive sample + # do not have positive samples in regression loss + loss_reg = torch.Tensor([0]).sum().to(reg_pred.device) + else: + loss_reg = self.reg_loss(sampled_reg_pred, gt_reg) + loss_reg /= num_pos + + losses = {"rpn_cls": loss_cls, "rpn_reg": loss_reg} + return losses + + @torch.no_grad() + def prepare_targets(self, anchors, masks, gt_segments, gt_labels): + # prepare gts: assign the gt_segment to each anchor + anchors = torch.cat(anchors, dim=0) # [B,K,2] + + gt_cls_list, gt_reg_list, pos_idxs_list, neg_idxs_list = [], [], [], [] + for i, (gt_segment, gt_label) in enumerate(zip(gt_segments, gt_labels)): + if len(gt_segment) == 0: # make a pseudo gt_segment + gt_segment = torch.tensor([[0, 0]], dtype=torch.float32, device=anchors.device) + gt_label = torch.zeros(self.num_classes, device=anchors.device).to(torch.int64) + else: + gt_label = torch.ones((gt_segment.shape[0], 1), device=anchors.device).to(torch.int64) # binary label + + # assign GT for valid positions + _, assigned_gt_idxs, assigned_labels = self.assigner.assign( + anchors[masks[i]], + gt_segment, + gt_label, + ) + + # sample positive and negative anchors + pos_idxs, neg_idxs = self.sampler.sample(assigned_gt_idxs) + pos_idxs_list.append(pos_idxs) + neg_idxs_list.append(neg_idxs) + + # classification target: pos_mask + neg_mask + gt_cls = assigned_labels[pos_idxs + neg_idxs].squeeze(-1) + gt_cls_list.append(gt_cls) + + # regression target: pos_mask + gt_reg = compute_delta(anchors[masks[i]][pos_idxs], gt_segment[assigned_gt_idxs[pos_idxs] - 1]) + gt_reg_list.append(gt_reg) + + gt_cls_concat = torch.cat(gt_cls_list, dim=0) # [B*(pos+neg)] + gt_reg_concat = torch.cat(gt_reg_list, dim=0) # [B*(pos),2] + return gt_cls_concat, gt_reg_concat, pos_idxs_list, neg_idxs_list + + @torch.no_grad() + def _get_nms_proposal_list(self, anchors, mask_list, cls_pred, reg_pred): + bs = cls_pred[0].shape[0] + device = cls_pred[0].device + pre_nms_topk = 2000 + post_nms_topk = 1000 + nms_thresh = 0.7 + + # for each feature map, apply delta_to_pred() and select top-k anchors before nms + topk_proposals, topk_scores, topk_masks, level_ids = [], [], [], [] + batch_idx = torch.arange(bs, device=device) + for l, (anchor_i, logits_i, reg_i, mask_i) in enumerate(zip(anchors, cls_pred, reg_pred, mask_list)): + # 1. get valid anchors + mask_i = mask_i.unsqueeze(-1).repeat(1, 1, len(self.scales)).flatten(1) # [bs,T*len(scales)] + + # 2. apply delta_to_pred() to get proposals + reg_i = reg_i.permute(0, 2, 1).reshape(bs, -1, 2) + scores_i = logits_i.permute(0, 2, 1).reshape(bs, -1).sigmoid() # [bs, T*len(scales)] + proposals_i = delta_to_pred(anchor_i, reg_i) # [bs, T*len(scales), 2] + + # 3. select top-k anchor for each level and each video + num_proposals_i = min(proposals_i.shape[1], pre_nms_topk) + topk_scores_i, topk_idx = scores_i.topk(num_proposals_i, dim=1) + topk_proposals_i = proposals_i[batch_idx[:, None], topk_idx] # [bs,topk,2] + topk_masks_i = mask_i[batch_idx[:, None], topk_idx] # [bs,topk] + + topk_proposals.append(topk_proposals_i) + topk_scores.append(topk_scores_i) + topk_masks.append(topk_masks_i) + level_ids.append(torch.full((num_proposals_i,), l, dtype=torch.int64, device=device)) + + # concat all levels together + topk_proposals = torch.cat(topk_proposals, dim=1) + topk_scores = torch.cat(topk_scores, dim=1) + topk_masks = torch.cat(topk_masks, dim=1) + level_ids = torch.cat(level_ids, dim=0) # we have recorded the level id + + # NMS on each level, and choose topk results. + nms_proposals, nms_scores = [], [] + for i in range(bs): + # select valid proposals + valid = topk_masks[i] + + # NMS on each feature map + new_proposals, new_scores, _ = batched_nms( + topk_proposals[i][valid], + topk_scores[i][valid], + level_ids[valid], + iou_threshold=nms_thresh, + max_seg_num=post_nms_topk, + use_soft_nms=False, + multiclass=True, + ) + + nms_proposals.append(new_proposals.to(device)) + nms_scores.append(new_scores.to(device)) + return nms_proposals, nms_scores + + # @torch.no_grad() + def _get_proposal_list(self, anchors, mask_list, cls_pred, reg_pred): + bs = cls_pred[0].shape[0] + + reg_pred = torch.cat(reg_pred, dim=-1).permute(0, 2, 1).reshape(bs, -1, 2) # [B,T*len(scales),2] + cls_pred = torch.cat(cls_pred, dim=-1).permute(0, 2, 1).reshape(bs, -1) # [B,T*len(scales)] + + anchors = torch.cat(anchors, dim=0).unsqueeze(0) # [1,T*len(scales),2] + proposals = delta_to_pred(anchors, reg_pred.detach()) # [B,K,2] + masks = torch.cat(mask_list, dim=1).unsqueeze(-1).repeat(1, 1, len(self.scales)) # [B,T,len(scales)] + + new_proposals, new_scores = [], [] + for proposal, logits, mask in zip(proposals, cls_pred, masks): + new_proposals.append(proposal[mask.view(-1)]) + new_scores.append(logits[mask.view(-1)].detach().sigmoid()) + return new_proposals, new_scores diff --git a/OpenTAD/opentad/models/dense_heads/prior_generator/__init__.py b/OpenTAD/opentad/models/dense_heads/prior_generator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb772d68cd6d3c35ed66ffb1aaf9c0b2ddd1baa --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/prior_generator/__init__.py @@ -0,0 +1,4 @@ +from .anchor_generator import AnchorGenerator +from .point_generator import PointGenerator + +__all__ = ["AnchorGenerator", "PointGenerator"] diff --git a/OpenTAD/opentad/models/dense_heads/prior_generator/anchor_generator.py b/OpenTAD/opentad/models/dense_heads/prior_generator/anchor_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..02e2b4e43f51782f8916d990d2e1947bd8c06119 --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/prior_generator/anchor_generator.py @@ -0,0 +1,26 @@ +import torch +from ...builder import PRIOR_GENERATORS + + +@PRIOR_GENERATORS.register_module() +class AnchorGenerator: + def __init__(self, scales=[1, 2, 4], strides=[1, 2, 4]): + super(AnchorGenerator, self).__init__() + + scales = torch.Tensor(scales) + self.base_anchors = torch.stack([-0.5 * scales, 0.5 * scales], dim=-1) + self.strides = strides + + def __call__(self, feat_list): + assert len(feat_list) == len(self.strides) + + multi_level_anchors = [] + for stride, feat in zip(self.strides, feat_list): + length = feat.shape[-1] + shift_center = torch.arange(0, length) + all_anchors = self.base_anchors[None, :, :] + shift_center[:, None, None] + all_anchors = all_anchors.view(-1, 2) * stride + + # all_anchors [T*num_anchors, 2] + multi_level_anchors.append(all_anchors.to(feat.dtype).to(feat.device)) + return multi_level_anchors diff --git a/OpenTAD/opentad/models/dense_heads/prior_generator/point_generator.py b/OpenTAD/opentad/models/dense_heads/prior_generator/point_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..d130564b6065339549ed910471de4020082c8968 --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/prior_generator/point_generator.py @@ -0,0 +1,36 @@ +import torch +from ...builder import PRIOR_GENERATORS + + +@PRIOR_GENERATORS.register_module() +class PointGenerator: + def __init__( + self, + strides, # strides of fpn levels + regression_range, # regression range (on feature grids) + use_offset=False, # if to align the points at grid centers + ): + super().__init__() + self.strides = strides + self.regression_range = regression_range + self.use_offset = use_offset + + def __call__(self, feat_list): + # feat_list: list[B,C,T] + + pts_list = [] + for i, feat in enumerate(feat_list): + T = feat.shape[-1] + + points = torch.linspace(0, T - 1, T, dtype=torch.float) * self.strides[i] # [T] + reg_range = torch.as_tensor(self.regression_range[i], dtype=torch.float) + stride = torch.as_tensor(self.strides[i], dtype=torch.float) + + if self.use_offset: + points += 0.5 * stride + + points = points[:, None] # [T,1] + reg_range = reg_range[None].repeat(T, 1) # [T,2] + stride = stride[None].repeat(T, 1) # [T,1] + pts_list.append(torch.cat((points, reg_range, stride), dim=1).to(feat.device)) # [T,4] + return pts_list diff --git a/OpenTAD/opentad/models/dense_heads/rpn_head.py b/OpenTAD/opentad/models/dense_heads/rpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..eaeda5b19086d51d9706022d018b978f4ad0cbdb --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/rpn_head.py @@ -0,0 +1,24 @@ +from ..builder import HEADS +from .anchor_head import AnchorHead + + +@HEADS.register_module() +class RPNHead(AnchorHead): + def __init__( + self, + in_channels, + feat_channels, + num_convs=3, + prior_generator=None, + loss=None, + cls_prior_prob=0.01, + ): + super().__init__( + num_classes=1, + in_channels=in_channels, + feat_channels=feat_channels, + num_convs=num_convs, + prior_generator=prior_generator, + loss=loss, + cls_prior_prob=cls_prior_prob, + ) diff --git a/OpenTAD/opentad/models/dense_heads/tem_head.py b/OpenTAD/opentad/models/dense_heads/tem_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f6926597365d10812deba29d503c4c4f3c99958b --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/tem_head.py @@ -0,0 +1,325 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..builder import HEADS +from ..bricks import ConvModule, GCNeXt +from ..losses.balanced_bce_loss import BalancedBCELoss +from ..utils.iou_tools import compute_ioa_torch + + +@HEADS.register_module() +class TemporalEvaluationHead(nn.Module): + def __init__(self, in_channels, num_classes, conv_cfg=None, loss=None, shared=False): + super().__init__() + + self.shared = shared + + if self.shared: # shared backbone + self.tem = nn.Sequential( + ConvModule( + in_channels, + in_channels, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + act_cfg=dict(type="relu"), + ), + ConvModule( + in_channels, + num_classes, + kernel_size=1, + stride=1, + ), + ) + + else: # not shared backbone + self.tem = nn.ModuleList([]) + for _ in range(num_classes): + layer = nn.Sequential( + ConvModule( + in_channels, + in_channels, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + act_cfg=dict(type="relu"), + ), + ConvModule( + in_channels, + 1, + kernel_size=1, + stride=1, + ), + ) + self.tem.append(layer) + + self.gt_type = loss["gt_type"] + for gt in self.gt_type: + assert gt in ["startness", "endness", "actionness"] + self.tem_loss = BalancedBCELoss(pos_thresh=loss["pos_thresh"]) + + def forward_train(self, x, masks, gt_segments, **kwargs): + if self.shared: + x = self.tem(x) + else: + x = torch.cat([layer(x) for layer in self.tem], dim=1) + + losses = {"loss_tem": self.losses(x, gt_segments)} + + proposal_list = None + return losses, proposal_list + + def forward_test(self, x, masks, **kwargs): + if self.shared: + x = self.tem(x) + else: + x = torch.cat([layer(x) for layer in self.tem], dim=1) + return x + + @torch.no_grad() + def prepare_targets(self, gt_segments, tscale): + gt_starts = [] + gt_ends = [] + gt_actions = [] + + temporal_anchor = torch.stack((torch.arange(0, tscale), torch.arange(1, tscale + 1)), dim=1) + temporal_anchor = temporal_anchor.to(gt_segments[0].device) + + for gt_segment in gt_segments: + gt_xmins = gt_segment[:, 0] + gt_xmaxs = gt_segment[:, 1] + + gt_start_bboxs = torch.stack((gt_xmins - 3.0 / 2, gt_xmins + 3.0 / 2), dim=1) + gt_end_bboxs = torch.stack((gt_xmaxs - 3.0 / 2, gt_xmaxs + 3.0 / 2), dim=1) + + gt_start = compute_ioa_torch(gt_start_bboxs, temporal_anchor) + gt_start = torch.max(gt_start, dim=1)[0] + + gt_end = compute_ioa_torch(gt_end_bboxs, temporal_anchor) # [T, N] + gt_end = torch.max(gt_end, dim=1)[0] + + gt_action = compute_ioa_torch(gt_segment, temporal_anchor) # [T, N] + gt_action = torch.max(gt_action, dim=1)[0] + + gt_starts.append(gt_start) + gt_ends.append(gt_end) + gt_actions.append(gt_action) + + gt_starts = torch.stack(gt_starts) + gt_ends = torch.stack(gt_ends) + gt_actions = torch.stack(gt_actions) + + gts = [] + if "startness" in self.gt_type: + gts.append(gt_starts) + + if "endness" in self.gt_type: + gts.append(gt_ends) + + if "actionness" in self.gt_type: + gts.append(gt_actions) + + return gts + + def losses(self, pred, gt_segments): + # pred: [B,2,T] + # gt_segment: list + + gts = self.prepare_targets(gt_segments, tscale=pred.shape[-1]) + assert len(gts) == pred.shape[1] + + pred = pred.sigmoid() # need to sigmoid + + loss = 0 + for i, gt in enumerate(gts): + loss += self.tem_loss(pred[:, i, :], gt) + return loss + + +@HEADS.register_module() +class GCNextTemporalEvaluationHead(TemporalEvaluationHead): + def __init__(self, in_channels, num_classes, loss=None, shared=False): + super().__init__(in_channels, num_classes, loss=loss, shared=shared) + + if self.shared: + self.tem = nn.Sequential( + GCNeXt(in_channels, in_channels, k=3, groups=32), + ConvModule(in_channels, num_classes, kernel_size=1, stride=1), + ) + + else: # not shared backbone + self.tem = nn.ModuleList([]) + for _ in range(num_classes): + layer = nn.Sequential( + GCNeXt(in_channels, in_channels, k=3, groups=32), + ConvModule(in_channels, 1, kernel_size=1, stride=1), + ) + self.tem.append(layer) + + +@HEADS.register_module() +class LocalGlobalTemporalEvaluationHead(nn.Module): + def __init__(self, in_channels, padding=0, loss=None): + super().__init__() + + # ------ local branch ------ + self.local_conv1d_s = nn.Conv1d(in_channels, 256, kernel_size=3, padding=1, groups=4) + self.local_conv1d_s_out = nn.Conv1d(256, 1, kernel_size=1) + + self.local_conv1d_e = nn.Conv1d(in_channels, 256, kernel_size=3, padding=1, groups=4) + self.local_conv1d_e_out = nn.Conv1d(256, 1, kernel_size=1) + + # ------ global branch ------ + channels = [128, 256, 512, 1024] + self.pool = nn.MaxPool1d(kernel_size=2, stride=2) + + self.x1_1 = nn.Conv1d(in_channels, channels[0], kernel_size=3, stride=1, padding=1, groups=4) + self.x2_1 = nn.Conv1d(channels[0], channels[1], kernel_size=3, stride=1, padding=1, groups=4) + self.x3_1 = nn.Conv1d(channels[1], channels[2], kernel_size=3, stride=1, padding=1, groups=4) + self.x4_1 = nn.Conv1d(channels[2], channels[3], kernel_size=3, stride=1, padding=1, groups=4) + + self.up41_to_32 = nn.ConvTranspose1d( + channels[3], + channels[2], + kernel_size=2, + stride=2, + output_padding=padding, + groups=4, + ) + + self.x3_2 = nn.Conv1d(channels[2] * 2, channels[2], kernel_size=3, stride=1, padding=1, groups=4) + + self.up31_to_22 = nn.ConvTranspose1d(channels[2], channels[1], kernel_size=2, stride=2, groups=4) + self.x2_2 = nn.Conv1d(channels[1] * 2, channels[1], kernel_size=3, stride=1, padding=1, groups=4) + + self.up32_to_23 = nn.ConvTranspose1d(channels[2], channels[1], kernel_size=2, stride=2, groups=4) + self.x2_3 = nn.Conv1d(channels[1] * 3, channels[1], kernel_size=3, stride=1, padding=1, groups=4) + + self.up21_to_12 = nn.ConvTranspose1d(channels[1], channels[0], kernel_size=2, stride=2, groups=4) + self.x1_2 = nn.Conv1d(channels[0] * 2, channels[0], kernel_size=3, stride=1, padding=1, groups=4) + + self.up22_to_13 = nn.ConvTranspose1d(channels[1], channels[0], kernel_size=2, stride=2, groups=4) + self.x1_3 = nn.Conv1d(channels[0] * 3, channels[0], kernel_size=3, stride=1, padding=1, groups=4) + + self.up23_to_14 = nn.ConvTranspose1d(channels[1], channels[0], kernel_size=2, stride=2, groups=4) + self.x1_4 = nn.Conv1d(channels[0] * 4, channels[0], kernel_size=3, stride=1, padding=1, groups=4) + + self.global_s_out = nn.Conv1d(channels[0], 1, kernel_size=1) + self.global_e_out = nn.Conv1d(channels[0], 1, kernel_size=1) + + self.tem_loss = BalancedBCELoss(pos_thresh=loss["pos_thresh"]) + + def forward_train(self, x, masks, gt_segments, **kwargs): + # ------ local branch ------ + tbd_local_s = F.relu(self.local_conv1d_s(x)) + tbd_local_s_out = self.local_conv1d_s_out(tbd_local_s).squeeze(1) + + tbd_local_e = F.relu(self.local_conv1d_e(x)) + tbd_local_e_out = self.local_conv1d_e_out(tbd_local_e).squeeze(1) + + # ------ global branch ------ + x1_1 = self.x1_1(x) + x2_1 = self.x2_1(self.pool(x1_1)) + x3_1 = self.x3_1(self.pool(x2_1)) + x4_1 = self.x4_1(self.pool(x3_1)) + + # layer 3 + x3_2 = self.x3_2(torch.cat((x3_1, self.up41_to_32(x4_1)), dim=1)) + + # layer 2 + x2_2 = self.x2_2(torch.cat((x2_1, self.up31_to_22(x3_1)), dim=1)) + x2_3 = self.x2_3(torch.cat((x2_1, x2_2, self.up32_to_23(x3_2)), dim=1)) + + # layer 1 + x1_2 = self.x1_2(torch.cat((x1_1, self.up21_to_12(x2_1)), dim=1)) + x1_3 = self.x1_3(torch.cat((x1_1, x1_2, self.up22_to_13(x2_2)), dim=1)) + x1_4 = self.x1_4(torch.cat((x1_1, x1_2, x1_3, self.up23_to_14(x2_3)), dim=1)) + + tbd_global_s_out = self.global_s_out(x1_4).squeeze(1) + tbd_global_e_out = self.global_e_out(x1_4).squeeze(1) + + tbd_out = (tbd_local_s_out, tbd_local_e_out, tbd_global_s_out, tbd_global_e_out) + + losses = {"loss_tem": self.losses(tbd_out, gt_segments)} + + proposal_list = None + return losses, proposal_list + + def forward_test(self, x, masks, **kwargs): + # ------ local branch ------ + tbd_local_s = F.relu(self.local_conv1d_s(x)) + tbd_local_s_out = self.local_conv1d_s_out(tbd_local_s).squeeze(1) + + tbd_local_e = F.relu(self.local_conv1d_e(x)) + tbd_local_e_out = self.local_conv1d_e_out(tbd_local_e).squeeze(1) + + # ------ global branch ------ + x1_1 = self.x1_1(x) + x2_1 = self.x2_1(self.pool(x1_1)) + x3_1 = self.x3_1(self.pool(x2_1)) + x4_1 = self.x4_1(self.pool(x3_1)) + + # layer 3 + x3_2 = self.x3_2(torch.cat((x3_1, self.up41_to_32(x4_1)), dim=1)) + + # layer 2 + x2_2 = self.x2_2(torch.cat((x2_1, self.up31_to_22(x3_1)), dim=1)) + x2_3 = self.x2_3(torch.cat((x2_1, x2_2, self.up32_to_23(x3_2)), dim=1)) + + # layer 1 + x1_2 = self.x1_2(torch.cat((x1_1, self.up21_to_12(x2_1)), dim=1)) + x1_3 = self.x1_3(torch.cat((x1_1, x1_2, self.up22_to_13(x2_2)), dim=1)) + x1_4 = self.x1_4(torch.cat((x1_1, x1_2, x1_3, self.up23_to_14(x2_3)), dim=1)) + + tbd_global_s_out = self.global_s_out(x1_4).squeeze(1) + tbd_global_e_out = self.global_e_out(x1_4).squeeze(1) + + tbd_out = (tbd_local_s_out, tbd_local_e_out, tbd_global_s_out, tbd_global_e_out) + + return tbd_out + + @torch.no_grad() + def prepare_targets(self, gt_segments, tscale): + gt_starts = [] + gt_ends = [] + + temporal_anchor = torch.stack((torch.arange(0, tscale), torch.arange(1, tscale + 1)), dim=1) + temporal_anchor = temporal_anchor.to(gt_segments[0].device) + + for gt_segment in gt_segments: + gt_xmins = gt_segment[:, 0] + gt_xmaxs = gt_segment[:, 1] + + gt_start_bboxs = torch.stack((gt_xmins - 3.0 / 2, gt_xmins + 3.0 / 2), dim=1) + gt_end_bboxs = torch.stack((gt_xmaxs - 3.0 / 2, gt_xmaxs + 3.0 / 2), dim=1) + + gt_start = compute_ioa_torch(gt_start_bboxs, temporal_anchor) + gt_start = torch.max(gt_start, dim=1)[0] + + gt_end = compute_ioa_torch(gt_end_bboxs, temporal_anchor) # [T, N] + gt_end = torch.max(gt_end, dim=1)[0] + + gt_starts.append(gt_start) + gt_ends.append(gt_end) + + gt_starts = torch.stack(gt_starts) + gt_ends = torch.stack(gt_ends) + return gt_starts, gt_ends + + def losses(self, pred, gt_segments): + tbd_ls, tbd_le, tbd_gs, tbd_ge = pred + gt_starts, gt_ends = self.prepare_targets(gt_segments, tscale=tbd_ls.shape[-1]) + + loss_tbd_ls = self.tem_loss(tbd_ls.sigmoid(), gt_starts) + loss_tbd_le = self.tem_loss(tbd_le.sigmoid(), gt_ends) + + loss_tbd_gs = self.tem_loss(tbd_gs.sigmoid(), gt_starts) + loss_tbd_ge = self.tem_loss(tbd_ge.sigmoid(), gt_ends) + + loss_tbd_local = loss_tbd_ls + loss_tbd_le + loss_tbd_global = loss_tbd_gs + loss_tbd_ge + + loss = 0.5 * (loss_tbd_local + loss_tbd_global) + return loss diff --git a/OpenTAD/opentad/models/dense_heads/temporalmaxer_head.py b/OpenTAD/opentad/models/dense_heads/temporalmaxer_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2999f738147d30ce48e073b04e104562a8e1b1af --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/temporalmaxer_head.py @@ -0,0 +1,143 @@ +import torch +from torch.nn import functional as F + +from .anchor_free_head import AnchorFreeHead +from ..builder import HEADS, build_loss + + +@HEADS.register_module() +class TemporalMaxerHead(AnchorFreeHead): + def __init__( + self, + num_classes, + in_channels, + feat_channels, + num_convs=3, + prior_generator=None, + loss=None, + loss_normalizer=100, + loss_normalizer_momentum=0.9, + label_smoothing=0, + cls_prior_prob=0.01, + loss_weight=1.0, + assigner=None, + ): + super().__init__( + num_classes, + in_channels, + feat_channels, + num_convs=num_convs, + cls_prior_prob=cls_prior_prob, + prior_generator=prior_generator, + loss=loss, + loss_normalizer=loss_normalizer, + loss_normalizer_momentum=loss_normalizer_momentum, + loss_weight=loss_weight, + label_smoothing=label_smoothing, + ) + self.assigner = build_loss(assigner) + + def losses(self, cls_pred, reg_pred, mask_list, points, gt_segments, gt_labels): + gt_cls, gt_reg, weights = self.prepare_targets(points, mask_list, cls_pred, reg_pred, gt_segments, gt_labels) + + # positive mask + gt_cls = torch.stack(gt_cls) + valid_mask = torch.cat(mask_list, dim=1) + pos_mask = torch.logical_and((gt_cls.sum(-1) > 0), valid_mask) + pos_weights = torch.stack(weights)[pos_mask] + num_pos = pos_mask.sum().item() + + # maintain an EMA of foreground to stabilize the loss normalizer + # useful for small mini-batch training + if self.training: + self.loss_normalizer = self.loss_normalizer_momentum * self.loss_normalizer + ( + 1 - self.loss_normalizer_momentum + ) * max(num_pos, 1) + loss_normalizer = self.loss_normalizer + else: + loss_normalizer = max(num_pos, 1) + + # 1. classification loss + cls_pred = [x.permute(0, 2, 1) for x in cls_pred] + cls_pred = torch.cat(cls_pred, dim=1)[valid_mask] + gt_target = gt_cls[valid_mask] + + # weight for cls + valid_cls_weights = torch.ones(gt_cls.shape[:-1], dtype=torch.float32).to(gt_cls.device) + valid_cls_weights[pos_mask] = pos_weights + valid_cls_weights = valid_cls_weights[valid_mask] + + # optional label smoothing + gt_target *= 1 - self.label_smoothing + gt_target += self.label_smoothing / (self.num_classes + 1) + + cls_loss = self.cls_loss(cls_pred, gt_target, reduction="none") + cls_loss = (cls_loss * valid_cls_weights[:, None]).sum() + cls_loss /= self.loss_normalizer + + # 2. regression using IoU/GIoU/DIOU loss (defined on positive samples) + split_size = [reg.shape[-1] for reg in reg_pred] + gt_reg = torch.stack(gt_reg).permute(0, 2, 1).split(split_size, dim=-1) # [B,2,T] + pred_segments = self.get_refined_proposals(points, reg_pred)[pos_mask] + gt_segments = self.get_refined_proposals(points, gt_reg)[pos_mask] + if num_pos == 0: + reg_loss = pred_segments.sum() * 0 + else: + # giou loss defined on positive samples + reg_loss = self.reg_loss(pred_segments, gt_segments, reduction="none") + reg_loss = (reg_loss * pos_weights).sum() + reg_loss /= loss_normalizer + + if self.loss_weight > 0: + loss_weight = self.loss_weight + else: + loss_weight = cls_loss.detach() / max(reg_loss.item(), 0.01) + + return {"cls_loss": cls_loss, "reg_loss": reg_loss * loss_weight} + + @torch.no_grad() + def prepare_targets(self, points, mask_list, cls_preds, reg_preds, gt_segments, gt_labels): + cls_preds = torch.cat([x.permute(0, 2, 1) for x in cls_preds], dim=1) # [B, T, 20] + reg_preds = torch.cat([x.permute(0, 2, 1) for x in reg_preds], dim=1) # [B, T, 2] + masks = torch.cat(mask_list, dim=1) + points = torch.cat(points, dim=0) + num_pts = points.shape[0] + + gt_cls, gt_reg, weights = [], [], [] + for mask, cls_pred, reg_pred, gt_segment, gt_label in zip(masks, cls_preds, reg_preds, gt_segments, gt_labels): + # label assignment + assign_matrix, min_inds, weight = self.assigner.assign( + cls_pred, points.clone(), reg_pred, gt_segment, gt_label, mask + ) + + # get target + num_gts = gt_segment.shape[0] + + # corner case where current sample does not have actions + if num_gts == 0: + gt_cls.append(gt_segment.new_full((num_pts, self.num_classes), 0)) + gt_reg.append(gt_segment.new_zeros((num_pts, 2))) + weights.append(weight) + continue + + # compute the distance of every point to each segment boundary + # auto broadcasting for all reg target-> F T x N x2 + gt_segs = gt_segment[None].expand(num_pts, num_gts, 2) + left = points[:, 0, None] - gt_segs[:, :, 0] + right = gt_segs[:, :, 1] - points[:, 0, None] + reg_targets = torch.stack((left, right), dim=-1) + + # cls_targets: F T x C; reg_targets F T x 2 + gt_label_one_hot = F.one_hot(gt_label.long(), self.num_classes).to(reg_targets.dtype) + cls_targets = assign_matrix @ gt_label_one_hot + # to prevent multiple GT actions with the same label and boundaries + cls_targets.clamp_(min=0.0, max=1.0) + + reg_targets = reg_targets[range(num_pts), min_inds] + # normalization based on stride + reg_targets /= points[:, 3, None] + + gt_cls.append(cls_targets) + gt_reg.append(reg_targets) + weights.append(weight) + return gt_cls, gt_reg, weights diff --git a/OpenTAD/opentad/models/dense_heads/tridet_head.py b/OpenTAD/opentad/models/dense_heads/tridet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..04bfcb73a518ad741963432bb2c314f74c076b75 --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/tridet_head.py @@ -0,0 +1,377 @@ +import math +import torch +import torch.nn as nn +from torch.nn import functional as F + +from ..builder import HEADS, build_loss +from .anchor_free_head import AnchorFreeHead +from ..bricks import ConvModule +from ..bricks.misc import Scale + + +@HEADS.register_module() +class TriDetHead(AnchorFreeHead): + def __init__( + self, + num_classes, + in_channels, + feat_channels, + num_convs=3, + cls_prior_prob=0.01, + prior_generator=None, + loss=None, + loss_normalizer=100, + loss_normalizer_momentum=0.9, + loss_weight=1.0, + label_smoothing=0.0, + center_sample="radius", + center_sample_radius=1.5, + kernel_size=3, + boundary_kernel_size=3, + iou_weight_power=0.2, + num_bins=16, + ): + self.kernel_size = kernel_size + self.boundary_kernel_size = boundary_kernel_size + self.num_bins = num_bins + self.iou_weight_power = iou_weight_power + + super().__init__( + num_classes, + in_channels, + feat_channels, + num_convs=num_convs, + cls_prior_prob=cls_prior_prob, + prior_generator=prior_generator, + loss=loss, + loss_normalizer=loss_normalizer, + loss_normalizer_momentum=loss_normalizer_momentum, + loss_weight=loss_weight, + label_smoothing=label_smoothing, + center_sample=center_sample, + center_sample_radius=center_sample_radius, + ) + + self._init_cls_start_convs() + self._init_cls_end_convs() + + self.iou_loss = build_loss(loss.iou_rate) + + def _init_cls_convs(self): + """Initialize classification conv layers of the head.""" + self.cls_convs = nn.ModuleList([]) + for i in range(self.num_convs): + self.cls_convs.append( + ConvModule( + self.in_channels if i == 0 else self.feat_channels, + self.feat_channels, + kernel_size=self.kernel_size, + stride=1, + padding=self.kernel_size // 2, + norm_cfg=dict(type="LN"), + act_cfg=dict(type="relu"), + ) + ) + + def _init_reg_convs(self): + """Initialize bbox regression conv layers of the head.""" + self.reg_convs = nn.ModuleList([]) + for i in range(self.num_convs): + self.reg_convs.append( + ConvModule( + self.in_channels if i == 0 else self.feat_channels, + self.feat_channels, + kernel_size=self.kernel_size, + stride=1, + padding=self.kernel_size // 2, + norm_cfg=dict(type="LN"), + act_cfg=dict(type="relu"), + ) + ) + + def _init_cls_start_convs(self): + """Initialize classification conv layers of the head.""" + self.cls_start_convs = nn.ModuleList([]) + for i in range(self.num_convs): + self.cls_start_convs.append( + ConvModule( + self.in_channels if i == 0 else self.feat_channels, + self.feat_channels, + kernel_size=self.boundary_kernel_size, + stride=1, + padding=self.boundary_kernel_size // 2, + norm_cfg=dict(type="LN"), + act_cfg=dict(type="relu"), + ) + ) + + def _init_cls_end_convs(self): + """Initialize classification conv layers of the head.""" + self.cls_end_convs = nn.ModuleList([]) + for i in range(self.num_convs): + self.cls_end_convs.append( + ConvModule( + self.in_channels if i == 0 else self.feat_channels, + self.feat_channels, + kernel_size=self.boundary_kernel_size, + stride=1, + padding=self.boundary_kernel_size // 2, + norm_cfg=dict(type="LN"), + act_cfg=dict(type="relu"), + ) + ) + + def _init_heads(self): + """Initialize predictor layers of the head.""" + self.cls_head = nn.Conv1d( + self.feat_channels, self.num_classes, kernel_size=self.kernel_size, padding=self.kernel_size // 2 + ) + self.reg_head = nn.Conv1d( + self.feat_channels, 2 * (self.num_bins + 1), kernel_size=self.kernel_size, padding=self.kernel_size // 2 + ) + + self.cls_start_head = nn.Conv1d( + self.feat_channels, + self.num_classes, + kernel_size=self.boundary_kernel_size, + padding=self.boundary_kernel_size // 2, + ) + self.cls_end_head = nn.Conv1d( + self.feat_channels, + self.num_classes, + kernel_size=self.boundary_kernel_size, + padding=self.boundary_kernel_size // 2, + ) + + self.scale = nn.ModuleList([Scale() for _ in range(len(self.prior_generator.strides))]) + + # use prior in model initialization to improve stability + # this will overwrite other weight init + if self.cls_prior_prob > 0: + bias_value = -(math.log((1 - self.cls_prior_prob) / self.cls_prior_prob)) + torch.nn.init.constant_(self.cls_head.bias, bias_value) + + def forward_train(self, feat_list, mask_list, gt_segments, gt_labels, **kwargs): + cls_pred = [] + reg_pred = [] + + cls_start_pred = [] + cls_end_pred = [] + + for l, (feat, mask) in enumerate(zip(feat_list, mask_list)): + cls_feat = feat + reg_feat = feat + + cls_start_feat = feat.detach() + cls_end_feat = feat.detach() + + for i in range(self.num_convs): + cls_feat, mask = self.cls_convs[i](cls_feat, mask) + reg_feat, mask = self.reg_convs[i](reg_feat, mask) + + cls_start_feat, mask = self.cls_start_convs[i](cls_start_feat, mask) + cls_end_feat, mask = self.cls_end_convs[i](cls_end_feat, mask) + + cls_pred.append(self.cls_head(cls_feat)) + reg_pred.append(F.relu(self.scale[l](self.reg_head(reg_feat)))) + cls_start_pred.append(self.cls_start_head(cls_start_feat)) + cls_end_pred.append(self.cls_end_head(cls_end_feat)) + + points = self.prior_generator(feat_list) + + losses = self.losses( + cls_pred, + reg_pred, + mask_list, + points, + gt_segments, + gt_labels, + cls_start_pred, + cls_end_pred, + ) + return losses + + def forward_test(self, feat_list, mask_list, **kwargs): + cls_pred = [] + reg_pred = [] + cls_start_pred = [] + cls_end_pred = [] + + for l, (feat, mask) in enumerate(zip(feat_list, mask_list)): + cls_feat = feat + reg_feat = feat + + cls_start_feat = feat.detach() + cls_end_feat = feat.detach() + + for i in range(self.num_convs): + cls_feat, mask = self.cls_convs[i](cls_feat, mask) + reg_feat, mask = self.reg_convs[i](reg_feat, mask) + + cls_start_feat, mask = self.cls_start_convs[i](cls_start_feat, mask) + cls_end_feat, mask = self.cls_end_convs[i](cls_end_feat, mask) + + cls_pred.append(self.cls_head(cls_feat)) + reg_pred.append(F.relu(self.scale[l](self.reg_head(reg_feat)))) + cls_start_pred.append(self.cls_start_head(cls_start_feat)) + cls_end_pred.append(self.cls_end_head(cls_end_feat)) + + points = self.prior_generator(feat_list) + + # get regression offsets + reg_pred = [x.permute(0, 2, 1) for x in reg_pred] # list([B,T_i,2]) + left, right = self.prepare_out_logits(cls_start_pred, cls_end_pred) # list([B C T_i, num_bins+1]) + decoded_offsets = [] + for i in range(len(left)): + batch_offsets = [] + for j in range(reg_pred[i].shape[0]): + batch_offsets.append( + self.decode_offset( + reg_pred[i][j], + left[i][j].permute(1, 0, 2), + right[i][j].permute(1, 0, 2), + False, + ) + ) + decoded_offsets.append(torch.stack(batch_offsets)) + reg_pred = torch.cat(decoded_offsets, dim=2) # [B, C, T, 2] + + # get proposals and scores + points = torch.cat(points, dim=0) # [T,4] + scores = torch.cat(cls_pred, dim=-1).permute(0, 2, 1).sigmoid() # [B,T,num_classes] + + # mask out invalid + masks = torch.cat(mask_list, dim=1)[..., None] # [B,T,1] + scores = scores * masks # [B,T,num_classes] + return points, reg_pred, scores + + def get_proposals(self, points, reg_pred): + start = points[:, 0] - reg_pred[:, 0] * points[:, 3] + end = points[:, 0] + reg_pred[:, 1] * points[:, 3] + proposals = torch.stack((start, end), dim=-1) # [N,2] + return proposals + + def pad_and_stride(self, cls_level_i, pad_left, num_bins): + pad = (num_bins, 0) if pad_left else (0, num_bins) + x = (F.pad(cls_level_i, pad, mode="constant", value=0)).unsqueeze(-1) # [B, C, T_i + bins, 1] + x_size = list(x.size()) + x_size[-1] = num_bins + 1 + x_size[-2] = x_size[-2] - num_bins # [B, C, T_i + bins, 1] -> [B, C, T_i, bins+1] + x_stride = list(x.stride()) + x_stride[-2] = x_stride[-1] + return x.as_strided(size=x_size, stride=x_stride) + + def prepare_out_logits(self, out_start, out_end): + # out_start, out_end list([B C T_i]) + out_start_logits = [] + out_end_logits = [] + for i in range(len(out_start)): + out_start_logits.append(self.pad_and_stride(out_start[i], True, self.num_bins).permute(0, 2, 1, 3)) + out_end_logits.append(self.pad_and_stride(out_end[i], False, self.num_bins).permute(0, 2, 1, 3)) + return out_start_logits, out_end_logits # list([B C T_i, num_bins+1]) + + def decode_offset(self, out_offsets, pred_left, pred_right, training=True): + # decode the offset value from the network output + # If the Trident-head is used, the predicted offset is calculated using the value from + # center offset head (out_offsets), start boundary head (pred_left) and end boundary head (pred_right) + + # Make an adaption for train and validation, when training, the out_offsets is a list with feature outputs + # from each FPN level. Each feature with shape [batchsize, T_level, (Num_bin+1)x2]. + # For validation, the out_offsets is a feature with shape [T_level, (Num_bin+1)x2] + if training: + # concat the offsets from different levels + out_offsets = torch.cat(out_offsets, dim=1) + out_offsets = out_offsets.view(out_offsets.shape[:2] + (2, -1)) # [B, T, 2, n_bins+1] + pred_left = torch.cat(pred_left, dim=1) # [B, T, C, n_bins+1] + pred_right = torch.cat(pred_right, dim=1) # [B, T, C, n_bins+1] + + pred_left_dis = torch.softmax(pred_left + out_offsets[:, :, :1, :], dim=-1) # [B, T, C, n_bins+1] + pred_right_dis = torch.softmax(pred_right + out_offsets[:, :, 1:, :], dim=-1) # [B, T, C, n_bins+1] + + else: + # offset from a single level + out_offsets = out_offsets.view(out_offsets.shape[0], 2, -1) # [T_i, 2, n_bins+1] + pred_left_dis = torch.softmax(pred_left + out_offsets[None, :, 0, :], dim=-1) # [C, T_i, n_bins+1] + pred_right_dis = torch.softmax(pred_right + out_offsets[None, :, 1, :], dim=-1) + + max_range_num = pred_left_dis.shape[-1] + + left_range_idx = torch.arange(max_range_num - 1, -1, -1, device=pred_left.device, dtype=torch.float) + right_range_idx = torch.arange(max_range_num, device=pred_right.device, dtype=torch.float) + + pred_left_dis = pred_left_dis.masked_fill(torch.isnan(pred_right_dis), 0) + pred_right_dis = pred_right_dis.masked_fill(torch.isnan(pred_right_dis), 0) + decoded_offset_left = torch.matmul(pred_left_dis, left_range_idx.unsqueeze(-1)) + decoded_offset_right = torch.matmul(pred_right_dis, right_range_idx.unsqueeze(-1)) + return torch.cat([decoded_offset_left, decoded_offset_right], dim=-1) + + def losses(self, cls_pred, reg_pred, mask_list, points, gt_segments, gt_labels, out_start, out_end): + gt_cls, gt_reg = self.prepare_targets(points, gt_segments, gt_labels) + + # positive mask + gt_cls = torch.stack(gt_cls) # [B,sum(T),num_classes] + gt_reg = torch.stack(gt_reg) # [B,sum(T),2] + valid_mask = torch.cat(mask_list, dim=1) + pos_mask = torch.logical_and((gt_cls.sum(-1) > 0), valid_mask) + num_pos = pos_mask.sum().item() + + # maintain an EMA of foreground to stabilize the loss normalizer + # useful for small mini-batch training + if self.training: + self.loss_normalizer = self.loss_normalizer_momentum * self.loss_normalizer + ( + 1 - self.loss_normalizer_momentum + ) * max(num_pos, 1) + loss_normalizer = self.loss_normalizer + else: + loss_normalizer = max(num_pos, 1) + + # 1. classification loss + cls_pred = [x.permute(0, 2, 1) for x in cls_pred] + cls_pred = torch.cat(cls_pred, dim=1)[valid_mask] + gt_target = gt_cls[valid_mask] + + # optional label smoothing + gt_target *= 1 - self.label_smoothing + gt_target += self.label_smoothing / (self.num_classes + 1) + + cls_loss = self.cls_loss(cls_pred, gt_target, reduction="none") + + # 2. regression using IoU/GIoU/DIOU loss (defined on positive samples) + reg_pred = [x.permute(0, 2, 1) for x in reg_pred] + + # decode the offset + out_start_logits, out_end_logits = self.prepare_out_logits(out_start, out_end) + decoded_offsets = self.decode_offset(reg_pred, out_start_logits, out_end_logits) + decoded_offsets = decoded_offsets[pos_mask] + + # the boundary head predicts the classification score for each categories. + pred_offsets = decoded_offsets[gt_cls[pos_mask].bool()] + gt_reg = gt_reg[pos_mask][torch.where(gt_cls[pos_mask])[0]] + points = torch.cat(points, dim=0).unsqueeze(0).repeat(pos_mask.shape[0], 1, 1) + points = points[pos_mask][torch.where(gt_cls[pos_mask])[0]] + + ## couple the classification loss with iou score + pred_segments = self.get_proposals(points, pred_offsets) + gt_segments = self.get_proposals(points, gt_reg) + + iou_rate = self.iou_loss(pred_segments, gt_segments, reduction="none") + rated_mask = gt_target > self.label_smoothing / (self.num_classes + 1) + cls_loss[rated_mask] *= (1 - iou_rate) ** self.iou_weight_power + + cls_loss = cls_loss.sum() + cls_loss /= self.loss_normalizer + + # regression loss + if num_pos == 0: + reg_loss = pred_segments.sum() * 0 + else: + # giou loss defined on positive samples + reg_loss = self.reg_loss(pred_segments, gt_segments, reduction="sum") + reg_loss /= loss_normalizer + + if self.loss_weight > 0: + loss_weight = self.loss_weight + else: + loss_weight = cls_loss.detach() / max(reg_loss.item(), 0.01) + + return {"cls_loss": cls_loss, "reg_loss": reg_loss * loss_weight} diff --git a/OpenTAD/opentad/models/dense_heads/vsgn_rpn_head.py b/OpenTAD/opentad/models/dense_heads/vsgn_rpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..64a94f4026b2ed2c30164587ac9fed064b36279d --- /dev/null +++ b/OpenTAD/opentad/models/dense_heads/vsgn_rpn_head.py @@ -0,0 +1,431 @@ +import math +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..builder import HEADS, build_loss, build_head +from ..losses.balanced_ce_loss import BalancedCELoss + + +class FPN_Anchors(nn.Module): + def __init__(self, pyramid_levels=[2, 4, 8, 16, 32], tscale=256, anchor_scale=[3, 7.5]): + super(FPN_Anchors, self).__init__() + self.pyramid_levels = pyramid_levels + self.tscale = tscale + self.scales = anchor_scale + self.base_stride = pyramid_levels[0] + + self.base_anchors = [] + for stride in pyramid_levels: + self.base_anchors.append(self.get_base_anchors(stride, self.scales)) + + self.anchors = self.gen_anchors() + + def gen_anchors(self): + feat_sizes = [math.ceil(self.tscale / stride) for stride in self.pyramid_levels] + anchors = [] + for size, stride, base_anchors in zip(feat_sizes, self.pyramid_levels, self.base_anchors): + shifts = torch.arange(0, size * stride, step=stride, dtype=torch.float32)[:, None].repeat(1, 2) + anchors.append((shifts.view(-1, 1, 2) + base_anchors.view(1, -1, 2)).reshape(-1, 2)) + + return anchors + + def get_base_anchors(self, stride, scales): + anchors = torch.tensor([1, stride], dtype=torch.float) - 0.5 + anchors = self._scale_enum(anchors, scales) + return anchors + + def _scale_enum(self, anchor, scales): + """Enumerate a set of anchors for each scale wrt an anchor.""" + length, center = self._whctrs(anchor) + ws = length * torch.tensor(scales) + anchors = self._mkanchors(ws, center) + return anchors + + def _mkanchors(self, ws, ctr): + anchors = torch.stack( + ( + ctr.unsqueeze(0) - 0.5 * (ws.to(dtype=torch.float32) - 1), + ctr.unsqueeze(0) + 0.5 * (ws.to(dtype=torch.float32) - 1), + ) + ).transpose(0, 1) + + return anchors + + def _whctrs(self, anchor): + length = anchor[1] - anchor[0] + 1 + center = anchor[0] + 0.5 * (length - 1) + return length, center + + +@HEADS.register_module() +class VSGNRPNHead(nn.Module): + def __init__( + self, + num_layers=4, + in_channels=256, + num_classes=1, + iou_thr=0.6, + anchor_generator=None, + tem_head=None, + loss_cls=None, + loss_loc=None, + ): + super(VSGNRPNHead, self).__init__() + + self.num_layers = num_layers + self.in_channels = in_channels + self.num_classes = num_classes + self.num_anchors = len(anchor_generator["anchor_scale"]) + + self.get_cls_towers() + self.get_reg_towers() + + self.tem_head = build_head(tem_head) + + self.iou_thr = iou_thr + self.anchor_generator = anchor_generator + self.anchors = FPN_Anchors(**anchor_generator).anchors + + # maintain an EMA of #foreground to stabilize the loss normalizer + # useful for small mini-batch training + self.loss_normalizer_cls = 100 + self.loss_normalizer_reg = 100 + self.loss_normalizer_momentum = 0.9 + self.loss_cls_func = build_loss(loss_cls) + # default regression loss is GIoU + + def get_cls_towers(self): + cls_tower = [] + for _ in range(self.num_layers): + cls_tower.append( + nn.Sequential( + nn.Conv1d( + self.in_channels, + self.in_channels, + kernel_size=3, + stride=1, + padding=1, + bias=False, + ), + nn.GroupNorm(32, self.in_channels), + nn.ReLU(), + ) + ) + self.cls_tower = nn.Sequential(*cls_tower) + + self.cls_head = nn.Conv1d( + self.in_channels, + self.num_anchors * self.num_classes, + kernel_size=3, + stride=1, + padding=1, + ) + + def get_reg_towers(self): + reg_tower = [] + for _ in range(self.num_layers): + reg_tower.append( + nn.Sequential( + nn.Conv1d( + self.in_channels, + self.in_channels, + kernel_size=3, + stride=1, + padding=1, + bias=False, + ), + nn.GroupNorm(32, self.in_channels), + nn.ReLU(), + ) + ) + self.reg_tower = nn.Sequential(*reg_tower) + self.reg_head = nn.Conv1d(self.in_channels, self.num_anchors * 2, kernel_size=3, stride=1, padding=1) + + def forward_train(self, feat_list, mask_list, gt_segments=None, gt_labels=None, return_loss=True): + B = feat_list[0].shape[0] + + # classification logits, start/end offsets + logits_pred = [] + offsets_pred = [] + for feat in feat_list: + logits_pred.append(self.cls_head(self.cls_tower(feat))) # (B, scales*cls, positions) * levels + offsets_pred.append(self.reg_head(self.reg_tower(feat))) # (B, scales*2, positions) * levels + + # (B, levels*positions*scales, cls) / (B, levels*positions*scales, 2) + logits_pred = torch.cat(logits_pred, dim=2).permute(0, 2, 1).reshape(B, -1, self.num_classes) + offsets_pred = torch.cat(offsets_pred, dim=2).permute(0, 2, 1).reshape(B, -1, 2) + + # anchors: (B, levels*positions*scales, 2) + anchors = torch.cat(self.anchors, dim=0).unsqueeze(0).repeat(B, 1, 1).to(device=feat_list[0].device) + + if self.num_classes == 1: + score_pred = logits_pred.sigmoid() + else: + score_pred = F.softmax(logits_pred, dim=2) + + # convert offsets to proposals + loc_pred = decode(offsets_pred.view(-1, 2), anchors.view(-1, 2)).view(B, -1, 2) + + # temporal evaluation module + tem_feat = F.interpolate(feat_list[0], size=self.anchor_generator.tscale, mode="linear", align_corners=True) + + losses = {} + if return_loss: + # start / end / action ness + losses.update(self.tem_head.forward_train(tem_feat, mask_list, gt_segments)[0]) + + # Special GT for VSGN: + # 1) Labels shift by including background = 0; + # 2) gt_segments has the third dimension as gt_labels + gts = [torch.cat((gt_b, gt_l[:, None] + 1), dim=-1) for gt_b, gt_l in zip(gt_segments, gt_labels)] + losses.update(self.cal_loc_loss(loc_pred, gts, anchors)) + losses.update(self.cal_cls_loss(logits_pred, gts, loc_pred)) + return losses, loc_pred + else: + tem_score = self.tem_head.forward_test(tem_feat, mask_list) + return tem_score, loc_pred, score_pred + + def forward_test(self, feat_list, mask_list, **kwargs): + return self.forward_train(feat_list, mask_list, return_loss=False, **kwargs) + + def cal_loc_loss(self, loc_pred, gt_bbox, anchors): + # reg_targets: corresponding gt_boxes of each anchor + cls_labels, loc_targets = prepare_targets(anchors, gt_bbox, self.iou_thr) + # bs, levels*positions*scales, num_cls/left-right + + loc_pred = loc_pred.view(-1, 2) + pos_inds = torch.nonzero(cls_labels > 0).squeeze(1) + + # update the loss normalizer + self.loss_normalizer_reg = self.loss_normalizer_momentum * self.loss_normalizer_reg + ( + 1 - self.loss_normalizer_momentum + ) * max(pos_inds.numel(), 1) + + reg_loss = giou_loss(loc_pred[pos_inds], loc_targets[pos_inds]) + reg_loss /= self.loss_normalizer_reg # pos_inds.numel() + return {"loss_stage1_reg": reg_loss} + + def cal_cls_loss(self, cls_pred, gt_bbox, anchors): + num_cls = self.num_classes + cls_labels, _ = prepare_targets(anchors, gt_bbox, self.iou_thr) + # bs, levels*positions*scales, num_cls/left-right + + if num_cls == 1: + cls_labels[cls_labels > 0] = 1 + + cls_pred = cls_pred.view(-1, num_cls) + # bs, levels*positions, scales*cls --> bs*levels*positions*scales, num_cls + pos_inds = torch.nonzero(cls_labels > 0).squeeze(1) + + # update the loss normalizer + self.loss_normalizer_cls = self.loss_normalizer_momentum * self.loss_normalizer_cls + ( + 1 - self.loss_normalizer_momentum + ) * max(pos_inds.numel(), 1) + + if isinstance(self.loss_cls_func, BalancedCELoss): + cls_loss = self.loss_cls_func(cls_pred, cls_labels) + else: + cls_pred = cls_pred.squeeze(-1) + cls_loss = self.loss_cls_func(cls_pred, cls_labels, reduction="sum") / self.loss_normalizer_cls + return {"loss_stage1_cls": cls_loss} + + +@torch.no_grad() +def prepare_targets(anchors, gt_bbox, iou_thr): + """ + Returns: + cls_labels: B * levels*positions*scales, num_cls + loc_targets: B * levels*positions*scales, left-right + """ + cls_targets = [] + reg_targets = [] + + for i in range(len(gt_bbox)): + gt_cur_im = gt_bbox[i][:, :-1] + gt_label = gt_bbox[i][:, -1] + anchor_cur_im = anchors[i] + + if anchor_cur_im.numel() == 0: + raise "Video with no proposals!" + + iou_matrix = iou_anchors_gts(anchor_cur_im, gt_cur_im) + + # Find the corresponding gt for each pred + matched_idxs = Matcher(True)(iou_matrix.transpose(0, 1), iou_thr) + + # Use the label of the corresponding gt as the classification target for the pred + cls_labels_cur_im = gt_label[matched_idxs] + cls_labels_cur_im[matched_idxs < 0] = 0 + + # Record the boundary offset as the regression target + matched_gts = gt_cur_im[matched_idxs.clamp(min=0)] + reg_targets_cur_im = matched_gts + + cls_targets.append(cls_labels_cur_im.to(dtype=torch.int32)) + reg_targets.append(reg_targets_cur_im) + + return torch.cat(cls_targets, dim=0), torch.cat(reg_targets, dim=0) + + +def iou_anchors_gts(anchor, gt): + anchors_min = anchor[:, 0] + anchors_max = anchor[:, 1] + box_min = gt[:, 0] + box_max = gt[:, 1] + len_anchors = anchors_max - anchors_min + 1 + int_xmin = torch.max(anchors_min[:, None], box_min) + int_xmax = torch.min(anchors_max[:, None], box_max) + inter_len = torch.clamp(int_xmax - int_xmin, min=0) + union_len = torch.clamp(len_anchors[:, None] + box_max - box_min - inter_len, min=0) + + jaccard = inter_len / union_len + + return jaccard + + +class Matcher(object): + """ + This class assigns to each predicted "element" (e.g., a box) a ground-truth + element. Each predicted element will have exactly zero or one matches; each + ground-truth element may be assigned to zero or more predicted elements. + + Matching is based on the MxN match_quality_matrix, that characterizes how well + each (ground-truth, predicted)-pair match. For example, if the elements are + boxes, the matrix may contain box IoU overlap values. + + The matcher returns a tensor of size N containing the index of the ground-truth + element m that matches to prediction n. If there is no match, a negative value + is returned. + """ + + BELOW_LOW_THRESHOLD = -1 + BETWEEN_THRESHOLDS = -2 + + def __init__(self, allow_low_quality_matches=False): + """ + Args: + allow_low_quality_matches (bool): if True, produce additional matches + for predictions that have only low-quality match candidates. See + set_low_quality_matches_ for more details. + """ + self.allow_low_quality_matches = allow_low_quality_matches + + def __call__(self, match_quality_matrix, iou_thr=0.5): + """ + Args: + match_quality_matrix (Tensor[float]): an MxN tensor, containing the + pairwise quality between M ground-truth elements and N predicted elements. + + Returns: + matches (Tensor[int64]): an N tensor where N[i] is a matched gt in + [0, M - 1] or a negative value indicating that prediction i could not + be matched. + """ + if match_quality_matrix.numel() == 0: + # empty targets or proposals not supported during training + if match_quality_matrix.shape[0] == 0: + raise ValueError("No ground-truth boxes available for one of the images " "during training") + else: + raise ValueError("No proposal boxes available for one of the images " "during training") + + # match_quality_matrix is M (gt) x N (predicted) + # Max over gt elements (dim 0) to find best gt candidate for each prediction + matched_vals, matches = match_quality_matrix.max(dim=0) + if self.allow_low_quality_matches: + all_matches = matches.clone() + + # Assign candidate matches with low quality to negative (unassigned) values + below_threshold = matched_vals < iou_thr + matches[below_threshold] = Matcher.BELOW_LOW_THRESHOLD + + if self.allow_low_quality_matches: + self.set_low_quality_matches_(matches, all_matches, match_quality_matrix) + + return matches + + def set_low_quality_matches_(self, matches, all_matches, match_quality_matrix): + """ + Produce additional matches for predictions that have only low-quality matches. + Specifically, for each ground-truth find the set of predictions that have + maximum overlap with it (including ties); for each prediction in that set, if + it is unmatched, then match it to the ground-truth with which it has the highest + quality value. + """ + # For each gt, find the prediction with which it has highest quality + highest_quality_foreach_gt, _ = match_quality_matrix.max(dim=1) + # Find highest quality match available, even if it is low, including ties + gt_pred_pairs_of_highest_quality = torch.nonzero(match_quality_matrix == highest_quality_foreach_gt[:, None]) + # Example gt_pred_pairs_of_highest_quality: + # tensor([[ 0, 39796], + # [ 1, 32055], + # [ 1, 32070], + # [ 2, 39190], + # [ 2, 40255], + # [ 3, 40390], + # [ 3, 41455], + # [ 4, 45470], + # [ 5, 45325], + # [ 5, 46390]]) + # Each row is a (gt index, prediction index) + # Note how gt items 1, 2, 3, and 5 each have two ties + + pred_inds_to_update = gt_pred_pairs_of_highest_quality[:, 1] + matches[pred_inds_to_update] = all_matches[pred_inds_to_update] + + +def giou_loss(pred_boxes, gt_boxes, weight=None): + pred_x1 = torch.min(pred_boxes[:, 0], pred_boxes[:, 1]) + pred_x2 = torch.max(pred_boxes[:, 0], pred_boxes[:, 1]) + pred_area = pred_x2 - pred_x1 + + target_x1 = gt_boxes[:, 0] + target_x2 = gt_boxes[:, 1] + target_area = target_x2 - target_x1 + + x1_intersect = torch.max(pred_x1, target_x1) + x2_intersect = torch.min(pred_x2, target_x2) + area_intersect = torch.zeros(pred_x1.size()).to(gt_boxes) + mask = x2_intersect > x1_intersect + area_intersect[mask] = x2_intersect[mask] - x1_intersect[mask] + + x1_enclosing = torch.min(pred_x1, target_x1) + x2_enclosing = torch.max(pred_x2, target_x2) + area_enclosing = (x2_enclosing - x1_enclosing) + 1e-7 + + area_union = pred_area + target_area - area_intersect + 1e-7 + ious = area_intersect / area_union + gious = ious - (area_enclosing - area_union) / area_enclosing + + losses = 1 - gious + + if weight is not None and weight.sum() > 0: + return (losses * weight).sum() + else: + assert losses.numel() != 0 + return losses.sum() + + +def decode(preds, anchors): + """ + Get absolute boundary values from anchors and predicted offsets + """ + anchors = anchors.to(preds.dtype) + + TO_REMOVE = 1 # TODO remove + ex_length = anchors[:, 1] - anchors[:, 0] + TO_REMOVE + ex_center = (anchors[:, 1] + anchors[:, 0]) / 2 + + wx, ww = (10, 5.0) + dx = preds[:, 0] / wx + dw = preds[:, 1] / ww + + # Prevent sending too large values into torch.exp() + dw = torch.clamp(dw, max=math.log(1000.0 / 16)) + + pred_ctr_x = dx * ex_length + ex_center + pred_w = torch.exp(dw) * ex_length + + pred_boxes = torch.zeros_like(preds) + pred_boxes[:, 0] = pred_ctr_x - 0.5 * (pred_w - 1) + pred_boxes[:, 1] = pred_ctr_x + 0.5 * (pred_w - 1) + return pred_boxes diff --git a/OpenTAD/opentad/models/detectors/__init__.py b/OpenTAD/opentad/models/detectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..049521f601c393135406d7de4a34ff2becdda4eb --- /dev/null +++ b/OpenTAD/opentad/models/detectors/__init__.py @@ -0,0 +1,35 @@ +from .base import BaseDetector +from .single_stage import SingleStageDetector +from .two_stage import TwoStageDetector +from .afsd import AFSD +from .bmn import BMN +from .gtad import GTAD +from .tsi import TSI +from .etad import ETAD +from .actionformer import ActionFormer +from .tridet import TriDet +from .temporalmaxer import TemporalMaxer +from .detr import DETR +from .deformable_detr import DeformableDETR +from .tadtr import TadTR +from .vsgn import VSGN +from .mamba import VideoMambaSuite + +__all__ = [ + "BaseDetector", + "SingleStageDetector", + "TwoStageDetector", + "AFSD", + "BMN", + "GTAD", + "TSI", + "ETAD", + "VSGN", + "ActionFormer", + "TriDet", + "TemporalMaxer", + "VideoMambaSuite", + "DETR", + "DeformableDETR", + "TadTR", +] diff --git a/OpenTAD/opentad/models/detectors/actionformer.py b/OpenTAD/opentad/models/detectors/actionformer.py new file mode 100644 index 0000000000000000000000000000000000000000..ba6e786ab87138f4fa10f9a875e462ba1af82109 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/actionformer.py @@ -0,0 +1,157 @@ +import torch +import torch.nn as nn + +from ..builder import DETECTORS +from .single_stage import SingleStageDetector +from ..bricks import Scale, AffineDropPath + + +@DETECTORS.register_module() +class ActionFormer(SingleStageDetector): + def __init__( + self, + projection, + rpn_head, + neck=None, + backbone=None, + ): + super().__init__( + backbone=backbone, + neck=neck, + projection=projection, + rpn_head=rpn_head, + ) + + n_mha_win_size = self.projection.n_mha_win_size + if isinstance(n_mha_win_size, int): + self.mha_win_size = [n_mha_win_size] * (1 + projection.arch[-1]) + else: + assert len(n_mha_win_size) == (1 + projection.arch[-1]) + self.mha_win_size = n_mha_win_size + self.max_seq_len = self.projection.max_seq_len + + max_div_factor = 1 + for s, w in zip(rpn_head.prior_generator.strides, self.mha_win_size): + stride = s * (w // 2) * 2 if w > 1 else s + assert self.max_seq_len % stride == 0, "max_seq_len must be divisible by fpn stride and window size" + if max_div_factor < stride: + max_div_factor = stride + self.max_div_factor = max_div_factor + + def pad_data(self, inputs, masks): + feat_len = inputs.shape[-1] + if feat_len == self.max_seq_len: + return inputs, masks + elif feat_len < self.max_seq_len: + max_len = self.max_seq_len + else: # feat_len > self.max_seq_len + max_len = feat_len + # pad the input to the next divisible size + stride = self.max_div_factor + max_len = (max_len + (stride - 1)) // stride * stride + + padding_size = [0, max_len - feat_len] + inputs = torch.nn.functional.pad(inputs, padding_size, value=0) + pad_masks = torch.zeros((inputs.shape[0], max_len), device=masks.device).bool() + pad_masks[:, :feat_len] = masks + return inputs, pad_masks + + def forward_train(self, inputs, masks, metas, gt_segments, gt_labels, **kwargs): + losses = dict() + if self.with_backbone: + x = self.backbone(inputs) + else: + x = inputs + + # pad the features and unsqueeze the mask for actionformer + x, masks = self.pad_data(x, masks) + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + loc_losses = self.rpn_head.forward_train( + x, + masks, + gt_segments=gt_segments, + gt_labels=gt_labels, + **kwargs, + ) + losses.update(loc_losses) + + # only key has loss will be record + losses["cost"] = sum(_value for _key, _value in losses.items()) + return losses + + def forward_test(self, inputs, masks, metas=None, infer_cfg=None, **kwargs): + if self.with_backbone: + x = self.backbone(inputs) + else: + x = inputs + + x, masks = self.pad_data(x, masks) + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + rpn_proposals, rpn_scores = self.rpn_head.forward_test(x, masks, **kwargs) + predictions = rpn_proposals, rpn_scores + return predictions + + def get_optim_groups(self, cfg): + # separate out all parameters that with / without weight decay + # see https://github.com/karpathy/minGPT/blob/master/mingpt/model.py#L134 + decay = set() + no_decay = set() + whitelist_weight_modules = (nn.Linear, nn.Conv1d) + blacklist_weight_modules = (nn.LayerNorm, nn.GroupNorm) + + # loop over all modules / params + for mn, m in self.named_modules(): + for pn, p in m.named_parameters(): + fpn = "%s.%s" % (mn, pn) if mn else pn # full param name + + # exclude the backbone parameters + if fpn.startswith("backbone"): + continue + + if pn.endswith("bias"): + # all biases will not be decayed + no_decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, whitelist_weight_modules): + # weights of whitelist modules will be weight decayed + decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, blacklist_weight_modules): + # weights of blacklist modules will NOT be weight decayed + no_decay.add(fpn) + elif pn.endswith("scale") and isinstance(m, (Scale, AffineDropPath)): + # corner case of our scale layer + no_decay.add(fpn) + elif pn.endswith("rel_pe"): + # corner case for relative position encoding + no_decay.add(fpn) + + # validate that we considered every parameter + param_dict = {pn: p for pn, p in self.named_parameters() if not pn.startswith("backbone")} + inter_params = decay & no_decay + union_params = decay | no_decay + assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params),) + assert ( + len(param_dict.keys() - union_params) == 0 + ), "parameters %s were not separated into either decay/no_decay set!" % (str(param_dict.keys() - union_params),) + + # create the pytorch optimizer object + optim_groups = [ + { + "params": [param_dict[pn] for pn in sorted(list(decay))], + "weight_decay": cfg["weight_decay"], + "lr": cfg["lr"], + }, + {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0, "lr": cfg["lr"]}, + ] + return optim_groups diff --git a/OpenTAD/opentad/models/detectors/afsd.py b/OpenTAD/opentad/models/detectors/afsd.py new file mode 100644 index 0000000000000000000000000000000000000000..578c5e5efd1f98f50ed65fe54405393b91842982 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/afsd.py @@ -0,0 +1,563 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np + +from ..builder import DETECTORS +from .two_stage import TwoStageDetector +from ..utils.post_processing import batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class AFSD(TwoStageDetector): + def __init__( + self, + neck, + rpn_head, + roi_head, + projection=None, + backbone=None, + ): + super(AFSD, self).__init__( + backbone=backbone, + projection=projection, + neck=neck, + rpn_head=rpn_head, + roi_head=roi_head, + ) + + self.num_classes = self.roi_head.num_classes + self.clip_len = rpn_head.frame_num + self.scale_factor = rpn_head.frame_num // rpn_head.feat_t + self.loss = MultiSegmentLoss( + self.num_classes, + self.clip_len, + overlap_thresh=roi_head.overlap_thresh, + negpos_ratio=1.0, + loc_weight=roi_head.loc_weight, + loc_bounded=roi_head.loc_bounded, + use_smooth_l1=roi_head.use_smooth_l1, + ) + self.calc_bce_loss = BCELoss() + + def forward_train(self, inputs, masks, metas, gt_segments, gt_labels, **kwargs): + if self.with_backbone: + x = self.backbone(inputs, masks) # [B,C,256,96,96] -> [B,C,256,3,3] + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + # AFSD Neck + pyramid_feats, frame_level_feat = self.neck(x, masks) + + # AFSD Coarse Head + ( + loc, + conf, + priors, + loc_feats, + conf_feats, + segments, + frame_segments, + ) = self.rpn_head.forward_train(pyramid_feats, **kwargs) + + # AFSD Refine Head + ( + start, + end, + prop_loc, + prop_conf, + center, + start_loc_prop, + end_loc_prop, + start_conf_prop, + end_conf_prop, + ) = self.roi_head.forward_train( + frame_level_feat, + loc_feats, + conf_feats, + segments, + frame_segments, + **kwargs, + ) + + # compute loss + gt_segments = [bboxes / masks.shape[1] for bboxes in gt_segments] # normalize gt_segments to [0,1] + gt_labels = [labels + 1 for labels in gt_labels] # change 0 to 1, since softmax + + losses = self.loss( + loc, + conf, + prop_loc, + prop_conf, + center, + priors, + gt_segments, + gt_labels, + ) + + losses.update( + self.compute_start_end_loss( + start, + end, + start_loc_prop, + end_loc_prop, + start_conf_prop, + end_conf_prop, + gt_segments, + ) + ) + + # only key has loss will be record + losses["cost"] = sum(_value for _key, _value in losses.items()) + return losses + + def compute_start_end_loss( + self, + pred_start, + pred_end, + start_loc_prop, + end_loc_prop, + start_conf_prop, + end_conf_prop, + gt_segments, + ): + with torch.no_grad(): + scores = [] + for gt_segment in gt_segments: + start = np.zeros([self.clip_len]) + end = np.zeros([self.clip_len]) + for seg in gt_segment: + s, e = seg.cpu().numpy() * self.clip_len + d = max((e - s) / 10.0, 2.0) + start_s = np.clip(int(round(s - d / 2)), 0, self.clip_len - 1) + start_e = np.clip(int(round(s + d / 2)), 0, self.clip_len - 1) + 1 + start[start_s:start_e] = 1 + end_s = np.clip(int(round(e - d / 2)), 0, self.clip_len - 1) + end_e = np.clip(int(round(e + d / 2)), 0, self.clip_len - 1) + 1 + end[end_s:end_e] = 1 + + scores.append(torch.from_numpy(np.stack([start, end], axis=0))) + scores = torch.stack(scores, dim=0).to(pred_start.device).float() + + loss_start, loss_end = self.calc_bce_loss(pred_start, pred_end, scores) + scores_ = F.interpolate(scores, scale_factor=1.0 / self.scale_factor) + loss_start_loc_prop, loss_end_loc_prop = self.calc_bce_loss(start_loc_prop, end_loc_prop, scores_) + loss_start_conf_prop, loss_end_conf_prop = self.calc_bce_loss(start_conf_prop, end_conf_prop, scores_) + loss_start = loss_start + 0.1 * (loss_start_loc_prop + loss_start_conf_prop) + loss_end = loss_end + 0.1 * (loss_end_loc_prop + loss_end_conf_prop) + return dict(loss_start=loss_start, loss_end=loss_end) + + def forward_test(self, inputs, masks, metas=None, infer_cfg=None): + if self.with_backbone: + x = self.backbone(inputs, masks) # [B,C,256,96,96]-> + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + # AFSD Neck + pyramid_feats, frame_level_feat = self.neck(x, masks) + + # AFSD Coarse Head + loc, conf, priors, loc_feats, conf_feats, segments, frame_segments = self.rpn_head.forward_train(pyramid_feats) + + # AFSD Refine Head + _, _, prop_loc, prop_conf, center, _, _, _, _ = self.roi_head.forward_train( + frame_level_feat, loc_feats, conf_feats, segments, frame_segments + ) + + # pack all + predictions = loc, conf, priors, prop_loc, prop_conf, center + return predictions + + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + locs, confs, priors, prop_locs, prop_confs, centers = predictions + + pre_nms_thresh = getattr(post_cfg, "pre_nms_thresh", 0.001) + pre_nms_topk = getattr(post_cfg, "pre_nms_topk", 2000) + + results = {} + for i in range(len(metas)): # processing each video + loc = locs[i] # [T,2] + conf = nn.Softmax(dim=-1)(confs[i]) # [N,num_class] + prop_loc = prop_locs[i] # [K,2] + prop_conf = nn.Softmax(dim=-1)(prop_confs[i]) # [N,num_class] + center = centers[i].sigmoid() # [N,1] + + pre_loc_w = loc[:, :1] + loc[:, 1:] + loc = 0.5 * pre_loc_w * prop_loc + loc + decoded_segments = torch.cat( + [ + priors[:, :1] * self.clip_len - loc[:, :1], + priors[:, :1] * self.clip_len + loc[:, 1:], + ], + dim=-1, + ) + decoded_segments.clamp_(min=0, max=self.clip_len) # [N,2] + decoded_segments = decoded_segments.cpu() + + conf = (conf + prop_conf) / 2.0 + conf = conf * center + conf = conf.view(-1, self.num_classes).transpose(1, 0) + conf_scores = conf.clone() + + # class 0 is background, we remove it + pred_prob = conf_scores[1:].transpose(0, 1).cpu() # [N,num_class-1] + num_classes = pred_prob.shape[1] + if num_classes == 1: # anet + scores = pred_prob.squeeze(-1) + labels = torch.zeros(scores.shape[0]).to(scores.device) + else: # thumos + pred_prob = pred_prob.flatten() # [N*num_class-1] + + # Apply filtering to make NMS faster following detectron2 + # 1. Keep seg with confidence score > a threshold + keep_idxs1 = pred_prob > pre_nms_thresh + pred_prob = pred_prob[keep_idxs1] + topk_idxs = keep_idxs1.nonzero(as_tuple=True)[0] + + # 2. Keep top k top scoring boxes only + num_topk = min(pre_nms_topk, topk_idxs.size(0)) + pred_prob, idxs = pred_prob.sort(descending=True) + pred_prob = pred_prob[:num_topk].clone() + topk_idxs = topk_idxs[idxs[:num_topk]].clone() + + # 3. gather predicted proposals + pt_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor") + cls_idxs = torch.fmod(topk_idxs, num_classes) + + decoded_segments = decoded_segments[pt_idxs] + scores = pred_prob + labels = cls_idxs + + # convert segments from 0~frame_num to 0~feature_grid + if metas[i]["fps"] == -1: # resize setting, like in anet / hacs + segments = decoded_segments.cpu() / self.clip_len * metas[i]["resize_length"] + else: # sliding window / padding setting, like in thumos / ego4d + segments = decoded_segments.cpu() / self.clip_len * metas[i]["window_size"] + + # if not sliding window, do nms + if post_cfg.sliding_window == False and post_cfg.nms is not None: + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + if isinstance(ext_cls, list): # own classification results + labels = [ext_cls[label.item()] for label in labels] + else: + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + return results + + +class MultiSegmentLoss(nn.Module): + def __init__( + self, + num_classes, + clip_len, + overlap_thresh, + negpos_ratio, + loc_weight=1.0, + cls_weight=1.0, + loc_bounded=True, + use_smooth_l1=False, + ): + super(MultiSegmentLoss, self).__init__() + self.num_classes = num_classes + self.clip_len = clip_len + self.overlap_thresh = overlap_thresh + self.negpos_ratio = negpos_ratio + self.focal_loss = FocalLoss_Ori(num_classes, balance_index=0, size_average=False, alpha=0.25) + self.loc_weight = loc_weight + self.cls_weight = cls_weight + self.loc_bounded = loc_bounded + self.use_smooth_l1 = use_smooth_l1 + + def forward(self, loc_data, conf_data, prop_loc_data, prop_conf_data, center_data, priors, gt_segments, gt_labels): + """ + :param predictions: a tuple containing loc, conf and priors + :param targets: ground truth segments and labels + :return: loc loss and conf loss + """ + num_batch = loc_data.size(0) + num_priors = priors.size(0) + num_classes = self.num_classes + clip_length = self.clip_len + + loss_l_list = [] + loss_c_list = [] + loss_ct_list = [] + loss_prop_l_list = [] + loss_prop_c_list = [] + + for idx in range(num_batch): + loc_t = torch.Tensor(num_priors, 2).to(loc_data.device) + prop_loc_t = torch.Tensor(num_priors, 2).to(loc_data.device) + + loc_p = loc_data[idx] + conf_p = conf_data[idx] + prop_loc_p = prop_loc_data[idx] + prop_conf_p = prop_conf_data[idx] + center_p = center_data[idx] + + with torch.no_grad(): + # match priors and ground truth segments + truths = gt_segments[idx] + labels = gt_labels[idx].long() + + K = priors.size(0) + N = truths.size(0) + center = priors[:, 0].unsqueeze(1).expand(K, N) + left = (center - truths[:, 0].unsqueeze(0).expand(K, N)) * clip_length + right = (truths[:, 1].unsqueeze(0).expand(K, N) - center) * clip_length + area = left + right + maxn = clip_length * 2 + area[left < 0] = maxn + area[right < 0] = maxn + + if self.loc_bounded: + max_dis = torch.max(left, right) + prior_lb, prior_rb = gen_bounds(priors) + l_bound = prior_lb.expand(K, N) + r_bound = prior_rb.expand(K, N) + area[max_dis <= l_bound] = maxn + area[max_dis > r_bound] = maxn + + best_truth_area, best_truth_idx = area.min(1) + loc_t[:, 0] = (priors[:, 0] - truths[best_truth_idx, 0]) * clip_length + loc_t[:, 1] = (truths[best_truth_idx, 1] - priors[:, 0]) * clip_length + conf_t = labels[best_truth_idx] + conf_t[best_truth_area >= maxn] = 0 + + iou = iou_loss(loc_p, loc_t, loss_type="iou") # [num_priors] + prop_conf_t = conf_t.clone() + + if self.loc_bounded: + if (conf_t > 0).sum() > 0: + max_iou = iou[conf_t > 0].max(0)[0] + else: + max_iou = 2.0 + prop_conf_t[iou < min(self.overlap_thresh, max_iou)] = 0 + else: + prop_conf_t[iou < self.overlap_thresh] = 0 + + prop_w = loc_p[:, 0] + loc_p[:, 1] + prop_loc_t[:, 0] = (loc_t[:, 0] - loc_p[:, 0]) / (0.5 * prop_w) + prop_loc_t[:, 1] = (loc_t[:, 1] - loc_p[:, 1]) / (0.5 * prop_w) + + pos = conf_t > 0 # [num_priors] + pos_idx = pos.unsqueeze(-1).expand_as(loc_p) # [num_priors, 2] + gt_loc_t = loc_t.clone() + loc_p = loc_p[pos_idx].view(-1, 2) + loc_target = loc_t[pos_idx].view(-1, 2) + if loc_p.numel() > 0: + loss_l = iou_loss(loc_p, loc_target, loss_type="giou", reduction="sum") + else: + loss_l = loc_p.sum() + + prop_pos = prop_conf_t > 0 + prop_pos_idx = prop_pos.unsqueeze(-1).expand_as(prop_loc_p) # [num_priors, 2] + prop_loc_p_pos = prop_loc_p[prop_pos_idx].view(-1, 2) + prop_loc_t_pos = prop_loc_t[prop_pos_idx].view(-1, 2) + + if prop_loc_p_pos.numel() > 0: + if self.use_smooth_l1: + loss_prop_l = F.smooth_l1_loss(prop_loc_p_pos, prop_loc_t_pos, reduction="sum") + else: + loss_prop_l = F.l1_loss(prop_loc_p_pos, prop_loc_t_pos, reduction="sum") + else: + loss_prop_l = prop_loc_p_pos.sum() + + prop_pre_loc = loc_p + cur_loc_t = gt_loc_t[pos_idx].view(-1, 2) + prop_loc_p = prop_loc_p[pos_idx].view(-1, 2) + center_p = center_p[pos.unsqueeze(-1)].view(-1) + if prop_pre_loc.numel() > 0: + prop_pre_w = (prop_pre_loc[:, 0] + prop_pre_loc[:, 1]).unsqueeze(-1) + cur_loc_p = 0.5 * prop_pre_w * prop_loc_p + prop_pre_loc + ious = iou_loss(cur_loc_p, cur_loc_t, loss_type="iou").clamp_(min=0) + loss_ct = F.binary_cross_entropy_with_logits(center_p, ious, reduction="sum") + else: + loss_ct = prop_pre_loc.sum() + + # softmax focal loss + conf_p = conf_p.view(-1, num_classes) + targets_conf = conf_t.view(-1, 1) + conf_p = F.softmax(conf_p, dim=1) + loss_c = self.focal_loss(conf_p, targets_conf) + + prop_conf_p = prop_conf_p.view(-1, num_classes) + prop_conf_p = F.softmax(prop_conf_p, dim=1) + loss_prop_c = self.focal_loss(prop_conf_p, prop_conf_t) + + N = max(pos.sum(), 1) + PN = max(prop_pos.sum(), 1) + loss_l /= N + loss_c /= N + loss_prop_l /= PN + loss_prop_c /= PN + loss_ct /= N + + loss_l_list.append(loss_l) + loss_c_list.append(loss_c) + loss_prop_l_list.append(loss_prop_l) + loss_prop_c_list.append(loss_prop_c) + loss_ct_list.append(loss_ct) + + losses = dict( + loss_loc=sum(loss_l_list) / num_batch * self.loc_weight, + loss_cls=sum(loss_c_list) / num_batch * self.cls_weight, + loss_iou=sum(loss_ct_list) / num_batch * self.cls_weight, + loss_prop_loc=sum(loss_prop_l_list) / num_batch * self.loc_weight, + loss_prop_cls=sum(loss_prop_c_list) / num_batch * self.cls_weight, + ) + + return losses + + +class FocalLoss_Ori(nn.Module): + """ + This is a implementation of Focal Loss with smooth label cross entropy supported which is proposed in + 'Focal Loss for Dense Object Detection. (https://arxiv.org/abs/1708.02002)' + Focal_Loss= -1*alpha*(1-pt)*log(pt) + :param num_class: + :param alpha: (tensor) 3D or 4D the scalar factor for this criterion + :param gamma: (float,double) gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putting more + focus on hard misclassified example + :param smooth: (float,double) smooth value when cross entropy + :param size_average: (bool, optional) By default, the losses are averaged over each loss element in the batch. + """ + + def __init__(self, num_class, alpha=0.25, gamma=2, balance_index=-1, size_average=True): + super(FocalLoss_Ori, self).__init__() + self.num_class = num_class + self.alpha = alpha + self.gamma = gamma + self.size_average = size_average + self.eps = 1e-6 + + if isinstance(self.alpha, (list, tuple)): + assert len(self.alpha) == self.num_class + self.alpha = torch.Tensor(list(self.alpha)) + elif isinstance(self.alpha, (float, int)): + assert 0 < self.alpha < 1.0, "alpha should be in `(0,1)`)" + assert balance_index > -1 + alpha = torch.ones((self.num_class)) + alpha *= 1 - self.alpha + alpha[balance_index] = self.alpha + self.alpha = alpha + elif isinstance(self.alpha, torch.Tensor): + self.alpha = self.alpha + else: + raise TypeError("Not support alpha type, expect `int|float|list|tuple|torch.Tensor`") + + def forward(self, logit, target): + if logit.dim() > 2: + # N,C,d1,d2 -> N,C,m (m=d1*d2*...) + logit = logit.view(logit.size(0), logit.size(1), -1) + logit = logit.transpose(1, 2).contiguous() # [N,C,d1*d2..] -> [N,d1*d2..,C] + logit = logit.view(-1, logit.size(-1)) # [N,d1*d2..,C]-> [N*d1*d2..,C] + target = target.view(-1, 1) # [N,d1,d2,...]->[N*d1*d2*...,1] + + # ----------memory saving way-------- + pt = logit.gather(1, target).view(-1) + self.eps + logpt = pt.log() + + if self.alpha.device != logpt.device: + self.alpha = self.alpha.to(logpt.device) + + alpha_class = self.alpha.gather(0, target.view(-1)) + logpt = alpha_class * logpt + loss = -1 * torch.pow(torch.sub(1.0, pt), self.gamma) * logpt + + if self.size_average: + loss = loss.mean() + else: + loss = loss.sum() + return loss + + +class BCELoss(nn.Module): + def __init__(self): + super(BCELoss, self).__init__() + self.bce_loss = torch.nn.BCELoss(reduction="mean") + + def forward(self, start, end, scores): + start = torch.tanh(start).mean(-1) + end = torch.tanh(end).mean(-1) + loss_start = self.bce_loss(start.view(-1), scores[:, 0].contiguous().view(-1).to(start.device)) + loss_end = self.bce_loss(end.view(-1), scores[:, 1].contiguous().view(-1).to(end.device)) + return loss_start, loss_end + + +def iou_loss(pred, target, weight=None, loss_type="giou", reduction="none"): + """ + iou: A ∩ B / A βˆͺ B = A ∩ B / (area(A) + area(B) - A ∩ B) + """ + pred_left = pred[:, 0] + pred_right = pred[:, 1] + target_left = target[:, 0] + target_right = target[:, 1] + + pred_area = pred_left + pred_right + target_area = target_left + target_right + + eps = torch.finfo(torch.float32).eps + + inter = torch.min(pred_left, target_left) + torch.min(pred_right, target_right) + area_union = target_area + pred_area - inter + ious = inter / area_union.clamp(min=eps) + + if loss_type == "linear_iou": + loss = 1.0 - ious + elif loss_type == "giou": + ac_uion = torch.max(pred_left, target_left) + torch.max(pred_right, target_right) + gious = ious - (ac_uion - area_union) / ac_uion.clamp(min=eps) + loss = 1.0 - gious + else: + loss = ious + + if weight is not None: + loss = loss * weight.view(loss.size()) + if reduction == "sum": + loss = loss.sum() + elif reduction == "mean": + loss = loss.mean() + return loss + + +def gen_bounds(priors): + bounds = [[0, 30], [15, 60], [30, 120], [60, 240], [96, 768], [256, 768]] + + K = priors.size(0) + prior_lb = priors[:, 1].clone() + prior_rb = priors[:, 1].clone() + for i in range(K): + prior_lb[i] = bounds[int(prior_lb[i])][0] + prior_rb[i] = bounds[int(prior_rb[i])][1] + prior_lb = prior_lb.unsqueeze(1) + prior_rb = prior_rb.unsqueeze(1) + return prior_lb, prior_rb diff --git a/OpenTAD/opentad/models/detectors/base.py b/OpenTAD/opentad/models/detectors/base.py new file mode 100644 index 0000000000000000000000000000000000000000..2fab99831a4fde76ad71c405a013a3716035cb1b --- /dev/null +++ b/OpenTAD/opentad/models/detectors/base.py @@ -0,0 +1,40 @@ +import torch +from ..utils.post_processing import load_predictions, save_predictions + + +class BaseDetector(torch.nn.Module): + """Base class for detectors.""" + + def __init__(self): + super(BaseDetector, self).__init__() + + def forward( + self, + inputs, + masks, + metas, + gt_segments=None, + gt_labels=None, + return_loss=True, + infer_cfg=None, + post_cfg=None, + **kwargs + ): + if return_loss: + return self.forward_train(inputs, masks, metas, gt_segments=gt_segments, gt_labels=gt_labels, **kwargs) + else: + return self.forward_detection(inputs, masks, metas, infer_cfg, post_cfg, **kwargs) + + def forward_detection(self, inputs, masks, metas, infer_cfg, post_cfg, **kwargs): + # step1: inference the model + if infer_cfg.load_from_raw_predictions: # easier and faster to tune the hyper parameter in postprocessing + predictions = load_predictions(metas, infer_cfg) + else: + predictions = self.forward_test(inputs, masks, metas, infer_cfg) + + if infer_cfg.save_raw_prediction: # save the predictions to disk + save_predictions(predictions, metas, infer_cfg.folder) + + # step2: detection post processing + results = self.post_processing(predictions, metas, post_cfg, **kwargs) + return results diff --git a/OpenTAD/opentad/models/detectors/bmn.py b/OpenTAD/opentad/models/detectors/bmn.py new file mode 100644 index 0000000000000000000000000000000000000000..5b0c35cf5ed44b5b3808e333b6376f9871c8ad25 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/bmn.py @@ -0,0 +1,168 @@ +import torch +import torch.nn as nn + +from ..builder import DETECTORS +from .two_stage import TwoStageDetector +from ..utils.post_processing import boundary_choose, batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class BMN(TwoStageDetector): + def __init__( + self, + projection, + rpn_head, + roi_head, + neck=None, + backbone=None, + ): + super(BMN, self).__init__( + backbone=backbone, + neck=neck, + projection=projection, + rpn_head=rpn_head, + roi_head=roi_head, + ) + + self.reset_params() + + def reset_params(self): + for m in self.modules(): + if isinstance(m, (nn.Conv1d, nn.Conv2d)): + nn.init.xavier_uniform_(m.weight) + nn.init.constant_(m.bias, 0) + + def forward_test(self, inputs, masks, metas=None, infer_cfg=None): + if self.with_backbone: + x = self.backbone(inputs, masks) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + # tem score + tem_score = self.rpn_head.forward_test(x, masks) # [B,2,T] + + # iou score + pred_iou_map = self.roi_head.forward_test(x) # [D,T,2] + + # pack all + predictions = tem_score, pred_iou_map + return predictions + + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + assert ext_cls != None # BMN is a proposal generation network + + score_type = getattr(post_cfg, "score_type", "iou") # otherwise, "iou*s*e" + proposal_post = getattr(post_cfg, "proposal", False) + + tem_score, pred_iou_map = predictions + tem_score = tem_score.sigmoid() + pred_iou_map = pred_iou_map.sigmoid() + + dscale = self.roi_head.proposal_generator.dscale + tscale = self.roi_head.proposal_generator.tscale + + # here is a nice matrix implementation for post processing + ds = torch.arange(0, dscale).to(pred_iou_map.device) + ts = torch.arange(0, tscale).to(pred_iou_map.device) + ds_mesh, ts_mesh = torch.meshgrid(ds, ts, indexing="ij") + start_end_index = torch.stack((ts_mesh, ts_mesh + ds_mesh), dim=-1) + valid_mask = start_end_index[:, :, 1] < tscale + start_end_index = start_end_index.clamp(max=tscale - 1).float() + + start_mask = boundary_choose(tem_score[:, 0, :]) + start_mask[:, 0] = True + end_mask = boundary_choose(tem_score[:, 1, :]) + end_mask[:, -1] = True + start_end_map = start_mask.unsqueeze(2) * end_mask.unsqueeze(1) + pred_iou_map = pred_iou_map[:, 0, :, :] * pred_iou_map[:, 1, :, :] + + results = {} + for i in range(len(metas)): # processing each video + start_end_mask = start_end_map[i][ + start_end_index[:, :, 0].view(-1).long(), + start_end_index[:, :, 1].view(-1).long(), + ] + start_end_mask = start_end_mask.reshape(dscale, tscale) * valid_mask + + segments_start = start_end_index[start_end_mask][:, 0] + segments_end = start_end_index[start_end_mask][:, 1] + 1 + segments = torch.stack((segments_start, segments_end), dim=-1).detach().cpu() + + # score + scores_iou = pred_iou_map[i][start_end_mask].detach().cpu() + if score_type == "iou": + scores = scores_iou + elif score_type == "iou*s*e": + score_start = tem_score[i, 0, start_end_index[start_end_mask][:, 0].long()].detach().cpu() + score_end = tem_score[i, 1, start_end_index[start_end_mask][:, 1].long()].detach().cpu() + scores = score_start * score_end * scores_iou + else: + raise f"score type should be iou or iou*s*e, but get {score_type}" + + # nms + labels = torch.zeros_like(scores_iou) # pseudo labels + if proposal_post: + segments = segments / tscale # convert to 0~1, since recall need a different NMS + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + segments = segments * tscale # convert back + else: + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + + return results + + def get_optim_groups(self, cfg): + BASE_weight = [] + TEM_weight = [] + PEM_weight = [] + + for name, p in self.named_parameters(): + # exclude the backbone + if name.startswith("backbone"): + continue + + if "projection" in name: + BASE_weight.append(p) + elif "rpn_head" in name: + TEM_weight.append(p) + elif "roi_head" in name: + PEM_weight.append(p) + else: + print(name, "is not in the optimizer") + + # create the pytorch optimizer object + optim_groups = [ + {"params": BASE_weight, "weight_decay": cfg["weight_decay"] * 10}, + {"params": TEM_weight, "weight_decay": cfg["weight_decay"]}, + {"params": PEM_weight, "weight_decay": cfg["weight_decay"]}, + ] + return optim_groups diff --git a/OpenTAD/opentad/models/detectors/deformable_detr.py b/OpenTAD/opentad/models/detectors/deformable_detr.py new file mode 100644 index 0000000000000000000000000000000000000000..6e08ed2a1e6f0d2fbb5f897644268ec818a0545f --- /dev/null +++ b/OpenTAD/opentad/models/detectors/deformable_detr.py @@ -0,0 +1,195 @@ +import torch +import torch.nn as nn + +from ..builder import DETECTORS +from .detr import DETR +from ..bricks import AffineDropPath +from ..utils.bbox_tools import proposal_cw_to_se +from ..utils.post_processing import batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class DeformableDETR(DETR): + def __init__( + self, + projection, + transformer, + neck=None, + backbone=None, + ): + super(DeformableDETR, self).__init__( + projection=projection, + transformer=transformer, + neck=neck, + backbone=backbone, + ) + + def forward_train(self, inputs, masks, metas, gt_segments, gt_labels, **kwargs): + if self.with_backbone: + x = self.backbone(inputs) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + # padding masks is the opposite of valid masks + if isinstance(masks, list): + padding_masks = [~mask for mask in masks] + elif isinstance(masks, torch.Tensor): + padding_masks = ~masks + else: + raise TypeError("masks should be either list or torch.Tensor") + + losses = dict() + transformer_loss = self.transformer.forward_train( + x, + padding_masks, + gt_segments=gt_segments, + gt_labels=gt_labels, + **kwargs, + ) + losses.update(transformer_loss) + + # only key has loss will be record + losses["cost"] = sum(_value for _key, _value in losses.items()) + return losses + + def forward_test(self, inputs, masks, metas=None, infer_cfg=None, **kwargs): + if self.with_backbone: + x = self.backbone(inputs) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + # padding masks is the opposite of valid masks + if isinstance(masks, list): + padding_masks = [~mask for mask in masks] + elif isinstance(masks, torch.Tensor): + padding_masks = ~masks + else: + raise TypeError("masks should be either list or torch.Tensor") + + output = self.transformer.forward_test(x, padding_masks, **kwargs) + + predictions = output, masks[0] + return predictions + + @torch.no_grad() + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + output, masks = predictions + pred_logits = output["pred_logits"] # [B,K,num_classes], before sigmoid + pred_boxes = output["pred_boxes"] # [B,K,2] + + pre_nms_topk = getattr(post_cfg, "pre_nms_topk", 200) + bs, _, num_classes = pred_logits.shape + + # Select top-k confidence boxes for inference + prob = pred_logits.sigmoid() + topk_values, topk_indexes = torch.topk(prob.view(bs, -1), pre_nms_topk, dim=1) + batch_scores = topk_values + topk_boxes = torch.div(topk_indexes, num_classes, rounding_mode="floor") + batch_labels = torch.fmod(topk_indexes, num_classes) + + batch_proposals = proposal_cw_to_se(pred_boxes) * torch.sum(masks, dim=1)[:, None, None] # cw -> sw, 0~tscale + batch_proposals = torch.gather(batch_proposals, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 2)) + + results = {} + for i in range(len(metas)): # processing each video + segments = batch_proposals[i].detach().cpu() # [N,2] + scores = batch_scores[i].detach().cpu() # [N,class] + labels = batch_labels[i].detach().cpu() # [N] + + # if not sliding window, do nms + if post_cfg.sliding_window == False and post_cfg.nms is not None: + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + if isinstance(ext_cls, list): # own classification results + labels = [ext_cls[label.item()] for label in labels] + else: + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + + return results + + def get_optim_groups(self, cfg): + # separate out all parameters that with / without weight decay + # see https://github.com/karpathy/minGPT/blob/master/mingpt/model.py#L134 + decay = set() + no_decay = set() + whitelist_weight_modules = (nn.Linear, nn.Conv1d) + blacklist_weight_modules = (nn.LayerNorm, nn.GroupNorm) + + # loop over all modules / params + for mn, m in self.named_modules(): + for pn, p in m.named_parameters(): + fpn = "%s.%s" % (mn, pn) if mn else pn # full param name + + # exclude the backbone parameters + if fpn.startswith("backbone"): + continue + + if pn.endswith("bias"): + # all biases will not be decayed + no_decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, whitelist_weight_modules): + # weights of whitelist modules will be weight decayed + decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, blacklist_weight_modules): + # weights of blacklist modules will NOT be weight decayed + no_decay.add(fpn) + elif pn.endswith("scale") and isinstance(m, AffineDropPath): + # corner case of our scale layer + no_decay.add(fpn) + elif pn.endswith("in_proj_weight") and isinstance(m, nn.MultiheadAttention): + decay.add(fpn) + elif pn.endswith("level_embeds"): + # corner case for position encoding + no_decay.add(fpn) + elif pn.endswith("weight") and ("tgt_embed" in pn): + no_decay.add(fpn) + + # validate that we considered every parameter + param_dict = {pn: p for pn, p in self.named_parameters() if not pn.startswith("backbone")} + inter_params = decay & no_decay + union_params = decay | no_decay + assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params),) + assert ( + len(param_dict.keys() - union_params) == 0 + ), "parameters %s were not separated into either decay/no_decay set!" % (str(param_dict.keys() - union_params),) + + # create the pytorch optimizer object + optim_groups = [ + {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": cfg["weight_decay"]}, + {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0}, + ] + return optim_groups diff --git a/OpenTAD/opentad/models/detectors/detr.py b/OpenTAD/opentad/models/detectors/detr.py new file mode 100644 index 0000000000000000000000000000000000000000..d3ab168c5a62001b046a1de223825e71fb9f5eb3 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/detr.py @@ -0,0 +1,164 @@ +import torch + +from .base import BaseDetector +from ..builder import DETECTORS, build_transformer, build_backbone, build_projection, build_neck +from ..utils.bbox_tools import proposal_cw_to_se +from ..utils.post_processing import batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class DETR(BaseDetector): + def __init__( + self, + projection, + transformer, + neck=None, + backbone=None, + ): + super().__init__() + + if backbone is not None: + self.backbone = build_backbone(backbone) + + if projection is not None: + self.projection = build_projection(projection) + + if neck is not None: + self.neck = build_neck(neck) + + self.transformer = build_transformer(transformer) + + @property + def with_backbone(self): + """bool: whether the detector has backbone""" + return hasattr(self, "backbone") and self.backbone is not None + + @property + def with_projection(self): + """bool: whether the detector has projection""" + return hasattr(self, "projection") and self.projection is not None + + @property + def with_neck(self): + """bool: whether the detector has neck""" + return hasattr(self, "neck") and self.neck is not None + + def forward_train(self, inputs, masks, metas, gt_segments, gt_labels, **kwargs): + if self.with_backbone: + x = self.backbone(inputs) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + # padding masks is the opposite of valid masks + padding_masks = ~masks + + losses = dict() + transformer_loss = self.transformer.forward_train( + x, + padding_masks, + gt_segments=gt_segments, + gt_labels=gt_labels, + **kwargs, + ) + losses.update(transformer_loss) + + # only key has loss will be record + losses["cost"] = sum(_value for _key, _value in losses.items()) + return losses + + def forward_test(self, inputs, masks, metas=None, infer_cfg=None, **kwargs): + if self.with_backbone: + x = self.backbone(inputs) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + # padding masks is the opposite of valid masks + padding_masks = ~masks + output = self.transformer.forward_test(x, padding_masks, **kwargs) + + predictions = output["pred_logits"], output["pred_boxes"], masks + return predictions + + @torch.no_grad() + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + pred_logits, pred_boxes, masks = predictions # [B,K,2], [B,K,num_classes] before softmax + + # For each box we assign the best class or the second best if the best on is `no_object`. + # batch_scores, batch_labels = F.softmax(pred_logits, dim=-1)[:, :, :-1].max(-1) + batch_scores = pred_logits.sigmoid() + batch_proposals = proposal_cw_to_se(pred_boxes) * torch.sum(masks, dim=1)[:, None, None] # cw -> sw, 0~tscale + + pre_nms_thresh = 0.001 + pre_nms_topk = 200 + num_classes = batch_scores.shape[-1] + + results = {} + for i in range(len(metas)): # processing each video + segments = batch_proposals[i].detach().cpu() # [N,2] + scores = batch_scores[i].detach().cpu() # [N,class] + pred_prob = scores.flatten() # [N*class] + + # Apply filtering to make NMS faster following detectron2 + # 1. Keep seg with confidence score > a threshold + keep_idxs1 = pred_prob > pre_nms_thresh + pred_prob = pred_prob[keep_idxs1] + topk_idxs = keep_idxs1.nonzero(as_tuple=True)[0] + + # 2. Keep top k top scoring boxes only + num_topk = min(pre_nms_topk, topk_idxs.size(0)) + pred_prob, idxs = pred_prob.sort(descending=True) + pred_prob = pred_prob[:num_topk].clone() + topk_idxs = topk_idxs[idxs[:num_topk]].clone() + + # 3. gather predicted proposals + pt_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor") + cls_idxs = torch.fmod(topk_idxs, num_classes) + + segments = segments[pt_idxs] + scores = pred_prob + labels = cls_idxs + + # if not sliding window, do nms + if post_cfg.sliding_window == False and post_cfg.nms is not None: + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + if isinstance(ext_cls, list): # own classification results + labels = [ext_cls[label.item()] for label in labels] + else: + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + + return results diff --git a/OpenTAD/opentad/models/detectors/etad.py b/OpenTAD/opentad/models/detectors/etad.py new file mode 100644 index 0000000000000000000000000000000000000000..6fb30dd45103d8773f875754a71d903dfc87bfd0 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/etad.py @@ -0,0 +1,108 @@ +import torch +import torch.nn as nn + +from ..builder import DETECTORS +from .two_stage import TwoStageDetector +from ..utils.post_processing import boundary_choose, batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class ETAD(TwoStageDetector): + def __init__( + self, + projection, + neck, + rpn_head, + roi_head, + backbone=None, + ): + super().__init__( + backbone=backbone, + neck=neck, + projection=projection, + rpn_head=rpn_head, + roi_head=roi_head, + ) + + self.reset_params() + + def reset_params(self): + for m in self.modules(): + if isinstance(m, (nn.Conv1d, nn.Linear)): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward_test(self, inputs, masks, metas=None, infer_cfg=None): + if self.with_backbone: + x = self.backbone(inputs, masks) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + # tem score + tem_score = self.rpn_head.forward_test(x, masks).sigmoid() # [B,2,T] + + # iou score + proposals, pred_iou = self.roi_head.forward_test(x) # [D,T,2] + + # pack all + predictions = tem_score, pred_iou, proposals + return predictions + + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + assert ext_cls != None # BMN is a proposal generation network + + tscale = self.roi_head.proposal_generator.tscale + + tem_score, pred_iou, proposals = predictions + pred_iou = pred_iou[..., 0] * pred_iou[..., 1] + + start_mask = boundary_choose(tem_score[:, 0, :]) + start_mask[:, 0] = True + end_mask = boundary_choose(tem_score[:, 1, :]) + end_mask[:, -1] = True + + results = {} + for i in range(len(metas)): # processing each video + start_idx = proposals[i][:, 0].int().clip(0, tscale - 1) + end_idx = proposals[i][:, 1].int().clip(0, tscale - 1) + idx = (start_mask[i][start_idx] == 1) & (end_mask[i][end_idx] == 1) + + segments = proposals[i][idx].detach().cpu() + scores = pred_iou[i][idx].detach().cpu() + # scores = (tem_score[i, 0][start_idx[idx]] * tem_score[i, 1][end_idx[idx]] * pred_iou[i][idx]).detach().cpu() + + labels = torch.zeros_like(scores) # pseudo labels + + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + return results diff --git a/OpenTAD/opentad/models/detectors/gtad.py b/OpenTAD/opentad/models/detectors/gtad.py new file mode 100644 index 0000000000000000000000000000000000000000..e82c9a7044e9d44891c092f71b207ced7e5bcba1 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/gtad.py @@ -0,0 +1,21 @@ +from ..builder import DETECTORS +from . import BMN + + +@DETECTORS.register_module() +class GTAD(BMN): + def __init__( + self, + projection, + neck, + rpn_head, + roi_head, + backbone=None, + ): + super(BMN, self).__init__( + backbone=backbone, + neck=neck, + projection=projection, + rpn_head=rpn_head, + roi_head=roi_head, + ) diff --git a/OpenTAD/opentad/models/detectors/mamba.py b/OpenTAD/opentad/models/detectors/mamba.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3658761d8c79a52b5abc4b51cf5b58f7cb9f55 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/mamba.py @@ -0,0 +1,74 @@ +import torch.nn as nn +from .single_stage import SingleStageDetector +from ..builder import DETECTORS +from ..bricks import Scale, AffineDropPath + + +@DETECTORS.register_module() +class VideoMambaSuite(SingleStageDetector): + def __init__(self, projection, rpn_head, neck=None, backbone=None): + super().__init__( + backbone=backbone, + neck=neck, + projection=projection, + rpn_head=rpn_head, + ) + + def get_optim_groups(self, cfg): + # separate out all parameters that with / without weight decay + # see https://github.com/karpathy/minGPT/blob/master/mingpt/model.py#L134 + decay = set() + no_decay = set() + whitelist_weight_modules = (nn.Linear, nn.Conv1d) + blacklist_weight_modules = (nn.LayerNorm, nn.GroupNorm) + + # loop over all modules / params + for mn, m in self.named_modules(): + for pn, p in m.named_parameters(): + fpn = "%s.%s" % (mn, pn) if mn else pn # full param name + + # exclude the backbone parameters + if fpn.startswith("backbone"): + continue + + if pn.endswith("bias"): + # all biases will not be decayed + no_decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, whitelist_weight_modules): + # weights of whitelist modules will be weight decayed + decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, blacklist_weight_modules): + # weights of blacklist modules will NOT be weight decayed + no_decay.add(fpn) + elif pn.endswith("scale") and isinstance(m, (Scale, AffineDropPath)): + # corner case of our scale layer + no_decay.add(fpn) + elif pn.endswith("rel_pe"): + # corner case for relative position encoding + no_decay.add(fpn) + elif ( + pn.endswith("A_log") + or pn.endswith("D_b") + or pn.endswith("D") + or pn.endswith("A_b_log") + or pn.endswith("forward_embed") + or pn.endswith("backward_embed") + ): + # corner case for mamba + decay.add(fpn) + + # validate that we considered every parameter + param_dict = {pn: p for pn, p in self.named_parameters() if not pn.startswith("backbone")} + inter_params = decay & no_decay + union_params = decay | no_decay + assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params),) + assert ( + len(param_dict.keys() - union_params) == 0 + ), "parameters %s were not separated into either decay/no_decay set!" % (str(param_dict.keys() - union_params),) + + # create the pytorch optimizer object + optim_groups = [ + {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": cfg["weight_decay"]}, + {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0}, + ] + return optim_groups diff --git a/OpenTAD/opentad/models/detectors/single_stage.py b/OpenTAD/opentad/models/detectors/single_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..a210c5750e7b70eef8a169a9872a057cdc496993 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/single_stage.py @@ -0,0 +1,168 @@ +import torch +from ..builder import DETECTORS, build_backbone, build_projection, build_head, build_neck +from .base import BaseDetector +from ..utils.post_processing import batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class SingleStageDetector(BaseDetector): + """ + Base class for single-stage detectors which should not have roi_extractors. + """ + + def __init__(self, backbone=None, projection=None, neck=None, rpn_head=None): + super(SingleStageDetector, self).__init__() + + if backbone is not None: + self.backbone = build_backbone(backbone) + + if projection is not None: + self.projection = build_projection(projection) + + if neck is not None: + self.neck = build_neck(neck) + + if rpn_head is not None: + self.rpn_head = build_head(rpn_head) + + @property + def with_backbone(self): + """bool: whether the detector has backbone""" + return hasattr(self, "backbone") and self.backbone is not None + + @property + def with_projection(self): + """bool: whether the detector has projection""" + return hasattr(self, "projection") and self.projection is not None + + @property + def with_neck(self): + """bool: whether the detector has neck""" + return hasattr(self, "neck") and self.neck is not None + + @property + def with_rpn_head(self): + """bool: whether the detector has localization head""" + return hasattr(self, "rpn_head") and self.rpn_head is not None + + def forward_train(self, inputs, masks, metas, gt_segments, gt_labels, **kwargs): + losses = dict() + if self.with_backbone: + x = self.backbone(inputs, masks) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + if self.with_rpn_head: + rpn_losses = self.rpn_head.forward_train( + x, + masks, + gt_segments=gt_segments, + gt_labels=gt_labels, + **kwargs, + ) + losses.update(rpn_losses) + + # only key has loss will be record + losses["cost"] = sum(_value for _key, _value in losses.items()) + return losses + + def forward_test(self, inputs, masks, metas=None, infer_cfg=None, **kwargs): + if self.with_backbone: + x = self.backbone(inputs, masks) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + if self.with_rpn_head: + rpn_proposals, rpn_scores = self.rpn_head.forward_test(x, masks) + else: + rpn_proposals = rpn_scores = None + + predictions = rpn_proposals, rpn_scores + return predictions + + @torch.no_grad() + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + rpn_proposals, rpn_scores = predictions + # rpn_proposals, # [B,K,2] + # rpn_scores, # [B,K,num_classes] after sigmoid + + pre_nms_thresh = getattr(post_cfg, "pre_nms_thresh", 0.001) + pre_nms_topk = getattr(post_cfg, "pre_nms_topk", 2000) + num_classes = rpn_scores[0].shape[-1] + + results = {} + for i in range(len(metas)): # processing each video + segments = rpn_proposals[i].detach().cpu() # [N,2] + scores = rpn_scores[i].detach().cpu() # [N,class] + + if num_classes == 1: + scores = scores.squeeze(-1) + labels = torch.zeros(scores.shape[0]).contiguous() + else: + pred_prob = scores.flatten() # [N*class] + + # Apply filtering to make NMS faster following detectron2 + # 1. Keep seg with confidence score > a threshold + keep_idxs1 = pred_prob > pre_nms_thresh + pred_prob = pred_prob[keep_idxs1] + topk_idxs = keep_idxs1.nonzero(as_tuple=True)[0] + + # 2. Keep top k top scoring boxes only + num_topk = min(pre_nms_topk, topk_idxs.size(0)) + pred_prob, idxs = pred_prob.sort(descending=True) + pred_prob = pred_prob[:num_topk].clone() + topk_idxs = topk_idxs[idxs[:num_topk]].clone() + + # 3. gather predicted proposals + pt_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor") + cls_idxs = torch.fmod(topk_idxs, num_classes) + + segments = segments[pt_idxs] + scores = pred_prob + labels = cls_idxs + + # if not sliding window, do nms + if post_cfg.sliding_window == False and post_cfg.nms is not None: + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + #import ipdb; ipdb.set_trace() + if isinstance(ext_cls, list): # own classification results + labels = [ext_cls[int(label.item())] for label in labels] + else: + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + + return results diff --git a/OpenTAD/opentad/models/detectors/tadtr.py b/OpenTAD/opentad/models/detectors/tadtr.py new file mode 100644 index 0000000000000000000000000000000000000000..0be87a9b77005d6e23e5e35c0dd39aeedfed8172 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/tadtr.py @@ -0,0 +1,124 @@ +import torch + +from ..builder import DETECTORS +from .deformable_detr import DeformableDETR +from ..utils.bbox_tools import proposal_cw_to_se +from ..utils.post_processing import batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class TadTR(DeformableDETR): + def __init__( + self, + projection, + transformer, + neck=None, + backbone=None, + ): + super(TadTR, self).__init__( + projection=projection, + transformer=transformer, + neck=neck, + backbone=backbone, + ) + self.with_act_reg = transformer.with_act_reg + + @torch.no_grad() + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + output, masks = predictions + pred_logits = output["pred_logits"] # [B,K,num_classes], before sigmoid + pred_boxes = output["pred_boxes"] # [B,K,2] + + pre_nms_topk = getattr(post_cfg, "pre_nms_topk", 200) + bs, _, num_classes = pred_logits.shape + + # Select top-k confidence boxes for inference + if self.with_act_reg: + prob = pred_logits.sigmoid() * output["pred_actionness"] + else: + prob = pred_logits.sigmoid() + + pre_nms_topk = min(pre_nms_topk, prob.view(bs, -1).shape[1]) + topk_values, topk_indexes = torch.topk(prob.view(bs, -1), pre_nms_topk, dim=1) + batch_scores = topk_values + topk_boxes = torch.div(topk_indexes, num_classes, rounding_mode="floor") + batch_labels = torch.fmod(topk_indexes, num_classes) + + batch_proposals = proposal_cw_to_se(pred_boxes) * masks.shape[-1] # cw -> sw, 0~tscale + batch_proposals = torch.gather(batch_proposals, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 2)) + + results = {} + for i in range(len(metas)): # processing each video + segments = batch_proposals[i].detach().cpu() # [N,2] + scores = batch_scores[i].detach().cpu() # [N,class] + labels = batch_labels[i].detach().cpu() # [N] + + # if not sliding window, do nms + if post_cfg.sliding_window == False and post_cfg.nms is not None: + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + if isinstance(ext_cls, list): # own classification results + labels = [ext_cls[label.item()] for label in labels] + else: + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + + return results + + def get_optim_groups(self, cfg): + def match_name_keywords(n, name_keywords): + out = False + for b in name_keywords: + if b in n: + out = True + break + return out + + lr_linear_proj_names = ["reference_points", "sampling_offsets"] + + param_dicts = [ + # non-backbone, non-offset + { + "params": [ + p + for n, p in self.named_parameters() + if not n.startswith("backbone") + and not match_name_keywords(n, lr_linear_proj_names) + and p.requires_grad + ], + "lr": cfg.lr, + "initial_lr": cfg.lr, + }, + # offset + { + "params": [ + p + for n, p in self.named_parameters() + if not n.startswith("backbone") and match_name_keywords(n, lr_linear_proj_names) and p.requires_grad + ], + "lr": cfg.lr * 0.1, + "initial_lr": cfg.lr * 0.1, + }, + ] + return param_dicts diff --git a/OpenTAD/opentad/models/detectors/temporalmaxer.py b/OpenTAD/opentad/models/detectors/temporalmaxer.py new file mode 100644 index 0000000000000000000000000000000000000000..362985cbfa85330ce1133aae6e7eef9d41e61015 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/temporalmaxer.py @@ -0,0 +1,64 @@ +import torch.nn as nn +from .single_stage import SingleStageDetector +from ..builder import DETECTORS +from ..bricks import Scale, AffineDropPath + + +@DETECTORS.register_module() +class TemporalMaxer(SingleStageDetector): + def __init__(self, projection, rpn_head, neck=None, backbone=None): + super().__init__( + backbone=backbone, + neck=neck, + projection=projection, + rpn_head=rpn_head, + ) + + def get_optim_groups(self, cfg): + # separate out all parameters that with / without weight decay + # see https://github.com/karpathy/minGPT/blob/master/mingpt/model.py#L134 + decay = set() + no_decay = set() + whitelist_weight_modules = (nn.Linear, nn.Conv1d) + blacklist_weight_modules = (nn.LayerNorm, nn.GroupNorm) + + # loop over all modules / params + for mn, m in self.named_modules(): + for pn, p in m.named_parameters(): + fpn = "%s.%s" % (mn, pn) if mn else pn # full param name + + # exclude the backbone parameters + if fpn.startswith("backbone"): + continue + + if pn.endswith("bias"): + # all biases will not be decayed + no_decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, whitelist_weight_modules): + # weights of whitelist modules will be weight decayed + decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, blacklist_weight_modules): + # weights of blacklist modules will NOT be weight decayed + no_decay.add(fpn) + elif pn.endswith("scale") and isinstance(m, (Scale, AffineDropPath)): + # corner case of our scale layer + no_decay.add(fpn) + elif pn.endswith("rel_pe"): + # corner case for relative position encoding + no_decay.add(fpn) + + # validate that we considered every parameter + param_dict = {pn: p for pn, p in self.named_parameters() if not pn.startswith("backbone")} + inter_params = decay & no_decay + union_params = decay | no_decay + assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params),) + assert ( + len(param_dict.keys() - union_params) == 0 + ), "parameters %s were not separated into either decay/no_decay set!" % (str(param_dict.keys() - union_params),) + + # create the pytorch optimizer object + optim_groups = [ + {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": cfg["weight_decay"]}, + {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0}, + ] + return optim_groups diff --git a/OpenTAD/opentad/models/detectors/tridet.py b/OpenTAD/opentad/models/detectors/tridet.py new file mode 100644 index 0000000000000000000000000000000000000000..f595b3407dfea2b019161a9d2c7cbae9d318fcbe --- /dev/null +++ b/OpenTAD/opentad/models/detectors/tridet.py @@ -0,0 +1,220 @@ +import torch +import torch.nn as nn + +from ..builder import DETECTORS +from .single_stage import SingleStageDetector +from ..bricks import Scale, AffineDropPath +from ..utils.post_processing import batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class TriDet(SingleStageDetector): + def __init__( + self, + projection, + rpn_head, + neck=None, + backbone=None, + ): + super(TriDet, self).__init__( + backbone=backbone, + neck=neck, + projection=projection, + rpn_head=rpn_head, + ) + + self.max_seq_len = projection.max_seq_len + assert len(projection.sgp_win_size) == len(rpn_head.prior_generator.strides) + + max_div_factor = 1 + for s, w in zip(rpn_head.prior_generator.strides, projection.sgp_win_size): + stride = s * w if w > 1 else s + if max_div_factor < stride: + max_div_factor = stride + self.max_div_factor = max_div_factor + + def pad_data(self, inputs, masks): + feat_len = inputs.shape[-1] + if feat_len <= self.max_seq_len: + max_len = self.max_seq_len + else: + max_len = feat_len + # pad the input to the next divisible size + stride = self.max_div_factor + max_len = (max_len + (stride - 1)) // stride * stride + + padding_size = [0, max_len - feat_len] + inputs = torch.nn.functional.pad(inputs, padding_size, value=0) + pad_masks = torch.zeros((inputs.shape[0], max_len), device=masks.device).bool() + pad_masks[:, :feat_len] = masks + return inputs, pad_masks + + def forward_train(self, inputs, masks, metas, gt_segments, gt_labels, **kwargs): + losses = dict() + if self.with_backbone: + x = self.backbone(inputs) + else: + x = inputs + + # pad the features and unsqueeze the mask + if not self.training: + x, masks = self.pad_data(x, masks) + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + loc_losses = self.rpn_head.forward_train( + x, + masks, + gt_segments=gt_segments, + gt_labels=gt_labels, + **kwargs, + ) + losses.update(loc_losses) + + # only key has loss will be record + losses["cost"] = sum(_value for _key, _value in losses.items()) + return losses + + def forward_test(self, inputs, masks, metas=None, infer_cfg=None, **kwargs): + if self.with_backbone: + x = self.backbone(inputs) + else: + x = inputs + + x, masks = self.pad_data(x, masks) + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + points, rpn_reg, rpn_scores = self.rpn_head.forward_test(x, masks, **kwargs) + predictions = points, rpn_reg, rpn_scores + return predictions + + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + points, rpn_reg, rpn_scores = predictions # [N, 4], [B, num_classes, N, 2], [B, N, num_classes] + + pre_nms_thresh = 0.001 + pre_nms_topk = 2000 + num_classes = rpn_scores.shape[-1] + points = points.cpu() + + results = {} + for i in range(len(metas)): # processing each video + scores = rpn_scores[i].detach().cpu() # [N] + reg = rpn_reg[i].detach().cpu() # [num_classes, N, 2] + + if num_classes == 1: + segments = self.rpn_head.get_proposals(points, reg.squeeze(0)).detach().cpu() # [N, 2] + scores = scores.squeeze(-1) + labels = torch.zeros(scores.shape[0]).contiguous() + else: + pred_prob = scores.flatten() # [N*class] + + # Apply filtering to make NMS faster following detectron2 + # 1. Keep seg with confidence score > a threshold + keep_idxs1 = pred_prob > pre_nms_thresh + pred_prob = pred_prob[keep_idxs1] + topk_idxs = keep_idxs1.nonzero(as_tuple=True)[0] + + # 2. Keep top k top scoring boxes only + num_topk = min(pre_nms_topk, topk_idxs.size(0)) + pred_prob, idxs = pred_prob.sort(descending=True) + pred_prob = pred_prob[:num_topk].clone() + topk_idxs = topk_idxs[idxs[:num_topk]].clone() + + # 3. gather predicted proposals + pt_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor") + cls_idxs = torch.fmod(topk_idxs, num_classes) + + segments = self.rpn_head.get_proposals(points[pt_idxs], reg[cls_idxs, pt_idxs]).detach().cpu() # [N, 2] + scores = pred_prob + labels = cls_idxs + + # if not sliding window, do nms + if post_cfg.sliding_window == False and post_cfg.nms is not None: + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + if isinstance(ext_cls, list): # own classification results + labels = [ext_cls[label.item()] for label in labels] + else: + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + + return results + + def get_optim_groups(self, cfg): + # separate out all parameters that with / without weight decay + # see https://github.com/karpathy/minGPT/blob/master/mingpt/model.py#L134 + decay = set() + no_decay = set() + whitelist_weight_modules = (nn.Linear, nn.Conv1d) + blacklist_weight_modules = (nn.LayerNorm, nn.GroupNorm) + + # loop over all modules / params + for mn, m in self.named_modules(): + for pn, p in m.named_parameters(): + fpn = "%s.%s" % (mn, pn) if mn else pn # full param name + + # exclude the backbone parameters + if fpn.startswith("backbone"): + continue + + if pn.endswith("bias"): + # all biases will not be decayed + no_decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, whitelist_weight_modules): + # weights of whitelist modules will be weight decayed + decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, blacklist_weight_modules): + # weights of blacklist modules will NOT be weight decayed + no_decay.add(fpn) + elif pn.endswith("scale") and isinstance(m, (Scale, AffineDropPath)): + # corner case of our scale layer + no_decay.add(fpn) + elif pn.endswith("rel_pe"): + # corner case for relative position encoding + no_decay.add(fpn) + + # validate that we considered every parameter + param_dict = {pn: p for pn, p in self.named_parameters() if not pn.startswith("backbone")} + inter_params = decay & no_decay + union_params = decay | no_decay + assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params),) + assert ( + len(param_dict.keys() - union_params) == 0 + ), "parameters %s were not separated into either decay/no_decay set!" % (str(param_dict.keys() - union_params),) + + # create the pytorch optimizer object + optim_groups = [ + {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": cfg["weight_decay"]}, + {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0}, + ] + return optim_groups diff --git a/OpenTAD/opentad/models/detectors/tsi.py b/OpenTAD/opentad/models/detectors/tsi.py new file mode 100644 index 0000000000000000000000000000000000000000..c49b38927a838b6b734c680c40358f24aa0246d4 --- /dev/null +++ b/OpenTAD/opentad/models/detectors/tsi.py @@ -0,0 +1,119 @@ +import torch +import torch.nn as nn + +from ..builder import DETECTORS +from .bmn import BMN +from ..utils.post_processing import boundary_choose, batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class TSI(BMN): + def __init__( + self, + projection, + rpn_head, + roi_head, + neck=None, + backbone=None, + ): + super().__init__( + backbone=backbone, + neck=neck, + projection=projection, + rpn_head=rpn_head, + roi_head=roi_head, + ) + + def reset_params(self): + for m in self.modules(): + if isinstance(m, (nn.Conv1d, nn.ConvTranspose1d, nn.Conv2d, nn.Conv3d)): + nn.init.xavier_uniform_(m.weight) + nn.init.constant_(m.bias, 0) + + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + assert ext_cls != None # BMN is a proposal generation network + + score_type = getattr(post_cfg, "score_type", "iou") # otherwise, "iou*s*e" + proposal_post = getattr(post_cfg, "proposal", False) + + (pred_local_s, pred_local_e, pred_global_s, pred_global_e), pred_iou_map = predictions + + pred_iou_map = pred_iou_map.sigmoid() + pred_s = torch.sqrt(pred_local_s.sigmoid() * pred_global_s.sigmoid()) + pred_e = torch.sqrt(pred_local_e.sigmoid() * pred_global_e.sigmoid()) + + dscale = self.roi_head.proposal_generator.dscale + tscale = self.roi_head.proposal_generator.tscale + + # here is a nice matrix implementation for post processing + ds = torch.arange(0, dscale).to(pred_iou_map.device) + ts = torch.arange(0, tscale).to(pred_iou_map.device) + ds_mesh, ts_mesh = torch.meshgrid(ds, ts, indexing="ij") + start_end_index = torch.stack((ts_mesh, ts_mesh + ds_mesh), dim=-1) + valid_mask = start_end_index[:, :, 1] < tscale + start_end_index = start_end_index.clamp(max=tscale - 1).float() + + start_mask = boundary_choose(pred_s) + start_mask[:, 0] = True + end_mask = boundary_choose(pred_e) + end_mask[:, -1] = True + start_end_map = start_mask.unsqueeze(2) * end_mask.unsqueeze(1) + pred_iou_map = pred_iou_map[:, 0, :, :] * pred_iou_map[:, 1, :, :] + + results = {} + for i in range(len(metas)): # processing each video + start_end_mask = start_end_map[i][ + start_end_index[:, :, 0].view(-1).long(), + start_end_index[:, :, 1].view(-1).long(), + ] + start_end_mask = start_end_mask.reshape(dscale, tscale) * valid_mask + + segments_start = start_end_index[start_end_mask][:, 0] + segments_end = start_end_index[start_end_mask][:, 1] + 1 + segments = torch.stack((segments_start, segments_end), dim=-1).detach().cpu() + + # score + scores_iou = pred_iou_map[i][start_end_mask].detach().cpu() + if score_type == "iou": + scores = scores_iou + elif score_type == "iou*s*e": + score_start = pred_s[i, start_end_index[start_end_mask][:, 0].long()].detach().cpu() + score_end = pred_e[i, start_end_index[start_end_mask][:, 1].long()].detach().cpu() + scores = score_start * score_end * scores_iou + else: + raise f"score type should be iou or iou*s*e, but get {score_type}" + + # nms + labels = torch.zeros_like(scores_iou) # pseudo labels + if proposal_post: + segments = segments / tscale # convert to 0~1, since recall need a different NMS + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + segments = segments * tscale # convert back + else: + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + + return results diff --git a/OpenTAD/opentad/models/detectors/two_stage.py b/OpenTAD/opentad/models/detectors/two_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc56d7054142f55412c02b6c1c76e2d7130861c --- /dev/null +++ b/OpenTAD/opentad/models/detectors/two_stage.py @@ -0,0 +1,197 @@ +import torch +from .base import BaseDetector +from ..builder import DETECTORS, build_backbone, build_projection, build_head, build_neck +from ..utils.post_processing import batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class TwoStageDetector(BaseDetector): + """Base class for two-stage detectors, consisting of roi_head.""" + + def __init__( + self, + backbone=None, + projection=None, + neck=None, + rpn_head=None, + roi_head=None, + ): + super(TwoStageDetector, self).__init__() + + if backbone is not None: + self.backbone = build_backbone(backbone) + + if projection is not None: + self.projection = build_projection(projection) + + if neck is not None: + self.neck = build_neck(neck) + + if rpn_head is not None: + self.rpn_head = build_head(rpn_head) + + if roi_head is not None: + self.roi_head = build_head(roi_head) + + @property + def with_backbone(self): + """bool: whether the detector has backbone""" + return hasattr(self, "backbone") and self.backbone is not None + + @property + def with_projection(self): + """bool: whether the detector has projection""" + return hasattr(self, "projection") and self.projection is not None + + @property + def with_neck(self): + """bool: whether the detector has neck""" + return hasattr(self, "neck") and self.neck is not None + + @property + def with_rpn_head(self): + """bool: whether the detector has RPN""" + return hasattr(self, "rpn_head") and self.rpn_head is not None + + @property + def with_roi_head(self): + """bool: whether the detector has a RoI head""" + return hasattr(self, "roi_head") and self.roi_head is not None + + def forward_train(self, inputs, masks, metas, gt_segments, gt_labels, **kwargs): + losses = dict() + + if self.with_backbone: + x = self.backbone(inputs, masks) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + if self.with_rpn_head: + rpn_losses, rpn_proposals = self.rpn_head.forward_train( + x, + masks, + gt_segments=gt_segments, + gt_labels=gt_labels, + **kwargs, + ) + losses.update(rpn_losses) + else: + rpn_proposals = None + + roi_losses = self.roi_head.forward_train( + x, + rpn_proposals, + gt_segments, + gt_labels, + **kwargs, + ) + losses.update(roi_losses) + + # only key has loss will be record + losses["cost"] = sum(_value for _key, _value in losses.items()) + return losses + + def forward_test(self, inputs, masks, metas=None, infer_cfg=None, **kwargs): + if self.with_backbone: + x = self.backbone(inputs, masks) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + if self.with_rpn_head: + rpn_proposals, rpn_scores = self.rpn_head.forward_test(x, masks) + else: + rpn_proposals = rpn_scores = None + + roi_proposals, roi_scores = self.roi_head.forward_test(x, rpn_proposals) + + # pack all + predictions = rpn_proposals, rpn_scores, roi_proposals, roi_scores + return predictions + + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + rpn_proposals, rpn_scores, roi_proposals, roi_scores = predictions + # rpn_proposals, # list [K,2] + # rpn_scores, # list [K] + # roi_proposals, # list [K,2] + # roi_scores, # list [K,num_class] + + pre_nms_thresh = 0.001 + pre_nms_topk = 2000 + num_classes = roi_scores[0].shape[-1] + + results = {} + for i in range(len(metas)): # processing each video + segments = roi_proposals[i].detach().cpu() # [N,2] + scores = (rpn_scores[i].unsqueeze(-1) * roi_scores[i]).detach().cpu() # [N,class] + # scores = rpn_scores[i].detach().cpu() # [N,class] + + if num_classes == 1: + scores = scores.squeeze(-1) + labels = torch.zeros(scores.shape[0]).contiguous() + else: + pred_prob = scores.flatten() # [N*class] + + # Apply filtering to make NMS faster following detectron2 + # 1. Keep seg with confidence score > a threshold + keep_idxs1 = pred_prob > pre_nms_thresh + pred_prob = pred_prob[keep_idxs1] + topk_idxs = keep_idxs1.nonzero(as_tuple=True)[0] + + # 2. Keep top k top scoring boxes only + num_topk = min(pre_nms_topk, topk_idxs.size(0)) + pred_prob, idxs = pred_prob.sort(descending=True) + pred_prob = pred_prob[:num_topk].clone() + topk_idxs = topk_idxs[idxs[:num_topk]].clone() + + # 3. gather predicted proposals + pt_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor") + cls_idxs = torch.fmod(topk_idxs, num_classes) + + segments = segments[pt_idxs] + scores = pred_prob + labels = cls_idxs + + # if not sliding window, do nms + if post_cfg.sliding_window == False and post_cfg.nms is not None: + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + if isinstance(ext_cls, list): # own classification results + labels = [ext_cls[label.item()] for label in labels] + else: + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + + return results diff --git a/OpenTAD/opentad/models/detectors/vsgn.py b/OpenTAD/opentad/models/detectors/vsgn.py new file mode 100644 index 0000000000000000000000000000000000000000..6ac45511312b10ab12ab02e66c483504644a3a8f --- /dev/null +++ b/OpenTAD/opentad/models/detectors/vsgn.py @@ -0,0 +1,177 @@ +import torch +import torch.nn as nn +from .two_stage import TwoStageDetector +from ..builder import DETECTORS +from ..utils.post_processing import batched_nms, convert_to_seconds + + +@DETECTORS.register_module() +class VSGN(TwoStageDetector): + def __init__( + self, + backbone=None, + projection=None, + neck=None, + rpn_head=None, + roi_head=None, + ): + super(VSGN, self).__init__( + backbone=backbone, + neck=neck, + projection=projection, + rpn_head=rpn_head, + roi_head=roi_head, + ) + + self.reset_params() + + def reset_params(self): + for m in self.modules(): + if isinstance(m, (nn.Conv1d, nn.Linear)): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward_train(self, inputs, masks, metas, gt_segments, gt_labels, **kwargs): + losses = dict() + + if self.with_backbone: + x = self.backbone(inputs, masks) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + rpn_losses, rpn_proposals = self.rpn_head.forward_train( + x, + masks, + gt_segments=gt_segments, + gt_labels=gt_labels, + **kwargs, + ) + losses.update(rpn_losses) + + roi_losses = self.roi_head.forward_train( + x, + rpn_proposals, + gt_segments=gt_segments, + gt_labels=gt_labels, + **kwargs, + ) + losses.update(roi_losses) + + losses["cost"] = sum(_value for _key, _value in losses.items()) + return losses + + def forward_test(self, inputs, masks, metas=None, infer_cfg=None, **kwargs): + if self.with_backbone: + x = self.backbone(inputs, masks) + else: + x = inputs + + if self.with_projection: + x, masks = self.projection(x, masks) + + if self.with_neck: + x, masks = self.neck(x, masks) + + tem_logits, rpn_proposals, rpn_scores = self.rpn_head.forward_test(x, masks, **kwargs) + + roi_proposals = self.roi_head.forward_test(x, rpn_proposals, **kwargs) + + # pack all + predictions = tem_logits, rpn_scores, roi_proposals + return predictions + + def post_processing(self, predictions, metas, post_cfg, ext_cls, **kwargs): + tem_logits, rpn_scores, roi_proposals = predictions + # tem_logits [B,3,T], rpn_scores [B,N,num_class], roi_proposals [B,N,2] + + pre_nms_thresh = 0.001 + pre_nms_topk = 2000 + num_classes = rpn_scores.shape[-1] + tscale = tem_logits.shape[-1] + start_scores, end_scores, _ = tem_logits.sigmoid().detach().cpu().unbind(dim=1) # [B,T] + + results = {} + + for i in range(len(metas)): # processing each video + segments = roi_proposals[i].detach().cpu() # [N,2] + segments = segments.clip(min=0, max=tscale - 1) + + start_score_l = start_scores[i][torch.floor(segments[:, 0]).int()] + start_score_r = start_scores[i][torch.ceil(segments[:, 0]).int()] + start_score = (start_score_l + start_score_r) * 0.5 + + end_score_l = end_scores[i][torch.floor(segments[:, 1]).int()] + end_score_r = end_scores[i][torch.ceil(segments[:, 1]).int()] + end_score = (end_score_l + end_score_r) * 0.5 + + scores = rpn_scores[i].detach().cpu() * (start_score * end_score).unsqueeze(-1) # [N,class] + + if num_classes == 1: + scores = scores.squeeze(-1) + labels = torch.zeros(scores.shape[0]).contiguous() + else: + # VSGN has the background class, so we remove it + scores = scores[:, 1:] + + pred_prob = scores.flatten() # [N*class] + + # Apply filtering to make NMS faster following detectron2 + # 1. Keep seg with confidence score > a threshold + keep_idxs1 = pred_prob > pre_nms_thresh + pred_prob = pred_prob[keep_idxs1] + topk_idxs = keep_idxs1.nonzero(as_tuple=True)[0] + + # 2. Keep top k top scoring boxes only + num_topk = min(pre_nms_topk, topk_idxs.size(0)) + pred_prob, idxs = pred_prob.sort(descending=True) + pred_prob = pred_prob[:num_topk].clone() + topk_idxs = topk_idxs[idxs[:num_topk]].clone() + + # 3. gather predicted proposals + # num_classes=21, so we should minus 1 + pt_idxs = torch.div(topk_idxs, num_classes - 1, rounding_mode="floor") + cls_idxs = torch.fmod(topk_idxs, num_classes - 1) + + segments = segments[pt_idxs] + scores = pred_prob + labels = cls_idxs + + # if not sliding window, do nms + if post_cfg.sliding_window == False and post_cfg.nms is not None: + segments, scores, labels = batched_nms(segments, scores, labels, **post_cfg.nms) + + video_id = metas[i]["video_name"] + + # convert segments to seconds + segments = convert_to_seconds(segments, metas[i]) + + # merge with external classifier + if isinstance(ext_cls, list): # own classification results + labels = [ext_cls[label.item()] for label in labels] + else: + segments, labels, scores = ext_cls(video_id, segments, scores) + + results_per_video = [] + for segment, label, score in zip(segments, labels, scores): + # convert to python scalars + results_per_video.append( + dict( + segment=[round(seg.item(), 2) for seg in segment], + label=label, + score=round(score.item(), 4), + ) + ) + + if video_id in results.keys(): + results[video_id].extend(results_per_video) + else: + results[video_id] = results_per_video + + return results diff --git a/OpenTAD/opentad/models/losses/__init__.py b/OpenTAD/opentad/models/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a58f1597e6aa9126f1491af4f62fdb593e44af2 --- /dev/null +++ b/OpenTAD/opentad/models/losses/__init__.py @@ -0,0 +1,24 @@ +from .balanced_bce_loss import BalancedBCELoss +from .balanced_ce_loss import BalancedCELoss +from .focal_loss import FocalLoss +from .smooth_l1_loss import SmoothL1Loss +from .balanced_l2_loss import BalancedL2Loss +from .iou_loss import DIOULoss, GIOULoss +from .scale_invariant_loss import ScaleInvariantLoss +from .set_loss import SetCriterion, DeformableSetCriterion, TadTRSetCriterion +from .assigner.anchor_free_simota_assigner import AnchorFreeSimOTAAssigner + +__all__ = [ + "BalancedBCELoss", + "BalancedCELoss", + "FocalLoss", + "BalancedL2Loss", + "SmoothL1Loss", + "DIOULoss", + "GIOULoss", + "ScaleInvariantLoss", + "SetCriterion", + "DeformableSetCriterion", + "TadTRSetCriterion", + "AnchorFreeSimOTAAssigner", +] diff --git a/OpenTAD/opentad/models/losses/assigner/anchor_free_simota_assigner.py b/OpenTAD/opentad/models/losses/assigner/anchor_free_simota_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..3364b6f4634396709b3998bbc31ad310691d647b --- /dev/null +++ b/OpenTAD/opentad/models/losses/assigner/anchor_free_simota_assigner.py @@ -0,0 +1,222 @@ +# modify from https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/bbox/assigners/sim_ota_assigner.py + +import torch +from torch.nn import functional as F +from ...builder import LOSSES +from ..focal_loss import sigmoid_focal_loss + +INF = float("inf") + + +@LOSSES.register_module() +class AnchorFreeSimOTAAssigner(object): + """Computes matching between predictions and ground truth. + + Args: + center_radius (int | float, optional): Ground truth center size + to judge whether a prior is in center. Default 2.5. + iou_weight (int | float, optional): The scale factor for regression + iou cost. Default 3.0. + cls_weight (int | float, optional): The scale factor for classification + cost. Default 1.0. + """ + + def __init__(self, center_radius=2.5, iou_weight=3.0, cls_weight=1.0, keep_percent=0.65, confuse_weight=0.1): + self.center_radius = center_radius + self.iou_weight = iou_weight + self.cls_weight = cls_weight + self.keep_percent = keep_percent + self.confuse_weight = confuse_weight + + def assign( + self, + out_scores, + points, + out_offsets, + gt_bboxes, + gt_labels, + valid_masks, + gt_bboxes_ignore=None, + eps=1e-7, + ): + assign_result = self._assign(out_scores, points, out_offsets, gt_bboxes, gt_labels, valid_masks, eps) + return assign_result + + def bbox_overlaps(self, points, out_offsets, gt_bboxes, eps: float = 1e-8): + num_bboxes = len(out_offsets) + num_gt = len(gt_bboxes) + + # gt_segs from (Mx2) to (NxMx2) + gt_segs = gt_bboxes[None].expand(num_bboxes, num_gt, 2) + left = points[:, 0, None] - gt_segs[:, :, 0] + right = gt_segs[:, :, 1] - points[:, 0, None] + gt_offset = torch.stack((left, right), dim=-1) + gt_offset /= points[:, 3, None].unsqueeze(-1) + + # out_offsets from (Nx2) to (NxMx2) + out_offsets = out_offsets.unsqueeze(1).expand(num_bboxes, num_gt, 2).clone() + + # set invalid positions = 0 + invalid_position = (gt_offset < 0).sum(-1) > 0 + gt_offset[invalid_position] = 0.0 + out_offsets[invalid_position] = 0.0 + + num_valid = len(out_offsets) + iou_cost, pairwise_ious = custom_ctr_diou_loss_1d(out_offsets.reshape(-1, 2), gt_offset.reshape(-1, 2)) + iou_cost = iou_cost.reshape(num_valid, num_gt) + iou_cost[invalid_position] = INF + pairwise_ious = pairwise_ious.reshape(num_valid, num_gt) + pairwise_ious[invalid_position] = 0 + return iou_cost, pairwise_ious + + @torch.no_grad() + def _assign(self, out_scores, points, out_offsets, gt_bboxes, gt_labels, valid_mask, eps=1e-7): + num_gt = gt_bboxes.size(0) + + valid_out_ofsets = out_offsets[valid_mask] + valid_out_scores = out_scores[valid_mask] + valid_points = points[valid_mask] + num_valid = valid_out_ofsets.size(0) + + pre_assign_mask = self.within_center(valid_points, gt_bboxes) + + iou_cost, pairwise_ious = self.bbox_overlaps(valid_points, valid_out_ofsets, gt_bboxes) + + gt_onehot_label = F.one_hot(gt_labels.long(), out_scores.shape[-1]) + gt_onehot_label = gt_onehot_label.float().unsqueeze(0).repeat(num_valid, 1, 1) + + valid_out_scores = valid_out_scores.unsqueeze(1).repeat(1, num_gt, 1) + cls_cost = sigmoid_focal_loss(valid_out_scores, gt_onehot_label).sum(-1) + cost_matrix = cls_cost * self.cls_weight + iou_cost * self.iou_weight + valid_cost_matrix_inds = cost_matrix < INF + valid_cost_matrix_inds = torch.logical_and(pre_assign_mask, valid_cost_matrix_inds) + + matching_matrix, min_inds, weight = self.dynamic_k_matching( + cost_matrix, num_gt, valid_mask, valid_cost_matrix_inds, pairwise_ious + ) + + # convert to original mask + original_matrix = torch.zeros((len(valid_mask), num_gt)).to(valid_mask.device) + original_matrix[valid_mask] = matching_matrix + + original_min_inds = torch.zeros((len(valid_mask),), dtype=torch.long).to(min_inds.device) + + original_min_inds[valid_mask] = min_inds + + original_weight = torch.zeros((len(valid_mask),), dtype=torch.float32).to(weight.device) + + original_weight[valid_mask] = weight + + return original_matrix, original_min_inds, original_weight + + def dynamic_k_matching(self, cost, num_gt, valid_mask, valid_cost_matrix_inds, pairwise_ious): + positive_pos = cost < INF + matching_matrix = (cost < INF).float() + pre_assign_weight = cost.new_ones((len(cost),)) + + pre_assign_weight[positive_pos.sum(1) > 0] = self.confuse_weight + + dynamic_ks = positive_pos.sum(0) + + dynamic_ks = (dynamic_ks * self.keep_percent).to(dynamic_ks) + + for gt_idx in range(num_gt): + _, pos_idx = torch.topk(cost[:, gt_idx], k=dynamic_ks[gt_idx], largest=False) + pre_assign_weight[pos_idx] = 1.0 + + del dynamic_ks, pos_idx + matching_matrix[~valid_cost_matrix_inds] = 0 + + _, min_inds = cost.min(1) + + return matching_matrix, min_inds, pre_assign_weight + + @torch.no_grad() + def within_center(self, concat_points, gt_segment): + # concat_points : F T x 4 (t, regression range, stride) + # gt_segment : N (#Events) x 2 + num_pts = concat_points.shape[0] + num_gts = gt_segment.shape[0] + + # compute the lengths of all segments -> F T x N + lens = gt_segment[:, 1] - gt_segment[:, 0] + lens = lens[None, :].repeat(num_pts, 1) + + if num_gts == 0: + return lens * 0.0 + + # compute the distance of every point to each segment boundary + # auto broadcasting for all reg target-> F T x N x2 + gt_segs = gt_segment[None].expand(num_pts, num_gts, 2) + left = concat_points[:, 0, None] - gt_segs[:, :, 0] + right = gt_segs[:, :, 1] - concat_points[:, 0, None] + reg_targets = torch.stack((left, right), dim=-1) + + # center of all segments F T x N + center_pts = 0.5 * (gt_segs[:, :, 0] + gt_segs[:, :, 1]) + # center sampling based on stride radius + # compute the new boundaries: + # concat_points[:, 3] stores the stride + t_mins = center_pts - concat_points[:, 3, None] * self.center_radius + t_maxs = center_pts + concat_points[:, 3, None] * self.center_radius + # prevent t_mins / maxs from over-running the action boundary + # left: torch.maximum(t_mins, gt_segs[:, :, 0]) + # right: torch.minimum(t_maxs, gt_segs[:, :, 1]) + # F T x N (distance to the new boundary) + cb_dist_left = concat_points[:, 0, None] - torch.maximum(t_mins, gt_segs[:, :, 0]) + cb_dist_right = torch.minimum(t_maxs, gt_segs[:, :, 1]) - concat_points[:, 0, None] + # F T x N x 2 + center_seg = torch.stack((cb_dist_left, cb_dist_right), -1) + # F T x N + inside_gt_seg_mask = center_seg.min(-1)[0] > 0 + + # limit the regression range for each location + max_regress_distance = reg_targets.max(-1)[0] + # F T x N + inside_regress_range = torch.logical_and( + (max_regress_distance >= concat_points[:, 1, None]), (max_regress_distance <= concat_points[:, 2, None]) + ) + + # lens.masked_fill_(inside_gt_seg_mask == 0, float('inf')) + # lens.masked_fill_(inside_regress_range == 0, float('inf')) + # pre_assign_mask = lens < INF + + lens.masked_fill_(inside_gt_seg_mask == 0, INF) + lens.masked_fill_(inside_regress_range == 0, INF) + # F T x N -> F T + min_len, min_len_inds = lens.min(dim=1) + + # corner case: multiple actions with very similar durations (e.g., THUMOS14) + pre_assign_mask = torch.logical_and((lens <= (min_len[:, None] + 1e-3)), (lens < INF)).to(reg_targets.dtype) + + return pre_assign_mask + + +def custom_ctr_diou_loss_1d(input_offsets: torch.Tensor, target_offsets: torch.Tensor, eps: float = 1e-8): + input_offsets = input_offsets.float() + target_offsets = target_offsets.float() + + lp, rp = input_offsets[:, 0], input_offsets[:, 1] + lg, rg = target_offsets[:, 0], target_offsets[:, 1] + + # intersection key points + lkis = torch.min(lp, lg) + rkis = torch.min(rp, rg) + + # iou + intsctk = rkis + lkis + unionk = (lp + rp) + (lg + rg) - intsctk + iouk = intsctk / unionk.clamp(min=eps) + + # smallest enclosing box + lc = torch.max(lp, lg) + rc = torch.max(rp, rg) + len_c = lc + rc + + # offset between centers + rho = 0.5 * (rp - lp - rg + lg) + + # diou + loss = 1.0 - iouk + torch.square(rho / len_c.clamp(min=eps)) + + return loss, iouk diff --git a/OpenTAD/opentad/models/losses/balanced_bce_loss.py b/OpenTAD/opentad/models/losses/balanced_bce_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..61e41a86c3279008d8e412dffc6b1e39d7865a09 --- /dev/null +++ b/OpenTAD/opentad/models/losses/balanced_bce_loss.py @@ -0,0 +1,34 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..builder import LOSSES + + +@LOSSES.register_module() +class BalancedBCELoss(nn.Module): + """Balanced Binary Cross-Entropy Loss. Usually used in temporal-evaluation-module.""" + + def __init__(self, pos_thresh=0.5): + super().__init__() + + self.pos_thresh = pos_thresh + + def forward(self, pred, gt): + pmask = (gt > self.pos_thresh).float() + nmask = (gt <= self.pos_thresh).float() + + loss = F.binary_cross_entropy(pred, pmask, reduction="none") + + num_pos = torch.sum(pmask) + num_neg = torch.sum(nmask) + + if (num_pos == 0) or (num_neg == 0): + return torch.mean(loss) + else: + coef_pos = 0.5 * (num_pos + num_neg) / num_pos + coef_neg = 0.5 * (num_pos + num_neg) / num_neg + loss = torch.mean((coef_pos * pmask + coef_neg * nmask) * loss) + return loss + + def __repr__(self): + return f"{self.__class__.__name__}(" f"pos_thresh={self.pos_thresh})" diff --git a/OpenTAD/opentad/models/losses/balanced_ce_loss.py b/OpenTAD/opentad/models/losses/balanced_ce_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..7b0ccf5aed6d73ef2af038fc3cb7870458d13c78 --- /dev/null +++ b/OpenTAD/opentad/models/losses/balanced_ce_loss.py @@ -0,0 +1,26 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..builder import LOSSES + + +@LOSSES.register_module() +class BalancedCELoss(object): + """Used in VSGN""" + + def __init__(self) -> None: + self.loss = torch.nn.CrossEntropyLoss(reduction="none") + + def __call__(self, cls_pred, cls_labels): + pmask = (cls_labels > 0).float() + nmask = (cls_labels == 0).float() + num_pos = torch.sum(pmask) + num_neg = torch.sum(nmask) + + loss = self.loss(cls_pred, cls_labels.to(torch.long)) + + pos_loss = torch.sum(loss * pmask) / num_pos + neg_loss = torch.sum(loss * nmask) / num_neg + + total_loss = pos_loss + neg_loss + return total_loss diff --git a/OpenTAD/opentad/models/losses/balanced_l2_loss.py b/OpenTAD/opentad/models/losses/balanced_l2_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..2d7b98f64b875e048d599fcd34bec9c8796ed892 --- /dev/null +++ b/OpenTAD/opentad/models/losses/balanced_l2_loss.py @@ -0,0 +1,48 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..builder import LOSSES + + +@LOSSES.register_module() +class BalancedL2Loss(nn.Module): + def __init__(self, high_thresh=0.7, low_thresh=0.3, weight=1.0): + super().__init__() + + self.high_thresh = high_thresh + self.low_thresh = low_thresh + self.weight = weight + + def forward(self, pred, gt): + h_mask = (gt > self.high_thresh).float() + m_mask = ((gt <= self.high_thresh) & (gt > self.low_thresh)).float() + l_mask = (gt <= self.low_thresh).float() + + num_h = torch.sum(h_mask) + num_m = torch.sum(m_mask) + num_l = torch.sum(l_mask) + + if num_h == 0: # in case of nan + loss = F.mse_loss(pred, gt, reduction="mean") + return loss + + r_m = num_h / num_m + m_mask_sample = torch.rand(m_mask.shape).to(gt.device) * m_mask + m_mask_sample = (m_mask_sample > (1 - r_m)).float() + + r_l = num_h / num_l + l_mask_sample = torch.rand(l_mask.shape).to(gt.device) * l_mask + l_mask_sample = (l_mask_sample > (1 - r_l)).float() + + mask = h_mask + m_mask_sample + l_mask_sample + loss = F.mse_loss(pred, gt, reduction="none") + loss = torch.sum(loss * mask) / torch.sum(mask) + + loss *= self.weight + return loss + + def __repr__(self): + return ( + f"{self.__class__.__name__}(" + f"high_thresh={self.high_thresh}, low_thresh={self.low_thresh}, weight={self.weight})" + ) diff --git a/OpenTAD/opentad/models/losses/focal_loss.py b/OpenTAD/opentad/models/losses/focal_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..47bbcb3aeab367bfc7f212be25bb77e7f859fc26 --- /dev/null +++ b/OpenTAD/opentad/models/losses/focal_loss.py @@ -0,0 +1,64 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..builder import LOSSES + + +@LOSSES.register_module() +class FocalLoss(nn.Module): + def __init__(self, alpha: float = 0.25, gamma: float = 2.0): + super(FocalLoss, self).__init__() + self.alpha = alpha + self.gamma = gamma + + def forward(self, inputs: torch.Tensor, targets: torch.Tensor, reduction: str = "none") -> torch.Tensor: + """ + Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. + Taken from + https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/focal_loss.py + # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + + 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 = 0.25. + gamma: Exponent of the modulating factor (1 - p_t) to + balance easy vs hard examples. + reduction: 'none' | 'mean' | 'sum' + 'none': No reduction will be applied to the output. + 'mean': The output will be averaged. + 'sum': The output will be summed. + Returns: + Loss tensor with the reduction option applied. + """ + loss = sigmoid_focal_loss(inputs, targets, self.alpha, self.gamma) + + if reduction == "mean": + loss = loss.mean() + elif reduction == "sum": + loss = loss.sum() + + return loss + + +def sigmoid_focal_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + alpha: float = 0.25, + gamma: float = 2.0, +) -> torch.Tensor: + inputs = inputs.float() + targets = targets.float() + p = torch.sigmoid(inputs) + ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") + p_t = p * targets + (1 - p) * (1 - targets) + loss = ce_loss * ((1 - p_t) ** gamma) + + if alpha >= 0: + alpha_t = alpha * targets + (1 - alpha) * (1 - targets) + loss = alpha_t * loss + return loss diff --git a/OpenTAD/opentad/models/losses/iou_loss.py b/OpenTAD/opentad/models/losses/iou_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb1325b0bce2149912090fadfa7974bcefaab0c --- /dev/null +++ b/OpenTAD/opentad/models/losses/iou_loss.py @@ -0,0 +1,47 @@ +import torch +import torch.nn as nn +from ..builder import LOSSES +from ..utils.iou_tools import compute_diou_torch, compute_giou_torch + + +@LOSSES.register_module() +class DIOULoss(nn.Module): + def __init__(self): + super(DIOULoss, self).__init__() + + def forward( + self, + input_bboxes: torch.Tensor, + target_bboxes: torch.Tensor, + reduction: str = "none", + eps: float = 1e-8, + ) -> torch.Tensor: + loss = 1 - torch.diag(compute_diou_torch(target_bboxes, input_bboxes)) + + if reduction == "mean": + loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() + elif reduction == "sum": + loss = loss.sum() + + return loss + + +@LOSSES.register_module() +class GIOULoss(nn.Module): + def __init__(self): + super(GIOULoss, self).__init__() + + def forward( + self, + input_bboxes: torch.Tensor, + target_bboxes: torch.Tensor, + reduction: str = "none", + eps: float = 1e-8, + ) -> torch.Tensor: + loss = 1 - torch.diag(compute_giou_torch(target_bboxes, input_bboxes)) + + if reduction == "mean": + loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() + elif reduction == "sum": + loss = loss.sum() + return loss diff --git a/OpenTAD/opentad/models/losses/scale_invariant_loss.py b/OpenTAD/opentad/models/losses/scale_invariant_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..499b6794664283ffe4d3fc71a0e5839010818c96 --- /dev/null +++ b/OpenTAD/opentad/models/losses/scale_invariant_loss.py @@ -0,0 +1,61 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..builder import LOSSES +from ..utils.iou_tools import compute_iou_torch + + +@LOSSES.register_module() +class ScaleInvariantLoss(nn.Module): + def __init__(self, pos_thresh=0.9, alpha=0.2): + super().__init__() + + self.pos_thresh = pos_thresh + self.alpha = alpha + + @torch.no_grad() + def prepare_targets(self, proposals, gt_segments): + proposals = proposals.to(gt_segments[0].device) # [N,2] + + gt_ious = [] + gt_iou_weights = [] + for gt_segment in gt_segments: + ious = compute_iou_torch(gt_segment, proposals) # [N,M] + gt_iou, max_index = torch.max(ious, dim=1) # [N], [N] + + # gt iou weight + gt_iou_weight = torch.ones_like(gt_iou) + pos_mask = gt_iou > self.pos_thresh + neg_mask = gt_iou <= self.pos_thresh + pos_num = (ious > self.pos_thresh).sum(dim=0) # [N], avoid 0 + + gt_iou_weight[pos_mask] = 1 / pos_num[max_index[pos_mask]].clip(min=1) + gt_iou_weight[neg_mask] = len(gt_segment) / torch.sum(neg_mask) + + gt_ious.append(gt_iou) + gt_iou_weights.append(gt_iou_weight) + + gt_ious = torch.stack(gt_ious) + gt_iou_weights = torch.stack(gt_iou_weights) + return gt_ious, gt_iou_weights + + def forward(self, pred, proposal, gt_segments): + gt_ious, gt_iou_weights = self.prepare_targets(proposal, gt_segments) + + # pred [B, N], this is after the valid mask + pmask = (gt_ious > self.pos_thresh).float() + nmask = (gt_ious <= self.pos_thresh).float() + + loss = F.binary_cross_entropy(pred, pmask, reduction="none") + + num_pos = torch.sum(pmask) + num_neg = torch.sum(nmask) + + if (num_pos == 0) or (num_neg == 0): + return torch.mean(loss) + else: + coef_pos = 0.5 * (num_pos + num_neg) / num_pos + coef_neg = 0.5 * (num_pos + num_neg) / num_neg + coef = self.alpha * pmask + (1 - self.alpha) * nmask + loss = torch.sum(coef * loss * gt_iou_weights) / pred.shape[0] + return loss, gt_ious diff --git a/OpenTAD/opentad/models/losses/set_loss.py b/OpenTAD/opentad/models/losses/set_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a832be9ff7b4f59864697c1d5935bae0b6500d23 --- /dev/null +++ b/OpenTAD/opentad/models/losses/set_loss.py @@ -0,0 +1,335 @@ +from typing import List +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.distributed as dist + +from .focal_loss import sigmoid_focal_loss +from ..builder import LOSSES, build_matcher +from ..utils.bbox_tools import proposal_cw_to_se +from ..utils.iou_tools import compute_giou_torch, compute_iou_torch +from ..utils.misc import convert_gt_to_one_hot + + +@LOSSES.register_module() +class SetCriterion(nn.Module): + """This class computes the loss for Conditional DETR. + The process happens in two steps: + 1) we compute hungarian assignment between ground truth boxes and the outputs of the model + 2) we supervise each pair of matched ground-truth / prediction (supervise class and box) + """ + + def __init__( + self, + num_classes, + matcher, + weight_dict, + losses: List[str] = ["class", "boxes"], + eos_coef: float = 0.1, + loss_class_type: str = "focal_loss", + alpha: float = 0.25, + gamma: float = 2.0, + use_multi_class: bool = True, # for multi-class classification + with_dn: bool = False, + ): + """Create the criterion. + Parameters: + num_classes: number of object categories, omitting the special no-object category + matcher: module able to compute a matching between targets and proposals + weight_dict: dict containing as key the names of the losses and as values their relative weight. + losses: list of all the losses to be applied. See get_loss for list of available losses. + focal_alpha: alpha in Focal Loss + """ + super().__init__() + self.num_classes = num_classes + self.matcher = build_matcher(matcher) + self.weight_dict = weight_dict + self.losses = losses + self.alpha = alpha + self.gamma = gamma + self.eos_coef = eos_coef + self.loss_class_type = loss_class_type + self.use_multi_class = use_multi_class + self.with_dn = with_dn + assert loss_class_type in [ + "ce_loss", + "focal_loss", + ], "only support ce loss and focal loss for computing classification loss" + + if self.loss_class_type == "ce_loss": + empty_weight = torch.ones(self.num_classes + 1) + empty_weight[-1] = eos_coef + self.register_buffer("empty_weight", empty_weight) + + def loss_labels(self, outputs, gt_segments, gt_labels, indices, num_boxes): + """Classification loss (Binary focal loss) + targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes] + """ + assert "pred_logits" in outputs + src_logits = outputs["pred_logits"] + + idx = self._get_src_permutation_idx(indices) + target_classes_o = torch.cat([t[J] for t, (_, J) in zip(gt_labels, indices)]) + + # Computation classification loss + if self.loss_class_type == "ce_loss": + target_classes = torch.full( + src_logits.shape[:2], + self.num_classes, + dtype=torch.int64, + device=src_logits.device, + ) + target_classes[idx] = target_classes_o + loss_class = F.cross_entropy(src_logits.transpose(1, 2), target_classes, self.empty_weight) + elif self.loss_class_type == "focal_loss": + # src_logits: (b, num_queries, num_classes) = (2, 300, 80) + # target_classes_one_hot = (2, 300, 80) + if self.use_multi_class: + target_classes_onehot = torch.zeros(src_logits.shape, dtype=torch.int64, device=src_logits.device) + target_classes_onehot[idx] = target_classes_o # [B,Q,num_classes] + target_classes_onehot = target_classes_onehot.float() + else: + target_classes = torch.full( + src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device + ) + target_classes[idx] = target_classes_o + + target_classes_onehot = torch.zeros( + [src_logits.shape[0], src_logits.shape[1], src_logits.shape[2] + 1], + dtype=src_logits.dtype, + layout=src_logits.layout, + device=src_logits.device, + ) + target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1) + target_classes_onehot = target_classes_onehot[:, :, :-1] + + loss_class = sigmoid_focal_loss( + src_logits, + target_classes_onehot, + alpha=self.alpha, + gamma=self.gamma, + ) + loss_class = loss_class.mean(1).sum() / num_boxes + loss_class *= src_logits.shape[1] + + losses = {"loss_class": loss_class} + return losses + + def loss_boxes(self, outputs, gt_segments, gt_labels, indices, num_boxes): + """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss + targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4] + The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size. + """ + assert "pred_boxes" in outputs + idx = self._get_src_permutation_idx(indices) + src_boxes = outputs["pred_boxes"][idx] + target_boxes = torch.cat([t[i] for t, (_, i) in zip(gt_segments, indices)], dim=0) + + loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction="none") + + losses = {} + losses["loss_bbox"] = loss_bbox.sum() / num_boxes + + loss_giou = 1 - torch.diag(compute_giou_torch(proposal_cw_to_se(target_boxes), proposal_cw_to_se(src_boxes))) + losses["loss_giou"] = loss_giou.sum() / num_boxes + return losses + + def _get_src_permutation_idx(self, indices): + # permute predictions following indices + batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)]) + src_idx = torch.cat([src for (src, _) in indices]) + return batch_idx, src_idx + + def _get_tgt_permutation_idx(self, indices): + # permute targets following indices + batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)]) + tgt_idx = torch.cat([tgt for (_, tgt) in indices]) + return batch_idx, tgt_idx + + def get_loss(self, loss, outputs, gt_segments, gt_labels, indices, num_boxes, **kwargs): + loss_map = { + "class": self.loss_labels, + "boxes": self.loss_boxes, + } + assert loss in loss_map, f"do you really want to compute {loss} loss?" + return loss_map[loss](outputs, gt_segments, gt_labels, indices, num_boxes, **kwargs) + + def get_encoder_loss(self, enc_outputs, gt_segments, gt_labels, indices, num_boxes, **kwargs): + pass + + def forward(self, outputs, gt_segments, gt_labels, dn_metas=None, return_indices=False): + """This performs the loss computation. + Parameters: + outputs: dict of tensors, see the output specification of the model for the format + targets: list of dicts, such that len(targets) == batch_size. + The expected keys in each dict depends on the losses applied, see each loss' doc + return_indices: used for vis. if True, the layer0-5 indices will be returned as well. + """ + + if self.loss_class_type == "focal_loss" and self.use_multi_class: + # deal with multi class issues happened in THUMOS + gt_segments, gt_labels = convert_gt_to_one_hot(gt_segments, gt_labels, num_classes=self.num_classes) + + # Retrieve the matching between the outputs of the last layer and the targets + outputs_without_aux = {k: v for k, v in outputs.items() if k != "aux_outputs" and k != "enc_outputs"} + indices = self.matcher(outputs_without_aux, gt_segments, gt_labels) + if return_indices: + indices0_copy = indices + indices_list = [] + + # Compute the average number of target boxes across all nodes, for normalization purposes + num_boxes = sum(t.shape[0] for t in gt_segments) + num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device) + dist.all_reduce(num_boxes) + num_boxes = torch.clamp(num_boxes / dist.get_world_size(), min=1).item() + + # Compute all the requested losses + losses = {} + for loss in self.losses: + losses.update(self.get_loss(loss, outputs, gt_segments, gt_labels, indices, num_boxes)) + + # In case of auxiliary losses, we repeat this process with the output of each intermediate layer. + if "aux_outputs" in outputs: + for i, aux_outputs in enumerate(outputs["aux_outputs"]): + indices = self.matcher(aux_outputs, gt_segments, gt_labels) + if return_indices: + indices_list.append(indices) + for loss in self.losses: + l_dict = self.get_loss(loss, aux_outputs, gt_segments, gt_labels, indices, num_boxes) + l_dict = {k + f"_{i}": v for k, v in l_dict.items()} + losses.update(l_dict) + + # denoising loss + if self.with_dn: + aux_num = len(outputs["aux_outputs"]) if "aux_outputs" in outputs else 0 + losses.update(self.get_dn_loss(dn_metas, gt_segments, gt_labels, aux_num, num_boxes)) + + # Compute losses for two-stage deformable-detr / DINO + if "enc_outputs" in outputs: + losses.update(self.get_encoder_loss(outputs["enc_outputs"], gt_segments, gt_labels, num_boxes)) + + for k in losses.keys(): + for kk in self.weight_dict.keys(): + if kk in k: + losses[k] *= self.weight_dict[kk] + + if return_indices: + indices_list.append(indices0_copy) + return losses, indices_list + else: + return losses + + +@LOSSES.register_module() +class DeformableSetCriterion(SetCriterion): + def get_encoder_loss(self, enc_outputs, gt_segments, gt_labels, num_boxes, **kwargs): + bin_labels = [] + for gt_label in gt_labels: + bin_label = torch.zeros_like(gt_label) + bin_label[:, 0] = 1 # deformable-detr only uses binary classification for encoder output + bin_labels.append(bin_label) + indices = self.matcher(enc_outputs, gt_segments, bin_labels) + encoder_losses = {} + for loss in self.losses: + l_dict = self.get_loss(loss, enc_outputs, gt_segments, bin_labels, indices, num_boxes, **kwargs) + l_dict = {k + "_enc": v for k, v in l_dict.items()} + encoder_losses.update(l_dict) + return encoder_losses + + +@LOSSES.register_module() +class TadTRSetCriterion(SetCriterion): + def loss_boxes(self, outputs, gt_segments, gt_labels, indices, num_boxes): + """Compute the losses related to the bounding boxes, the L1 regression loss and the IoU loss + targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4] + The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size. + """ + assert "pred_boxes" in outputs + idx = self._get_src_permutation_idx(indices) + src_boxes = outputs["pred_boxes"][idx] + target_boxes = torch.cat([t[i] for t, (_, i) in zip(gt_segments, indices)], dim=0) + + loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction="none") + + losses = {} + losses["loss_bbox"] = loss_bbox.sum() / num_boxes + + loss_iou = 1 - torch.diag(compute_iou_torch(proposal_cw_to_se(target_boxes), proposal_cw_to_se(src_boxes))) + losses["loss_iou"] = loss_iou.sum() / num_boxes + return losses + + def loss_actionness(self, outputs, gt_segments, gt_labels, indices, num_boxes): + """Compute the actionness regression loss + targets dicts must contain the key "segments" containing a tensor of dim [nb_target_segments, 2] + The target segments are expected in format (center, width), normalized by the video length. + """ + assert "pred_actionness" in outputs + + # Compute GT IoU + gt_iou = [] + for gt_segment, pred_boxes in zip(gt_segments, outputs["pred_boxes"]): + iou = compute_iou_torch(proposal_cw_to_se(gt_segment), proposal_cw_to_se(pred_boxes)) + gt_iou.append(iou.max(dim=1)[0]) + gt_iou = torch.cat(gt_iou, dim=0) # [bs*num_queries] + + pred_iou = outputs["pred_actionness"].view(-1) # [bs*num_queries] + loss_actionness = F.l1_loss(pred_iou, gt_iou.detach()) + + losses = {} + losses["loss_actionness"] = loss_actionness + return losses + + def forward(self, outputs, gt_segments, gt_labels, return_indices=False): + """This performs the loss computation. + Parameters: + outputs: dict of tensors, see the output specification of the model for the format + targets: list of dicts, such that len(targets) == batch_size. + The expected keys in each dict depends on the losses applied, see each loss' doc + return_indices: used for vis. if True, the layer0-5 indices will be returned as well. + """ + if self.loss_class_type == "focal_loss" and self.use_multi_class: + # deal with multi class issues happened in THUMOS + gt_segments, gt_labels = convert_gt_to_one_hot(gt_segments, gt_labels, num_classes=self.num_classes) + + # Retrieve the matching between the outputs of the last layer and the targets + outputs_without_aux = {k: v for k, v in outputs.items() if k != "aux_outputs" and k != "enc_outputs"} + indices = self.matcher(outputs_without_aux, gt_segments, gt_labels) + if return_indices: + indices0_copy = indices + indices_list = [] + + # Compute the average number of target boxes across all nodes, for normalization purposes + num_boxes = sum(t.shape[0] for t in gt_segments) + num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device) + dist.all_reduce(num_boxes) + num_boxes = torch.clamp(num_boxes / dist.get_world_size(), min=1).item() + + # Compute all the requested losses + losses = {} + for loss in self.losses: + losses.update(self.get_loss(loss, outputs, gt_segments, gt_labels, indices, num_boxes)) + + # Compute the actionness loss + losses.update(self.loss_actionness(outputs, gt_segments, gt_labels, indices, num_boxes)) + + # In case of auxiliary losses, we repeat this process with the output of each intermediate layer. + if "aux_outputs" in outputs: + for i, aux_outputs in enumerate(outputs["aux_outputs"]): + indices = self.matcher(aux_outputs, gt_segments, gt_labels) + if return_indices: + indices_list.append(indices) + for loss in self.losses: + l_dict = self.get_loss(loss, aux_outputs, gt_segments, gt_labels, indices, num_boxes) + l_dict = {k + f"_{i}": v for k, v in l_dict.items()} + losses.update(l_dict) + + for k in losses.keys(): + for kk in self.weight_dict.keys(): + if kk in k: + losses[k] *= self.weight_dict[kk] + + if return_indices: + indices_list.append(indices0_copy) + return losses, indices_list + else: + return losses diff --git a/OpenTAD/opentad/models/losses/smooth_l1_loss.py b/OpenTAD/opentad/models/losses/smooth_l1_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..eb5def28997ec6db1cb479d5cd70c8f4f921a883 --- /dev/null +++ b/OpenTAD/opentad/models/losses/smooth_l1_loss.py @@ -0,0 +1,25 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..builder import LOSSES + + +@LOSSES.register_module() +class SmoothL1Loss(nn.Module): + def __init__(self): + super().__init__() + + def forward( + self, + inputs: torch.Tensor, + targets: torch.Tensor, + reduction: str = "sum", + eps: float = 1e-8, + ) -> torch.Tensor: + loss = F.smooth_l1_loss(inputs, targets, reduction="none") + + if reduction == "mean": + loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() + elif reduction == "sum": + loss = loss.sum() + return loss diff --git a/OpenTAD/opentad/models/necks/__init__.py b/OpenTAD/opentad/models/necks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b23e0e5df54659744dea4173e0876aef5dfd612f --- /dev/null +++ b/OpenTAD/opentad/models/necks/__init__.py @@ -0,0 +1,6 @@ +from .fpn import FPN, FPNIdentity +from .etad_lstm import LSTMNeck +from .afsd_neck import AFSDNeck +from .vsgn_fpn import VSGNFPN + +__all__ = ["LSTMNeck", "AFSDNeck", "FPN", "FPNIdentity", "VSGNFPN"] diff --git a/OpenTAD/opentad/models/necks/afsd_neck.py b/OpenTAD/opentad/models/necks/afsd_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..51d1c28d7aa3cddd537a48b15c643973001a4930 --- /dev/null +++ b/OpenTAD/opentad/models/necks/afsd_neck.py @@ -0,0 +1,219 @@ +import numpy as np +import torch.nn as nn +import torch.nn.functional as F + +from ..builder import NECKS + + +@NECKS.register_module() +class AFSDNeck(nn.Module): + def __init__(self, in_channels, out_channels, frame_num, layer_num=6, e2e=False): + super().__init__() + + self.frame_num = frame_num + self.pyramids = nn.ModuleList() + + if e2e: + input_conv = Unit3D( + in_channels=in_channels, + output_channels=out_channels, + kernel_shape=[1, 3, 3], + use_batch_norm=False, + padding="spatial_valid", + use_bias=True, + activation_fn=None, + ) + else: + # feature-based model + input_conv = Unit1D( + in_channels=in_channels, + output_channels=out_channels, + kernel_shape=1, + stride=1, + use_bias=True, + activation_fn=None, + ) + + self.pyramids.append( + nn.Sequential( + input_conv, + nn.GroupNorm(32, out_channels), + nn.ReLU(inplace=True), + ) + ) + for _ in range(1, layer_num): + self.pyramids.append( + nn.Sequential( + Unit1D( + in_channels=out_channels, + output_channels=out_channels, + kernel_shape=3, + stride=2, + use_bias=True, + activation_fn=None, + ), + nn.GroupNorm(32, out_channels), + nn.ReLU(inplace=True), + ) + ) + + self.deconv = nn.Sequential( + Unit1D(out_channels, out_channels, 3, activation_fn=None), + nn.GroupNorm(32, out_channels), + nn.ReLU(inplace=True), + Unit1D(out_channels, out_channels, 3, activation_fn=None), + nn.GroupNorm(32, out_channels), + nn.ReLU(inplace=True), + Unit1D(out_channels, out_channels, 1, activation_fn=None), + nn.GroupNorm(32, out_channels), + nn.ReLU(inplace=True), + ) + + # init the weights + self.init_weights() + + def init_weights(self): + def glorot_uniform_(tensor): + fan_in, fan_out = nn.init._calculate_fan_in_and_fan_out(tensor) + scale = 1.0 + scale /= max(1.0, (fan_in + fan_out) / 2.0) + limit = np.sqrt(3.0 * scale) + return nn.init._no_grad_uniform_(tensor, -limit, limit) + + for m in self.modules(): + if isinstance(m, (nn.Conv1d, nn.Conv3d)): + glorot_uniform_(m.weight) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.GroupNorm): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def forward(self, feat, mask): + pyramid_feats = [] + for i, conv in enumerate(self.pyramids): + if i == 0: + x = conv(feat) + x = x.squeeze(-1).squeeze(-1) * mask[:, None, :].detach().float() + else: + mask = F.max_pool1d(mask.unsqueeze(1).float(), kernel_size=2, stride=2).squeeze(1).bool() + x = conv(x) * mask[:, None, :].detach().float() + pyramid_feats.append(x) # [B, C, 96/48/24/12/6/3] + + frame_level_feat = pyramid_feats[0].unsqueeze(-1) + frame_level_feat = F.interpolate(frame_level_feat, [self.frame_num, 1]).squeeze(-1) + frame_level_feat = self.deconv(frame_level_feat) # [B, C, 768] + return pyramid_feats, frame_level_feat + + +class Unit3D(nn.Module): + def __init__( + self, + in_channels, + output_channels, + kernel_shape=(1, 1, 1), + stride=(1, 1, 1), + padding="spatial_valid", + activation_fn=F.relu, + use_batch_norm=False, + use_bias=False, + ): + """Initializes Unit3D module.""" + super(Unit3D, self).__init__() + + self._output_channels = output_channels + self._kernel_shape = kernel_shape + self._stride = stride + self._use_batch_norm = use_batch_norm + self._activation_fn = activation_fn + self._use_bias = use_bias + self.padding = padding + + if self._use_batch_norm: + self.bn = nn.BatchNorm3d(self._output_channels, eps=0.001, momentum=0.01) + + self.conv3d = nn.Conv3d( + in_channels=in_channels, + out_channels=self._output_channels, + kernel_size=self._kernel_shape, + stride=self._stride, + padding=0, + bias=self._use_bias, + ) + + def compute_pad(self, dim, s): + if s % self._stride[dim] == 0: + return max(self._kernel_shape[dim] - self._stride[dim], 0) + else: + return max(self._kernel_shape[dim] - (s % self._stride[dim]), 0) + + def forward(self, x): + # compute 'same' padding + if self.padding == "same": + (batch, channel, t, h, w) = x.size() + pad_t = self.compute_pad(0, t) + pad_h = self.compute_pad(1, h) + pad_w = self.compute_pad(2, w) + + pad_t_f = pad_t // 2 + pad_t_b = pad_t - pad_t_f + pad_h_f = pad_h // 2 + pad_h_b = pad_h - pad_h_f + pad_w_f = pad_w // 2 + pad_w_b = pad_w - pad_w_f + + pad = [pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b] + x = F.pad(x, pad) + + if self.padding == "spatial_valid": + (batch, channel, t, h, w) = x.size() + pad_t = self.compute_pad(0, t) + pad_t_f = pad_t // 2 + pad_t_b = pad_t - pad_t_f + + pad = [0, 0, 0, 0, pad_t_f, pad_t_b] + x = F.pad(x, pad) + + x = self.conv3d(x) + if self._use_batch_norm: + x = self.bn(x) + if self._activation_fn is not None: + x = self._activation_fn(x) + return x + + +class Unit1D(nn.Module): + def __init__( + self, + in_channels, + output_channels, + kernel_shape=1, + stride=1, + padding="same", + activation_fn=F.relu, + use_bias=True, + ): + super(Unit1D, self).__init__() + self.conv1d = nn.Conv1d(in_channels, output_channels, kernel_shape, stride, padding=0, bias=use_bias) + self._activation_fn = activation_fn + self._padding = padding + self._stride = stride + self._kernel_shape = kernel_shape + + def compute_pad(self, t): + if t % self._stride == 0: + return max(self._kernel_shape - self._stride, 0) + else: + return max(self._kernel_shape - (t % self._stride), 0) + + def forward(self, x): + if self._padding == "same": + batch, channel, t = x.size() + pad_t = self.compute_pad(t) + pad_t_f = pad_t // 2 + pad_t_b = pad_t - pad_t_f + x = F.pad(x, [pad_t_f, pad_t_b]) + x = self.conv1d(x) + if self._activation_fn is not None: + x = self._activation_fn(x) + return x diff --git a/OpenTAD/opentad/models/necks/etad_lstm.py b/OpenTAD/opentad/models/necks/etad_lstm.py new file mode 100644 index 0000000000000000000000000000000000000000..185f302e90b642c3b137ca1c91a7bca3884e5333 --- /dev/null +++ b/OpenTAD/opentad/models/necks/etad_lstm.py @@ -0,0 +1,85 @@ +import torch +import torch.nn as nn +from ..builder import NECKS +from ..bricks import ConvModule + + +@NECKS.register_module() +class LSTMNeck(nn.Module): + def __init__( + self, + in_channels, + out_channels, + conv_cfg=dict(groups=4), + norm_cfg=dict(type="GN", num_groups=16), + ): + super().__init__() + + self.mem_f = nn.LSTM(input_size=in_channels, hidden_size=in_channels, num_layers=1) + self.mem_b = nn.LSTM(input_size=in_channels, hidden_size=in_channels, num_layers=1) + + self.layer2_f = ConvModule( + in_channels, + in_channels // 2, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + + self.layer2_b = ConvModule( + in_channels, + in_channels // 2, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + + self.layer2_d = ConvModule( + in_channels, + in_channels, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + + self.layer3 = ConvModule( + in_channels * 2, + out_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + + def forward(self, x, mask): + # x shape [B,C,T] + + # flatten param for multi GPU training + self.mem_f.flatten_parameters() + self.mem_b.flatten_parameters() + + # memory + x_f, _ = self.mem_f(x.permute(2, 0, 1)) # [T,B,C] + x_b, _ = self.mem_b(x.permute(2, 0, 1).flip(dims=[0])) # [T,B,C] + + # layer 2 + x_f, _ = self.layer2_f(x_f.permute(1, 2, 0), mask) + x_b, _ = self.layer2_b(x_b.flip(dims=[0]).permute(1, 2, 0), mask) + x, _ = self.layer2_d(x, mask) + + x = torch.cat((x_f, x, x_b), dim=1) + + # layer 3 + x, mask = self.layer3(x, mask) # [B,C,T] + return x, mask diff --git a/OpenTAD/opentad/models/necks/fpn.py b/OpenTAD/opentad/models/necks/fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..18c2e881ae7e9f52fc17447a519e341d71aa0ffb --- /dev/null +++ b/OpenTAD/opentad/models/necks/fpn.py @@ -0,0 +1,127 @@ +import torch.nn as nn +import torch.nn.functional as F +import copy + +from ..bricks import ConvModule +from ..builder import NECKS + + +@NECKS.register_module() +class FPN(nn.Module): + def __init__( + self, + in_channels, + out_channels, + num_levels, + norm_cfg=None, + ): + super().__init__() + + self.lateral_convs = nn.ModuleList() + self.fpn_convs = nn.ModuleList() + + if isinstance(in_channels, int): + in_channels = [in_channels] * num_levels + + for i in range(num_levels): + self.lateral_convs.append( + ConvModule( + in_channels[i], + out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + ) + ) + self.fpn_convs.append( + ConvModule( + out_channels, + out_channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg, + ) + ) + + def forward(self, input_list, mask_list): + assert len(input_list) == len(self.lateral_convs) + + # build laterals + laterals = [self.lateral_convs[i](input_list[i], mask_list[i])[0] for i in range(len(self.lateral_convs))] + + # build top-down path + for i in range(len(laterals) - 1, 0, -1): + laterals[i - 1] += F.interpolate(laterals[i], scale_factor=2, mode="nearest") + + # build outputs + fpn_outs = [self.fpn_convs[i](laterals[i], mask_list[i])[0] for i in range(len(laterals))] + return fpn_outs, mask_list + + +@NECKS.register_module() +class FPNIdentity(nn.Module): + def __init__( + self, + in_channels, # input feature channels, len(in_channels) = #levels + out_channels, # output feature channel + num_levels=0, + scale_factor=2.0, # downsampling rate between two fpn levels + start_level=0, # start fpn level + end_level=-1, # end fpn level + norm_cfg=dict(type="LN"), # if no norm, set to none + ): + super().__init__() + + self.in_channels = [in_channels] * num_levels + self.out_channel = out_channels + self.scale_factor = scale_factor + + self.start_level = start_level + if end_level == -1: + self.end_level = len(self.in_channels) + else: + self.end_level = end_level + assert self.end_level <= len(self.in_channels) + assert (self.start_level >= 0) and (self.start_level < self.end_level) + + if norm_cfg is not None: + norm_cfg = copy.copy(norm_cfg) # make a copy + norm_type = norm_cfg["type"] + norm_cfg.pop("type") + self.norm_type = norm_type + else: + self.norm_type = None + + self.fpn_norms = nn.ModuleList() + for i in range(self.start_level, self.end_level): + # check feat dims + assert self.in_channels[i] == self.out_channel + + if self.norm_type == "BN": + fpn_norm = nn.BatchNorm1d(num_features=out_channels, **norm_cfg) + elif self.norm_type == "GN": + fpn_norm = nn.GroupNorm(num_channels=out_channels, **norm_cfg) + elif self.norm_type == "LN": + fpn_norm = nn.LayerNorm(out_channels) + else: + assert self.norm_type is None + fpn_norm = nn.Identity() + self.fpn_norms.append(fpn_norm) + + def forward(self, inputs, fpn_masks): + # inputs must be a list / tuple + assert len(inputs) == len(self.in_channels) + assert len(fpn_masks) == len(self.in_channels) + + # apply norms, fpn_masks will remain the same with 1x1 convs + fpn_feats = tuple() + new_fpn_masks = tuple() + for i in range(len(self.fpn_norms)): + x = inputs[i + self.start_level] + if self.norm_type == "LN": + x = self.fpn_norms[i](x.permute(0, 2, 1)).permute(0, 2, 1) + else: + x = self.fpn_norms[i](x) + fpn_feats += (x,) + new_fpn_masks += (fpn_masks[i + self.start_level],) + + return fpn_feats, new_fpn_masks diff --git a/OpenTAD/opentad/models/necks/vsgn_fpn.py b/OpenTAD/opentad/models/necks/vsgn_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..7c3d8f9c406cf6cc702b26a6ca60b12c7b2c57a3 --- /dev/null +++ b/OpenTAD/opentad/models/necks/vsgn_fpn.py @@ -0,0 +1,110 @@ +import torch.nn as nn +from ..builder import NECKS + + +@NECKS.register_module() +class VSGNFPN(nn.Module): + def __init__( + self, + in_channels, + out_channels, + num_levels, + scale_factor=2, + ): + super(VSGNFPN, self).__init__() + + self.num_levels = num_levels + self.scale_factor = scale_factor + + # Transit from encoder to decoder + self.levels_transit = self._make_levels_same( + in_channels=in_channels, + out_channels=out_channels, + ) + + # Upsampling modules by fusing encoder features and decoder features + self.levels_enc = nn.ModuleList() + for _ in range(self.num_levels - 1): + self.levels_enc.append( + self._make_levels_same( + in_channels=in_channels, + out_channels=out_channels, + ) + ) + + self.levels_dec = nn.ModuleList() + for _ in range(self.num_levels - 1): + self.levels_dec.append( + self._make_levels_up( + in_channels=in_channels, + out_channels=out_channels, + stride=scale_factor, + output_padding=1, + ) + ) + + self.levels_fuse = nn.ModuleList() + for _ in range(self.num_levels - 1): + self.levels_fuse.append( + self._make_levels_same( + in_channels=in_channels, + out_channels=out_channels, + ) + ) + + def _make_levels_up(self, in_channels, out_channels, stride=2, output_padding=1): + return nn.Sequential( + nn.ConvTranspose1d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + padding=1, + output_padding=output_padding, + groups=1, + ), + nn.ReLU(inplace=True), + ) + + def _make_levels_same(self, in_channels, out_channels): + return nn.Sequential( + nn.Conv1d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=1, + padding=1, + groups=1, + ), + nn.ReLU(inplace=True), + ) + + def forward_one_layer(self, module_enc, module_dec, module_fuse, input_enc, input_dec): + feat_enc = module_enc(input_enc) + feat_dec = module_dec(input_dec) + return module_fuse(feat_enc + feat_dec) + + def forward(self, feat_list, mask_list): + feats = [] + + # First decoder level + feats.append(self.levels_transit(feat_list[-1])) + + # The rest decoder levels + for i in range(1, self.num_levels): + feat = self.forward_one_layer( + self.levels_enc[i - 1], + self.levels_dec[i - 1], + self.levels_fuse[i - 1], + feat_list[::-1][i], + feats[i - 1], + ) + feats.append(feat) + + # Reverse the order of feats + feats = feats[::-1] # [B,C,T], [B,C,T//2], [B,C,T//4] ... + + # Masking + for i in range(len(feats)): + feats[i] = feats[i] * mask_list[i].unsqueeze(1).float().detach() + return feats, mask_list diff --git a/OpenTAD/opentad/models/projections/__init__.py b/OpenTAD/opentad/models/projections/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..84c34d7a13283195ef673d569b3d132c0e72fef3 --- /dev/null +++ b/OpenTAD/opentad/models/projections/__init__.py @@ -0,0 +1,18 @@ +from .base import ConvSingleProj, ConvPyramidProj +from .actionformer_proj import Conv1DTransformerProj +from .tridet_proj import TriDetProj +from .temporalmaxer_proj import TemporalMaxerProj +from .vsgn_proj import VSGNPyramidProj +from .mlp_proj import MLPPyramidProj +from .mamba_proj import MambaProj + +__all__ = [ + "ConvSingleProj", + "ConvPyramidProj", + "Conv1DTransformerProj", + "TriDetProj", + "TemporalMaxerProj", + "VSGNPyramidProj", + "MLPPyramidProj", + "MambaProj", +] diff --git a/OpenTAD/opentad/models/projections/actionformer_proj.py b/OpenTAD/opentad/models/projections/actionformer_proj.py new file mode 100644 index 0000000000000000000000000000000000000000..a229edb32989db5ec5efb38228d1c2f18466ee6a --- /dev/null +++ b/OpenTAD/opentad/models/projections/actionformer_proj.py @@ -0,0 +1,186 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from ..bricks import ConvModule, TransformerBlock +from ..builder import PROJECTIONS + + +@PROJECTIONS.register_module() +class Conv1DTransformerProj(nn.Module): + def __init__( + self, + in_channels, + out_channels, + arch=(2, 2, 5), # (#convs, #stem transformers, #branch transformers) + conv_cfg=None, # kernel_size proj_pdrop + norm_cfg=None, + attn_cfg=None, # n_head n_mha_win_size attn_pdrop + path_pdrop=0.0, # dropout rate for drop path + use_abs_pe=False, # use absolute position embedding + max_seq_len=2304, + input_pdrop=0.0, # drop out the input feature + ): + super().__init__() + assert len(arch) == 3 + + self.in_channels = in_channels + self.out_channels = out_channels + self.arch = arch + self.kernel_size = conv_cfg["kernel_size"] + self.proj_pdrop = conv_cfg["proj_pdrop"] + self.scale_factor = 2 # as default + self.n_mha_win_size = attn_cfg["n_mha_win_size"] + self.n_head = attn_cfg["n_head"] + self.attn_pdrop = 0.0 # as default + self.path_pdrop = path_pdrop + self.with_norm = norm_cfg is not None + self.use_abs_pe = use_abs_pe + self.max_seq_len = max_seq_len + + self.input_pdrop = nn.Dropout1d(p=input_pdrop) if input_pdrop > 0 else None + + if isinstance(self.n_mha_win_size, int): + self.mha_win_size = [self.n_mha_win_size] * (1 + arch[-1]) + else: + assert len(self.n_mha_win_size) == (1 + arch[-1]) + self.mha_win_size = self.n_mha_win_size + + if isinstance(self.in_channels, (list, tuple)): + assert isinstance(self.out_channels, (list, tuple)) and len(self.in_channels) == len(self.out_channels) + self.proj = nn.ModuleList([]) + for n_in, n_out in zip(self.in_channels, self.out_channels): + self.proj.append( + ConvModule( + n_in, + n_out, + kernel_size=1, + stride=1, + padding=0, + ) + ) + in_channels = out_channels = sum(self.out_channels) + else: + self.proj = None + + # position embedding (1, C, T), rescaled by 1/sqrt(n_embed) + if self.use_abs_pe: + pos_embed = get_sinusoid_encoding(self.max_seq_len, out_channels) / (out_channels**0.5) + self.register_buffer("pos_embed", pos_embed, persistent=False) + + # embedding network using convs + self.embed = nn.ModuleList() + for i in range(arch[0]): + self.embed.append( + ConvModule( + in_channels if i == 0 else out_channels, + out_channels, + kernel_size=self.kernel_size, + stride=1, + padding=self.kernel_size // 2, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + ) + + # stem network using (vanilla) transformer + self.stem = nn.ModuleList() + for idx in range(arch[1]): + self.stem.append( + TransformerBlock( + out_channels, + self.n_head, + n_ds_strides=(1, 1), + attn_pdrop=self.attn_pdrop, + proj_pdrop=self.proj_pdrop, + path_pdrop=self.path_pdrop, + mha_win_size=self.mha_win_size[0], + ) + ) + + # main branch using transformer with pooling + self.branch = nn.ModuleList() + for idx in range(arch[2]): + self.branch.append( + TransformerBlock( + out_channels, + self.n_head, + n_ds_strides=(self.scale_factor, self.scale_factor), + attn_pdrop=self.attn_pdrop, + proj_pdrop=self.proj_pdrop, + path_pdrop=self.path_pdrop, + mha_win_size=self.mha_win_size[1 + idx], + ) + ) + + # init weights + self.apply(self.__init_weights__) + + def __init_weights__(self, module): + # set nn.Linear/nn.Conv1d bias term to 0 + if isinstance(module, (nn.Linear, nn.Conv1d)): + if module.bias is not None: + torch.nn.init.constant_(module.bias, 0.0) + + def forward(self, x, mask): + # x: batch size, feature channel, sequence length, + # mask: batch size, sequence length (bool) + + # feature projection + if self.proj is not None: + x = torch.cat([proj(s, mask)[0] for proj, s in zip(self.proj, x.split(self.in_channels, dim=1))], dim=1) + + # drop out input if needed + if self.input_pdrop is not None: + x = self.input_pdrop(x) + + # embedding network + for idx in range(len(self.embed)): + x, mask = self.embed[idx](x, mask) + + # training: using fixed length position embeddings + if self.use_abs_pe and self.training: + assert x.shape[-1] <= self.max_seq_len, "Reached max length." + pe = self.pos_embed + # add pe to x + x = x + pe[:, :, : x.shape[-1]] * mask.unsqueeze(1).to(x.dtype) + + # inference: re-interpolate position embeddings for over-length sequences + if self.use_abs_pe and (not self.training): + if x.shape[-1] >= self.max_seq_len: + pe = F.interpolate(self.pos_embed, x.shape[-1], mode="linear", align_corners=False) + else: + pe = self.pos_embed + # add pe to x + x = x + pe[:, :, : x.shape[-1]] * mask.unsqueeze(1).to(x.dtype) + + # stem transformer + for idx in range(len(self.stem)): + x, mask = self.stem[idx](x, mask) + + # prep for outputs + out_feats = (x,) + out_masks = (mask,) + + # main branch with downsampling + for idx in range(len(self.branch)): + x, mask = self.branch[idx](x, mask) + out_feats += (x,) + out_masks += (mask,) + + return out_feats, out_masks + + +def get_sinusoid_encoding(n_position, d_hid): + """Sinusoid position encoding table""" + + def get_position_angle_vec(position): + return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)] + + sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)]) + sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i + sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1 + + # return a tensor of size 1 C T + return torch.FloatTensor(sinusoid_table).unsqueeze(0).transpose(1, 2) diff --git a/OpenTAD/opentad/models/projections/base.py b/OpenTAD/opentad/models/projections/base.py new file mode 100644 index 0000000000000000000000000000000000000000..43be8b3edab2641f9ea1efe19bc28402a396e13b --- /dev/null +++ b/OpenTAD/opentad/models/projections/base.py @@ -0,0 +1,147 @@ +import torch.nn as nn +import torch.nn.functional as F +from .actionformer_proj import get_sinusoid_encoding +from ..builder import PROJECTIONS +from ..bricks import ConvModule + + +@PROJECTIONS.register_module() +class ConvSingleProj(nn.Module): + def __init__( + self, + in_channels, + out_channels, + num_convs, + conv_cfg=None, + norm_cfg=None, + act_cfg=dict(type="relu"), + drop_out=None, + ): + super().__init__() + assert num_convs > 0 + self.drop_out = nn.Dropout1d(p=drop_out) if drop_out is not None else None + + self.convs = nn.ModuleList() + for i in range(num_convs): + self.convs.append( + ConvModule( + in_channels if i == 0 else out_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + ) + ) + + def forward(self, x, mask): + # x shape [B,C,T], mask [B,T] + + if self.drop_out is not None: + x = self.drop_out(x) + + for conv in self.convs: + x, mask = conv(x, mask) + return x, mask + + +@PROJECTIONS.register_module() +class ConvPyramidProj(nn.Module): + def __init__( + self, + in_channels, + out_channels, + arch=(2, 5), # (stem convs, downsample levels) + conv_cfg=None, + norm_cfg=dict(type="LN"), + drop_out=0.0, + drop_path=0.0, + use_abs_pe=False, + max_seq_len=-1, + ): + super().__init__() + + assert len(arch) == 2 + assert arch[1] > 0 + self.arch = arch + self.use_abs_pe = use_abs_pe + self.max_seq_len = max_seq_len + + self.drop_out = nn.Dropout1d(p=drop_out) if drop_out > 0 else None + + # projection convs without downsampling + self.stem_convs = nn.ModuleList() + for i in range(arch[0]): + self.stem_convs.append( + ConvModule( + in_channels if i == 0 else out_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + ) + + # position embedding (1, C, T), rescaled by 1/sqrt(n_embed) + if self.use_abs_pe: + pos_embed = get_sinusoid_encoding(self.max_seq_len, out_channels) / (out_channels**0.5) + self.register_buffer("pos_embed", pos_embed, persistent=False) + + # downsampling for pyramid feature + self.downsampling = nn.MaxPool1d(kernel_size=3, stride=2, padding=1) + + # convs between each level + self.pyramid_convs = nn.ModuleList() + for _ in range(arch[1] + 1): + self.pyramid_convs.append( + ConvModule( + out_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + ) + + def forward(self, x, mask): + # x shape [B,C,T], mask [B,T] + if self.drop_out is not None: + x = self.drop_out(x) + + # stem convs without downsampling + for conv in self.stem_convs: + x, mask = conv(x, mask) + + # add position embedding + if self.use_abs_pe: + if self.training: + assert x.shape[-1] <= self.max_seq_len, "Reached max length." + pe = self.pos_embed + # add pe to x + x = x + pe[:, :, : x.shape[-1]] * mask.unsqueeze(1).to(x.dtype) + else: + if x.shape[-1] >= self.max_seq_len: + pe = F.interpolate(self.pos_embed, x.shape[-1], mode="linear", align_corners=False) + else: + pe = self.pos_embed + x = x + pe[:, :, : x.shape[-1]] * mask.unsqueeze(1).to(x.dtype) + + # downsampling and saving to output + out, out_mask = [], [] + for level in range(self.arch[1] + 1): + if level > 0: + mask = self.downsampling(mask.float()).bool() + x = self.downsampling(x) * mask.unsqueeze(1).to(x.dtype) + + x, mask = self.pyramid_convs[level](x, mask) + out.append(x) + out_mask.append(mask) + return out, out_mask diff --git a/OpenTAD/opentad/models/projections/mamba_proj.py b/OpenTAD/opentad/models/projections/mamba_proj.py new file mode 100644 index 0000000000000000000000000000000000000000..83ec6fb9affd226c1d3f82304b7927d20b6d6239 --- /dev/null +++ b/OpenTAD/opentad/models/projections/mamba_proj.py @@ -0,0 +1,226 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .actionformer_proj import get_sinusoid_encoding +from ..bricks import ConvModule, AffineDropPath +from ..builder import PROJECTIONS + +try: + from mamba_ssm.modules.mamba_simple import Mamba as ViM + from mamba_ssm.modules.mamba_new import Mamba as DBM + + MAMBA_AVAILABLE = True + +except ImportError: + MAMBA_AVAILABLE = False + + +@PROJECTIONS.register_module() +class MambaProj(nn.Module): + """Implementation of Video-Mamba-Suite: https://arxiv.org/abs/2403.09626""" + + def __init__( + self, + in_channels, + out_channels, + arch=(2, 2, 5), # (#convs, #stem transformers, #branch transformers) + conv_cfg=None, # kernel_size proj_pdrop + norm_cfg=None, + use_abs_pe=False, # use absolute position embedding + max_seq_len=2304, + input_pdrop=0.0, # drop out the input feature + mamba_cfg=dict(kernel_size=4, drop_path_rate=0.3, use_mamba_type="dbm"), # default to DBM + ): + super().__init__() + assert ( + MAMBA_AVAILABLE + ), "Please install mamba-ssm to use this module. Check: https://github.com/OpenGVLab/video-mamba-suite" + + assert len(arch) == 3 + + self.in_channels = in_channels + self.out_channels = out_channels + self.arch = arch + self.kernel_size = conv_cfg["kernel_size"] + self.scale_factor = 2 # as default + self.with_norm = norm_cfg is not None + self.use_abs_pe = use_abs_pe + self.max_seq_len = max_seq_len + + self.input_pdrop = nn.Dropout1d(p=input_pdrop) if input_pdrop > 0 else None + + if isinstance(self.in_channels, (list, tuple)): + assert isinstance(self.out_channels, (list, tuple)) and len(self.in_channels) == len(self.out_channels) + self.proj = nn.ModuleList([]) + for n_in, n_out in zip(self.in_channels, self.out_channels): + self.proj.append( + ConvModule( + n_in, + n_out, + kernel_size=1, + stride=1, + padding=0, + ) + ) + in_channels = out_channels = sum(self.out_channels) + else: + self.proj = None + + # position embedding (1, C, T), rescaled by 1/sqrt(n_embed) + if self.use_abs_pe: + pos_embed = get_sinusoid_encoding(self.max_seq_len, out_channels) / (out_channels**0.5) + self.register_buffer("pos_embed", pos_embed, persistent=False) + + # embedding network using convs + self.embed = nn.ModuleList() + for i in range(arch[0]): + self.embed.append( + ConvModule( + in_channels if i == 0 else out_channels, + out_channels, + kernel_size=self.kernel_size, + stride=1, + padding=self.kernel_size // 2, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + ) + + # stem network using (vanilla) transformer + self.stem = nn.ModuleList() + for _ in range(arch[1]): + self.stem.append(MaskMambaBlock(out_channels, **mamba_cfg)) + + # main branch using transformer with pooling + self.branch = nn.ModuleList() + for _ in range(arch[2]): + self.branch.append(MaskMambaBlock(out_channels, n_ds_stride=2, **mamba_cfg)) + + # init weights + self.apply(self.__init_weights__) + + def __init_weights__(self, module): + # set nn.Linear bias term to 0 + if isinstance(module, (nn.Linear, nn.Conv1d)): + if module.bias is not None: + if not getattr(module.bias, "_no_reinit", False): + torch.nn.init.constant_(module.bias, 0.0) + + def forward(self, x, mask): + # x: batch size, feature channel, sequence length, + # mask: batch size, sequence length (bool) + + # feature projection + if self.proj is not None: + x = torch.cat([proj(s, mask)[0] for proj, s in zip(self.proj, x.split(self.in_channels, dim=1))], dim=1) + + # drop out input if needed + if self.input_pdrop is not None: + x = self.input_pdrop(x) + + # embedding network + for idx in range(len(self.embed)): + x, mask = self.embed[idx](x, mask) + + # training: using fixed length position embeddings + if self.use_abs_pe and self.training: + assert x.shape[-1] <= self.max_seq_len, "Reached max length." + pe = self.pos_embed + # add pe to x + x = x + pe[:, :, : x.shape[-1]] * mask.unsqueeze(1).to(x.dtype) + + # inference: re-interpolate position embeddings for over-length sequences + if self.use_abs_pe and (not self.training): + if x.shape[-1] >= self.max_seq_len: + pe = F.interpolate(self.pos_embed, x.shape[-1], mode="linear", align_corners=False) + else: + pe = self.pos_embed + # add pe to x + x = x + pe[:, :, : x.shape[-1]] * mask.unsqueeze(1).to(x.dtype) + + # stem transformer + for idx in range(len(self.stem)): + x, mask = self.stem[idx](x, mask) + + # prep for outputs + out_feats = (x,) + out_masks = (mask,) + + # main branch with downsampling + for idx in range(len(self.branch)): + x, mask = self.branch[idx](x, mask) + out_feats += (x,) + out_masks += (mask,) + + return out_feats, out_masks + + +class MaskMambaBlock(nn.Module): + def __init__( + self, + n_embd, # dimension of the input features + kernel_size=4, # conv kernel size + n_ds_stride=1, # downsampling stride for the current layer + drop_path_rate=0.3, # drop path rate + use_mamba_type="dbm", + ): + super().__init__() + if use_mamba_type == "dbm": + self.mamba = DBM(n_embd, d_conv=kernel_size, use_fast_path=True, expand=1) + elif use_mamba_type == "vim": + # vim + self.mamba = ViM(n_embd, d_conv=kernel_size, bimamba_type="v2", use_fast_path=True) + else: + raise NotImplementedError + if n_ds_stride > 1: + self.downsample = MaxPooler(kernel_size=3, stride=2, padding=1) + else: + self.downsample = None + + self.norm = nn.LayerNorm(n_embd) + + # drop path + if drop_path_rate > 0.0: + self.drop_path = AffineDropPath(n_embd, drop_prob=drop_path_rate) + else: + self.drop_path = nn.Identity() + + def forward(self, x, mask): + res = x + x_ = x.transpose(1, 2) + x_ = self.norm(x_) + x_ = self.mamba(x_).transpose(1, 2) + x = x_ * mask.unsqueeze(1).to(x.dtype) + + x = res + self.drop_path(x) + + if self.downsample is not None: + x, mask = self.downsample(x, mask) + + return x, mask + + +class MaxPooler(nn.Module): + def __init__( + self, + kernel_size, + stride, + padding, + ): + super().__init__() + self.ds_pooling = nn.MaxPool1d(kernel_size, stride=stride, padding=padding) + + self.stride = stride + + def forward(self, x, mask, **kwargs): + if self.stride > 1: + # downsample the mask using nearest neighbor + out_mask = self.ds_pooling(mask.float()).bool() + else: + # masking out the features + out_mask = mask + + out = self.ds_pooling(x) * out_mask.unsqueeze(1).to(x.dtype) + + return out, out_mask.bool() diff --git a/OpenTAD/opentad/models/projections/mlp_proj.py b/OpenTAD/opentad/models/projections/mlp_proj.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ae77a9597c5bfbc6a38d3c858c57ac5532c543 --- /dev/null +++ b/OpenTAD/opentad/models/projections/mlp_proj.py @@ -0,0 +1,106 @@ +import torch.nn as nn +import torch.nn.functional as F +from .actionformer_proj import get_sinusoid_encoding +from ..builder import PROJECTIONS +from ..bricks import ConvModule, ConvFormerBlock + + +@PROJECTIONS.register_module() +class MLPPyramidProj(nn.Module): + def __init__( + self, + in_channels, + out_channels, + arch=(2, 5), # (stem convs, downsample levels) + conv_cfg=None, + norm_cfg=dict(type="LN"), + drop_out=0.0, + drop_path=0.0, + use_abs_pe=False, + max_seq_len=-1, + ): + super().__init__() + + assert len(arch) == 2 + assert arch[1] > 0 + self.arch = arch + self.use_abs_pe = use_abs_pe + self.max_seq_len = max_seq_len + + self.drop_out = nn.Dropout1d(p=drop_out) if drop_out > 0 else None + + # projection convs without downsampling + self.stem_convs = nn.ModuleList() + for i in range(arch[0]): + self.stem_convs.append( + ConvModule( + in_channels if i == 0 else out_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + ) + + # position embedding (1, C, T), rescaled by 1/sqrt(n_embed) + if self.use_abs_pe: + pos_embed = get_sinusoid_encoding(self.max_seq_len, out_channels) / (out_channels**0.5) + self.register_buffer("pos_embed", pos_embed, persistent=False) + + # downsampling for pyramid feature + self.downsampling = nn.MaxPool1d(kernel_size=3, stride=2, padding=1) + + # convs between each level + self.pyramid_convs = nn.ModuleList() + for _ in range(arch[1] + 1): + self.pyramid_convs.append( + # ConvNeXtV2Block( + # dim=out_channels, + # kernel_size=3, + # stride=1, + # drop_path=drop_path, + # ) + ConvFormerBlock( + dim=out_channels, + kernel_size=3, + drop_path=drop_path, + ) + ) + + def forward(self, x, mask): + # x shape [B,C,T], mask [B,T] + if self.drop_out is not None: + x = self.drop_out(x) + + # stem convs without downsampling + for conv in self.stem_convs: + x, mask = conv(x, mask) + + # add position embedding + if self.use_abs_pe: + if self.training: + assert x.shape[-1] <= self.max_seq_len, "Reached max length." + pe = self.pos_embed + # add pe to x + x = x + pe[:, :, : x.shape[-1]] * mask.unsqueeze(1).to(x.dtype) + else: + if x.shape[-1] >= self.max_seq_len: + pe = F.interpolate(self.pos_embed, x.shape[-1], mode="linear", align_corners=False) + else: + pe = self.pos_embed + x = x + pe[:, :, : x.shape[-1]] * mask.unsqueeze(1).to(x.dtype) + + # downsampling and saving to output + out, out_mask = [], [] + for level in range(self.arch[1] + 1): + if level > 0: + mask = self.downsampling(mask.float()).bool() + x = self.downsampling(x) * mask.unsqueeze(1).to(x.dtype) + + x, mask = self.pyramid_convs[level](x, mask) + out.append(x) + out_mask.append(mask) + return out, out_mask diff --git a/OpenTAD/opentad/models/projections/temporalmaxer_proj.py b/OpenTAD/opentad/models/projections/temporalmaxer_proj.py new file mode 100644 index 0000000000000000000000000000000000000000..04d861723e44c8264884dc0f57111900bfb15c3e --- /dev/null +++ b/OpenTAD/opentad/models/projections/temporalmaxer_proj.py @@ -0,0 +1,116 @@ +import torch +import torch.nn as nn + +from ..bricks import ConvModule +from ..builder import PROJECTIONS + + +@PROJECTIONS.register_module() +class TemporalMaxerProj(nn.Module): + def __init__( + self, + in_channels, + out_channels, + arch=(2, 0, 5), # (#convs, #stem, #branch) + conv_cfg=None, # kernel_size proj_pdrop + norm_cfg=None, + drop_out=0.0, + ): + super().__init__() + assert len(arch) == 3 + + self.in_channels = in_channels + self.out_channels = out_channels + self.arch = arch + self.kernel_size = conv_cfg["kernel_size"] + self.scale_factor = 2 # as default + self.with_norm = norm_cfg is not None + + self.drop_out = nn.Dropout1d(p=drop_out) if drop_out > 0 else None + + if isinstance(self.in_channels, (list, tuple)): + assert isinstance(self.out_channels, (list, tuple)) and len(self.in_channels) == len(self.out_channels) + self.proj = nn.ModuleList([]) + for n_in, n_out in zip(self.in_channels, self.out_channels): + self.proj.append( + ConvModule( + n_in, + n_out, + kernel_size=1, + stride=1, + padding=0, + ) + ) + in_channels = out_channels = sum(self.out_channels) + else: + self.proj = None + + # embedding network using convs + self.embed = nn.ModuleList() + for i in range(arch[0]): + self.embed.append( + ConvModule( + in_channels if i == 0 else out_channels, + out_channels, + kernel_size=self.kernel_size, + stride=1, + padding=self.kernel_size // 2, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + ) + + # stem network using (vanilla) transformer + self.branch = nn.ModuleList() + for _ in range(arch[2]): + self.branch.append( + TemporalMaxer( + kernel_size=3, + stride=self.scale_factor, + padding=1, + ) + ) + + def forward(self, x, mask): + # x: batch size, feature channel, sequence length + # mask: batch size, sequence length (bool) + if self.drop_out is not None: + x = self.drop_out(x) + + # feature projection + if self.proj is not None: + x = torch.cat([proj(s, mask)[0] for proj, s in zip(self.proj, x.split(self.in_channels, dim=1))], dim=1) + + # embedding network + for idx in range(len(self.embed)): + x, mask = self.embed[idx](x, mask) + + # prep for outputs + out_feats = (x,) + out_masks = (mask,) + + # main branch with downsampling + for idx in range(len(self.branch)): + x, mask = self.branch[idx](x, mask) + out_feats += (x,) + out_masks += (mask,) + + return out_feats, out_masks + + +class TemporalMaxer(nn.Module): + def __init__(self, kernel_size, stride, padding): + super().__init__() + self.ds_pooling = nn.MaxPool1d(kernel_size, stride=stride, padding=padding) + self.stride = stride + + def forward(self, x, mask): + if self.stride > 1: + out_mask = self.ds_pooling(mask.float()).bool() + else: + # masking out the features + out_mask = mask + + out = self.ds_pooling(x) * out_mask.unsqueeze(1).to(x.dtype) + + return out, out_mask.bool() diff --git a/OpenTAD/opentad/models/projections/tridet_proj.py b/OpenTAD/opentad/models/projections/tridet_proj.py new file mode 100644 index 0000000000000000000000000000000000000000..dc457089179a054eaa5c7eb8d7692ff0a1e45099 --- /dev/null +++ b/OpenTAD/opentad/models/projections/tridet_proj.py @@ -0,0 +1,140 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +from ..bricks import ConvModule, SGPBlock +from ..builder import PROJECTIONS +from .actionformer_proj import get_sinusoid_encoding + + +@PROJECTIONS.register_module() +class TriDetProj(nn.Module): + def __init__( + self, + in_channels, + out_channels, + sgp_mlp_dim, # dim in SGP + arch=(2, 2, 5), # (#convs, #stem transformers, #branch transformers) + sgp_win_size=[-1] * 6, # size of local window for mha + downsample_type="max", # how to downsample feature in FPN + k=1.5, + init_conv_vars=1, # initialization of gaussian variance for the weight in SGP + conv_cfg=None, # kernel_size + norm_cfg=None, + path_pdrop=0.0, # dropout rate for drop path + use_abs_pe=False, # use absolute position embedding + max_seq_len=2304, + input_noise=0.0, + ): + super().__init__() + assert len(arch) == 3 + assert len(sgp_win_size) == (1 + arch[2]) + + self.in_channels = in_channels + self.out_channels = out_channels + self.arch = arch + self.kernel_size = conv_cfg["kernel_size"] + self.scale_factor = 2 # as default + + self.path_pdrop = path_pdrop + self.with_norm = norm_cfg is not None + self.use_abs_pe = use_abs_pe + self.max_seq_len = max_seq_len + self.sgp_win_size = sgp_win_size + self.downsample_type = downsample_type + self.input_noise = input_noise + + # position embedding (1, C, T), rescaled by 1/sqrt(n_embed) + if self.use_abs_pe: + pos_embed = get_sinusoid_encoding(self.max_seq_len, out_channels) / (out_channels**0.5) + self.register_buffer("pos_embed", pos_embed, persistent=False) + + # embedding network using convs + self.embed = nn.ModuleList() + for i in range(arch[0]): + self.embed.append( + ConvModule( + in_channels if i == 0 else out_channels, + out_channels, + kernel_size=self.kernel_size, + stride=1, + padding=self.kernel_size // 2, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + ) + + # stem network using SGP blocks + self.stem = nn.ModuleList() + for idx in range(arch[1]): + self.stem.append( + SGPBlock( + out_channels, + kernel_size=1, + n_ds_stride=1, + n_hidden=sgp_mlp_dim, + k=k, + init_conv_vars=init_conv_vars, + ) + ) + + # main branch using SGP blocks with pooling + self.branch = nn.ModuleList() + for idx in range(arch[2]): + self.branch.append( + SGPBlock( + out_channels, + kernel_size=self.sgp_win_size[1 + idx], + n_ds_stride=self.scale_factor, + path_pdrop=self.path_pdrop, + n_hidden=sgp_mlp_dim, + downsample_type=downsample_type, + k=k, + init_conv_vars=init_conv_vars, + ) + ) + + def forward(self, x, mask): + # x: batch size, feature channel, sequence length, + # mask: batch size, sequence length (bool) + + # trick, adding noise may slightly increases the variability between input features. + if self.input_noise > 0: + noise = torch.randn_like(x) * self.input_noise + x += noise + + # embedding network + for idx in range(len(self.embed)): + x, mask = self.embed[idx](x, mask) + + # training: using fixed length position embeddings + if self.use_abs_pe and self.training: + assert x.shape[-1] <= self.max_seq_len, "Reached max length." + pe = self.pos_embed + # add pe to x + x = x + pe[:, :, : x.shape[-1]] * mask.unsqueeze(1).to(x.dtype) + + # inference: re-interpolate position embeddings for over-length sequences + if self.use_abs_pe and (not self.training): + if x.shape[-1] >= self.max_seq_len: + pe = F.interpolate(self.pos_embed, x.shape[-1], mode="linear", align_corners=False) + else: + pe = self.pos_embed + # add pe to x + x = x + pe[:, :, : x.shape[-1]] * mask.unsqueeze(1).to(x.dtype) + + # stem transformer + for idx in range(len(self.stem)): + x, mask = self.stem[idx](x, mask) + + # prep for outputs + out_feats = (x,) + out_masks = (mask,) + + # main branch with downsampling + for idx in range(len(self.branch)): + x, mask = self.branch[idx](x, mask) + out_feats += (x,) + out_masks += (mask,) + + return out_feats, out_masks diff --git a/OpenTAD/opentad/models/projections/vsgn_proj.py b/OpenTAD/opentad/models/projections/vsgn_proj.py new file mode 100644 index 0000000000000000000000000000000000000000..a5cf9497f2a6b54df76f921157a79463c864c45b --- /dev/null +++ b/OpenTAD/opentad/models/projections/vsgn_proj.py @@ -0,0 +1,71 @@ +import torch.nn as nn +import torch.nn.functional as F +from .actionformer_proj import get_sinusoid_encoding +from ..builder import PROJECTIONS +from ..bricks import ConvModule +from ..bricks.gcn import xGN + + +@PROJECTIONS.register_module() +class VSGNPyramidProj(nn.Module): + def __init__( + self, + in_channels, + out_channels, + pyramid_levels=[2, 4, 8, 16, 32], + conv_cfg=None, + norm_cfg=None, # dict(type="LN"), + use_gcn=False, + gcn_kwargs=dict(num_neigh=10, nfeat_mode="feat_ctr", agg_type="max", edge_weight="false"), + ): + super().__init__() + + # projection convs without downsampling + init_stride = pyramid_levels[0] // 2 + self.stem_convs = ConvModule( + in_channels, + out_channels, + kernel_size=3, + stride=init_stride, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + + # downsampling convs + scale_factor = pyramid_levels[1] // pyramid_levels[0] + self.pyramid_convs = nn.ModuleList() + for _ in range(len(pyramid_levels)): + if use_gcn: + block = xGN( + out_channels, + stride=scale_factor, + gcn_kwargs=gcn_kwargs, + ) + else: + block = ConvModule( + out_channels, + out_channels, + kernel_size=3, + stride=scale_factor, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=dict(type="relu"), + ) + self.pyramid_convs.append(block) + + def forward(self, x, mask): + # x shape [B,C,T], mask [B,T] + + # stem convs without downsampling + x, mask = self.stem_convs(x, mask) + + # downsampling and saving to output + out, out_mask = [], [] + for conv in self.pyramid_convs: + x, mask = conv(x, mask) + out.append(x) + out_mask.append(mask) + return out, out_mask diff --git a/OpenTAD/opentad/models/roi_heads/__init__.py b/OpenTAD/opentad/models/roi_heads/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b49ce8a1eef792eedaa50fbe8e8da32d3b3dead4 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/__init__.py @@ -0,0 +1,19 @@ +from .standard_roi_head import StandardRoIHead +from .cascade_roi_head import CascadeRoIHead +from .standard_map_head import StandardProposalMapHead +from .etad_roi_head import ETADRoIHead +from .afsd_roi_head import AFSDRefineHead +from .vsgn_roi_head import VSGNRoIHead + +from .proposal_generator import * +from .roi_extractors import * +from .proposal_head import * + +__all__ = [ + "StandardRoIHead", + "CascadeRoIHead", + "StandardProposalMapHead", + "ETADRoIHead", + "AFSDRefineHead", + "VSGNRoIHead", +] diff --git a/OpenTAD/opentad/models/roi_heads/afsd_roi_head.py b/OpenTAD/opentad/models/roi_heads/afsd_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b4ea0433bbe6c73373860073d8dd794d4c4ab947 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/afsd_roi_head.py @@ -0,0 +1,183 @@ +import torch +import torch.nn as nn +from ..builder import HEADS +from ..necks.afsd_neck import Unit1D +from .roi_extractors.boundary_pooling.boundary_pooling_op import BoundaryMaxPooling + + +@HEADS.register_module() +class AFSDRefineHead(nn.Module): + def __init__(self, in_channels, num_classes, **kwargs): + super().__init__() + + self.in_channels = in_channels + self.num_classes = num_classes + + self.loc_proposal_branch = ProposalBranch(in_channels, 512) + self.conf_proposal_branch = ProposalBranch(in_channels, 512) + + self.prop_loc_head = Unit1D( + in_channels=in_channels, + output_channels=2, + kernel_shape=1, + activation_fn=None, + ) + self.prop_conf_head = Unit1D( + in_channels=in_channels, + output_channels=num_classes, + kernel_shape=1, + activation_fn=None, + ) + + self.center_head = Unit1D( + in_channels=in_channels, + output_channels=1, + kernel_shape=3, + stride=1, + use_bias=True, + activation_fn=None, + ) + + # init weights + self.init_weights() + + def init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv1d): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.GroupNorm): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def forward_train( + self, + frame_level_feat, + loc_feats, + conf_feats, + segments_list, + frame_segments_list, + **kwargs, + ): + start = frame_level_feat[:, : self.in_channels // 2].permute(0, 2, 1).contiguous() # [B,T,C] + end = frame_level_feat[:, self.in_channels // 2 :].permute(0, 2, 1).contiguous() # [B,T,C] + + prop_locs = [] + prop_confs = [] + centers = [] + batch_num = frame_level_feat.size(0) + + for i, (loc_feat, conf_feat, segments, frame_segments) in enumerate( + zip(loc_feats, conf_feats, segments_list, frame_segments_list) + ): + # boundary pooling to extract proposal features + loc_prop_feat, loc_prop_feat_ = self.loc_proposal_branch( + loc_feat, + frame_level_feat, + segments, + frame_segments, + ) + conf_prop_feat, conf_prop_feat_ = self.conf_proposal_branch( + conf_feat, + frame_level_feat, + segments, + frame_segments, + ) + + # level 0 to predict start/end + if i == 0: + ndim = loc_prop_feat_.size(1) // 2 + start_loc_prop = loc_prop_feat_[:, :ndim].permute(0, 2, 1).contiguous() + end_loc_prop = loc_prop_feat_[:, ndim:].permute(0, 2, 1).contiguous() + start_conf_prop = conf_prop_feat_[:, :ndim].permute(0, 2, 1).contiguous() + end_conf_prop = conf_prop_feat_[:, ndim:].permute(0, 2, 1).contiguous() + + # regression + prop_loc = self.prop_loc_head(loc_prop_feat) + prop_loc = prop_loc.view(batch_num, 2, -1).permute(0, 2, 1).contiguous() + prop_locs.append(prop_loc) # [B,T,2] + + # classification + prop_conf = self.prop_conf_head(conf_prop_feat) + prop_conf = prop_conf.view(batch_num, self.num_classes, -1).permute(0, 2, 1).contiguous() + prop_confs.append(prop_conf) # [B,T,num_classes] + + # center + center = self.center_head(loc_prop_feat) + center = center.view(batch_num, 1, -1).permute(0, 2, 1).contiguous() # [B,T,1] + centers.append(center) + + prop_loc = torch.cat([o.view(batch_num, -1, 2) for o in prop_locs], 1) + prop_conf = torch.cat([o.view(batch_num, -1, self.num_classes) for o in prop_confs], 1) + center = torch.cat([o.view(batch_num, -1, 1) for o in centers], 1) + return start, end, prop_loc, prop_conf, center, start_loc_prop, end_loc_prop, start_conf_prop, end_conf_prop + + def forward_test( + self, + frame_level_feat, + loc_feats, + conf_feats, + segments_list, + frame_segments_list, + **kwargs, + ): + return self.forward_train(frame_level_feat, loc_feats, conf_feats, segments_list, frame_segments_list) + + +class ProposalBranch(nn.Module): + def __init__(self, in_channels, proposal_channels): + super(ProposalBranch, self).__init__() + self.cur_point_conv = nn.Sequential( + Unit1D( + in_channels=in_channels, + output_channels=proposal_channels, + kernel_shape=1, + activation_fn=None, + ), + nn.GroupNorm(32, proposal_channels), + nn.ReLU(inplace=True), + ) + self.lr_conv = nn.Sequential( + Unit1D( + in_channels=in_channels, + output_channels=proposal_channels * 2, + kernel_shape=1, + activation_fn=None, + ), + nn.GroupNorm(32, proposal_channels * 2), + nn.ReLU(inplace=True), + ) + + self.boundary_max_pooling = BoundaryMaxPooling() + + self.roi_conv = nn.Sequential( + Unit1D( + in_channels=proposal_channels, + output_channels=proposal_channels, + kernel_shape=1, + activation_fn=None, + ), + nn.GroupNorm(32, proposal_channels), + nn.ReLU(inplace=True), + ) + + self.proposal_conv = nn.Sequential( + Unit1D( + in_channels=proposal_channels * 4, + output_channels=in_channels, + kernel_shape=1, + activation_fn=None, + ), + nn.GroupNorm(32, in_channels), + nn.ReLU(inplace=True), + ) + + def forward(self, feature, frame_level_feature, segments, frame_segments): + fm_short = self.cur_point_conv(feature) + feature = self.lr_conv(feature) + prop_feature = self.boundary_max_pooling(feature, segments) + prop_roi_feature = self.boundary_max_pooling(frame_level_feature, frame_segments) + prop_roi_feature = self.roi_conv(prop_roi_feature) + prop_feature = torch.cat([prop_roi_feature, prop_feature, fm_short], dim=1) + prop_feature = self.proposal_conv(prop_feature) + return prop_feature, feature diff --git a/OpenTAD/opentad/models/roi_heads/cascade_roi_head.py b/OpenTAD/opentad/models/roi_heads/cascade_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..283364d0d63c8c748c3154934ddfe4bde2b72683 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/cascade_roi_head.py @@ -0,0 +1,91 @@ +import copy +import torch +import torch.nn as nn +from ..builder import HEADS, build_proposal_generator, build_roi_extractor, build_head + + +@HEADS.register_module() +class CascadeRoIHead(nn.Module): + def __init__( + self, + stages, + proposal_roi_extractor, + proposal_head, + proposal_generator=None, + ): + super().__init__() + + self.stage_loss_weight = stages.loss_weight + self.proposal_roi_extractor = build_roi_extractor(proposal_roi_extractor) + + self.proposal_heads = nn.ModuleList([]) + for i in range(stages.number): + stage_cfg = copy.deepcopy(proposal_head) + stage_cfg.loss.assigner.pos_iou_thr = stages.pos_iou_thresh[i] + stage_cfg.loss.assigner.neg_iou_thr = stages.pos_iou_thresh[i] + stage_cfg.loss.assigner.min_pos_iou = stages.pos_iou_thresh[i] + self.proposal_heads.append(build_head(stage_cfg)) + + if proposal_generator != None: + self.proposal_generator = build_proposal_generator(proposal_generator) + + @property + def with_proposal_generator(self): + """bool: whether the roi head's proposals are initialized by proposal_generator""" + return hasattr(self, "proposal_generator") and self.proposal_generator is not None + + def forward_train(self, x, proposal_list, gt_segments, gt_labels, **kwargs): + # (Optional) proposals generator + if self.with_proposal_generator: + proposal_list = self.proposal_generator(x) + + losses = {} + for i in range(len(self.proposal_heads)): + # roi align to get the proposal feature + proposal_feats = self.proposal_roi_extractor(x, proposal_list) # [B,K,C,res] + + # head forward + loss, proposal_list = self.proposal_heads[i].forward_train( + proposal_feats, + proposal_list, + gt_segments, + gt_labels, + ) + + for name, value in loss.items(): + if "loss" in name: + losses[f"s{i}.{name}"] = value * self.stage_loss_weight[i] + else: + losses[f"s{i}.{name}"] = value + return losses + + def forward_test(self, x, proposal_list=None, **kwargs): + if self.with_proposal_generator: + proposal_list = self.proposal_generator(x) + + proposals = [] + scores = [] + for i in range(len(self.proposal_heads)): + # roi align to get the proposal feature + proposal_feats = self.proposal_roi_extractor(x, proposal_list) # [B,K,C,res] + + # head forward + proposal_list, proposal_score = self.proposal_heads[i].forward_test(proposal_feats, proposal_list) + + proposals.append(proposal_list) + scores.append(proposal_score) + + # get refined proposal: average of three stages, [B,K,2] + # proposals = torch.stack(proposals, dim=-1).mean(dim=-1) + # get proposal score: average of three stages, [B,K,num_classes] + # cls_score = torch.stack(scores, dim=-1).mean(dim=-1) + + refined_proposal_list = [] + proposal_score_list = [] + + for i in range(len(proposals[0])): + proposals_per_video = torch.stack([prop[i] for prop in proposals], dim=-1).mean(dim=-1) + scores_per_video = torch.stack([score[i] for score in scores], dim=-1).mean(dim=-1) + refined_proposal_list.append(proposals_per_video) + proposal_score_list.append(scores_per_video) + return refined_proposal_list, proposal_score_list diff --git a/OpenTAD/opentad/models/roi_heads/etad_roi_head.py b/OpenTAD/opentad/models/roi_heads/etad_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..51b34eb86bd49076e2142c818f12cad47841b8ca --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/etad_roi_head.py @@ -0,0 +1,110 @@ +import copy +import torch +import torch.nn as nn +from ..builder import HEADS, build_proposal_generator, build_roi_extractor, build_head +from ..utils.iou_tools import compute_iou_torch, compute_ioa_torch + + +@HEADS.register_module() +class ETADRoIHead(nn.Module): + def __init__( + self, + stages, + proposal_generator, + proposal_roi_extractor, + proposal_head, + ): + super().__init__() + + self.tscale = proposal_generator.tscale + self.stage_loss_weight = stages.loss_weight + self.proposal_generator = build_proposal_generator(proposal_generator) + self.proposal_roi_extractor = build_roi_extractor(proposal_roi_extractor) + + self.proposal_heads = nn.ModuleList([]) + for i in range(stages.number): + stage_cfg = copy.deepcopy(proposal_head) + stage_cfg.loss.pos_iou_thresh = stages.pos_iou_thresh[i] + self.proposal_heads.append(build_head(stage_cfg)) + + def forward_train(self, x, proposal_list, gt_segments, gt_labels, **kwargs): + proposal_list = self.proposal_generator(bs=x.shape[0], device=x.device, training=True) # [B,K,2] + gt_starts, gt_ends, batch_gt_segment = self.prepare_shared_gt(gt_segments, proposal_list) + + losses = {} + for i in range(len(self.proposal_heads)): + # roi align to get the proposal feature + proposal_feats = self.proposal_roi_extractor(x, proposal_list) # [B,K,C,res] + + # head forward + loss, proposal_list = self.proposal_heads[i].forward_train( + proposal_feats, + proposal_list, + gt_starts, + gt_ends, + batch_gt_segment, + ) + + for name, value in loss.items(): + if "loss" in name: + losses[f"{name}.s{i}"] = value * self.stage_loss_weight[i] + else: + losses[f"{name}.s{i}"] = value + return losses + + def prepare_shared_gt(self, gt_segments, proposals): + # get startness/endness + gt_starts = [] + gt_ends = [] + + temporal_anchor = torch.stack((torch.arange(0, self.tscale), torch.arange(1, self.tscale + 1)), dim=1) + temporal_anchor = temporal_anchor.to(gt_segments[0].device) + + for gt_segment in gt_segments: + gt_xmins = gt_segment[:, 0] + gt_xmaxs = gt_segment[:, 1] + + gt_start_bboxs = torch.stack((gt_xmins - 3.0 / 2, gt_xmins + 3.0 / 2), dim=1) + gt_end_bboxs = torch.stack((gt_xmaxs - 3.0 / 2, gt_xmaxs + 3.0 / 2), dim=1) + + gt_start = compute_ioa_torch(gt_start_bboxs, temporal_anchor) + gt_start = torch.max(gt_start, dim=1)[0] + + gt_end = compute_ioa_torch(gt_end_bboxs, temporal_anchor) # [T, N] + gt_end = torch.max(gt_end, dim=1)[0] + + gt_starts.append(gt_start) + gt_ends.append(gt_end) + + gt_starts = torch.stack(gt_starts) # [B,T] + gt_ends = torch.stack(gt_ends) # [B,T] + + # get corresponding gt_boxes + batch_gt_segment = [] + for gt_segment, proposal in zip(gt_segments, proposals): + ious = compute_iou_torch(gt_segment, proposal) # [K,N] + gt_iou_index = torch.max(ious, dim=1)[1] # [K] + batch_gt_segment.append(gt_segment[gt_iou_index]) # [K,2] + batch_gt_segment = torch.stack(batch_gt_segment) # [B,K,2] + return gt_starts, gt_ends, batch_gt_segment + + def forward_test(self, x, proposal_list=None, **kwargs): + proposal_list = self.proposal_generator(bs=x.shape[0], device=x.device) # [B, + + proposals = [] + scores = [] + for i in range(len(self.proposal_heads)): + # roi align to get the proposal feature + proposal_feats = self.proposal_roi_extractor(x, proposal_list) # [B,K,C,res] + + # head forward + proposal_list, proposal_score = self.proposal_heads[i].forward_test(proposal_feats, proposal_list) + proposals.append(proposal_list) + scores.append(proposal_score) + + # get refined proposal: average of three stages, [B,K,2] + refined_proposal = torch.stack(proposals, dim=-1).mean(dim=-1) + + # get proposal score: average of three stages, [B,K,num_classes] + proposal_score = torch.stack(scores, dim=-1).mean(dim=-1) + return refined_proposal, proposal_score diff --git a/OpenTAD/opentad/models/roi_heads/proposal_generator/__init__.py b/OpenTAD/opentad/models/roi_heads/proposal_generator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf5936045a28479abbc7fc955d0a23cfc51a580 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/proposal_generator/__init__.py @@ -0,0 +1,4 @@ +from .dense_map import DenseProposalMap +from .sample_map import ProposalMapSampling + +__all__ = ["DenseProposalMap", "ProposalMapSampling"] diff --git a/OpenTAD/opentad/models/roi_heads/proposal_generator/dense_map.py b/OpenTAD/opentad/models/roi_heads/proposal_generator/dense_map.py new file mode 100644 index 0000000000000000000000000000000000000000..a4c9b8b058190565097baffa31d7520cde2803cb --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/proposal_generator/dense_map.py @@ -0,0 +1,38 @@ +import torch +import torch.nn as nn +from ...builder import PROPOSAL_GENERATORS + + +@PROPOSAL_GENERATORS.register_module() +class DenseProposalMap(nn.Module): + def __init__(self, tscale, dscale): + super().__init__() + + self.tscale = tscale + self.dscale = dscale + self.build_proposal_map() + + def forward(self, **kwargs): + return self.proposal_map, self.valid_mask + + def build_proposal_map(self): + proposal_map = [] # x axis is duration, y axis is start + valid_mask = [] + for dur_idx in range(self.dscale): + for start_idx in range(self.tscale): + end_idx = start_idx + dur_idx + 1 + if end_idx <= self.tscale: + proposal_map.append([start_idx, end_idx]) + valid_mask.append(1) + else: + proposal_map.append([0, 0]) + valid_mask.append(0) + + proposal_map = torch.Tensor(proposal_map) + self.proposal_map = proposal_map.reshape(self.dscale, self.tscale, 2) + + valid_mask = torch.Tensor(valid_mask) + self.valid_mask = valid_mask.reshape(self.dscale, self.tscale).bool() + + def __repr__(self): + return f"{self.__class__.__name__}(" f"tscale={self.tscale}, dscale={self.dscale})" diff --git a/OpenTAD/opentad/models/roi_heads/proposal_generator/sample_map.py b/OpenTAD/opentad/models/roi_heads/proposal_generator/sample_map.py new file mode 100644 index 0000000000000000000000000000000000000000..0cb773ca438ab374293980bddad060b297c78601 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/proposal_generator/sample_map.py @@ -0,0 +1,86 @@ +import random +import math +import numpy as np +import torch +import torch.nn as nn +from ...builder import PROPOSAL_GENERATORS + + +@PROPOSAL_GENERATORS.register_module() +class ProposalMapSampling(nn.Module): + def __init__(self, tscale, dscale, sampling_ratio=0.06, strategy="random"): + super().__init__() + + self.tscale = tscale + self.dscale = dscale + self.sampling_ratio = sampling_ratio + self.strategy = strategy + self.build_proposal_map() + + def forward(self, bs, device, training=False): + if training: + if self.training: # training + anchors_init = [self.sample_proposal_map() for _ in range(bs)] + anchors_init = torch.stack(anchors_init, dim=0) + else: # training but validation + anchors_init = self.proposal_map[self.grid_mask.bool()] + anchors_init = anchors_init.unsqueeze(0).repeat(bs, 1, 1) + else: # testing + anchors_init = self.proposal_map[self.valid_mask.bool()] + anchors_init = anchors_init.unsqueeze(0).repeat(bs, 1, 1) + return anchors_init.to(device) # [B,K,2] + + def build_proposal_map(self): + proposal_map = [] # x axis is duration, y axis is start + valid_mask = [] + for dur_idx in range(self.dscale): + for start_idx in range(self.tscale): + end_idx = start_idx + dur_idx + 1 + if end_idx <= self.tscale: + proposal_map.append([start_idx, end_idx]) + valid_mask.append(1) + else: + proposal_map.append([0, 0]) + valid_mask.append(0) + + proposal_map = torch.Tensor(proposal_map) + self.proposal_map = proposal_map.reshape(self.dscale, self.tscale, 2) + + valid_mask = torch.Tensor(valid_mask) + self.valid_mask = valid_mask.reshape(self.dscale, self.tscale).bool() + + # grid mask for validation + step = math.sqrt(1 / self.sampling_ratio) + mask = np.zeros((self.dscale, self.tscale)) + for idx in np.arange(1, self.dscale, step).round().astype(int): + for jdx in np.arange(1, self.tscale, step).round().astype(int): + if jdx + idx < self.tscale: + mask[idx, jdx] = 1 + self.grid_mask = torch.Tensor(mask) + + self.sample_num = int(valid_mask.sum().int() * self.sampling_ratio) + + def sample_proposal_map(self): + if self.strategy == "random": # random select + indices = random.sample(range(self.valid_mask.sum().int()), self.sample_num) + indices = torch.Tensor(indices).long() + indices = torch.nonzero(self.valid_mask)[indices] + select_mask = torch.zeros_like(self.valid_mask) + select_mask[indices[:, 0], indices[:, 1]] = 1 + anchors_init = self.proposal_map[select_mask.bool()] + + elif self.strategy == "grid": # grid select + anchors_init = self.proposal_map[self.grid_mask.bool()] + + elif self.strategy == "block": # block select + block_w = int(math.sqrt(self.sample_num)) + x = random.randint(0, self.dscale - 2 * block_w) + y = random.randint(0, self.tscale - 2 * block_w - x) + mask = np.zeros((self.dscale, self.tscale)) + for idx in range(x, x + block_w): + for jdx in range(y, y + block_w): + if jdx + idx < self.tscale: + mask[idx, jdx] = 1 + block_mask = torch.Tensor(mask) + anchors_init = self.proposal_map[block_mask.bool()] + return anchors_init diff --git a/OpenTAD/opentad/models/roi_heads/proposal_head/__init__.py b/OpenTAD/opentad/models/roi_heads/proposal_head/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbc7e080ce592e3c669a995b09309c83ad6785f4 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/proposal_head/__init__.py @@ -0,0 +1,6 @@ +from .convfc_head import ConvFCHead +from .pem_head import PEMHead, TSIHead +from .etad_head import ETADHead + + +__all__ = ["ConvFCHead", "PEMHead", "TSIHead", "ETADHead"] diff --git a/OpenTAD/opentad/models/roi_heads/proposal_head/convfc_head.py b/OpenTAD/opentad/models/roi_heads/proposal_head/convfc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1bbd78d6f35d77be4fe158644b756af3b4dccde5 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/proposal_head/convfc_head.py @@ -0,0 +1,283 @@ +import math +import torch +import torch.nn as nn +from ...builder import HEADS, build_loss +from ...utils.bbox_tools import delta_to_pred, compute_delta +from ...utils.misc import convert_gt_to_one_hot + + +@HEADS.register_module() +class ConvFCHead(nn.Module): + r"""General proposal head, with shared conv and fc layers and two separated branches. + /-> cls fcs + roi feats -> shared convs -> shared fcs + \-> reg fcs + """ + + def __init__( + self, + in_channels, + roi_size, + num_classes, + shared_convs_num=0, # shared convs + shared_convs_channel=128, + shared_fcs_num=1, # shared fcs + shared_fcs_channel=512, + head_fcs_num=3, # specific fcs for each feature + head_fcs_channel=128, + cls_prior_prob=0.01, + # reg_class_agnostic=True, + loss=None, + ): + super().__init__() + + self.in_channels = in_channels + self.roi_size = roi_size + self.num_classes = num_classes + self.cls_prior_prob = cls_prior_prob + + # shared layers setting + self.shared_convs_num = shared_convs_num + self.shared_convs_channel = shared_convs_channel + self.shared_fcs_num = shared_fcs_num + self.shared_fcs_channel = shared_fcs_channel + + # head layers setting + self.head_fcs_num = head_fcs_num + self.head_fcs_channel = head_fcs_channel + + # initialize layers + self._init_layers() + + # loss + self.multiply_with_iou = loss.multiply_with_iou if "multiply_with_iou" in loss else False + self.assigner = build_loss(loss.assigner) + self.sampler = build_loss(loss.sampler) + self.cls_loss = build_loss(loss.cls_loss) + self.reg_loss = build_loss(loss.reg_loss) + + def _init_layers(self): + """Initialize layers of the head.""" + self._init_shared() + self._init_heads() + + def _init_shared(self): + """Initialize shared conv fc layers""" + assert (self.shared_convs_num + self.shared_fcs_num) > 0 + self.shared_conv_fc = ConvFC( + in_channels=self.in_channels, + roi_size=self.roi_size, + convs_num=self.shared_convs_num, + convs_channel=self.shared_convs_channel, + fcs_num=self.shared_fcs_num, + fcs_channel=self.shared_fcs_channel, + ) + + def _init_heads(self): + """Initialize classification head and regression head""" + self.cls_head = FCHead( + in_channels=self.shared_fcs_channel, + out_channels=self.num_classes, + fcs_num=self.head_fcs_num, + fcs_channel=self.head_fcs_channel, + ) + + self.reg_head = FCHead( + in_channels=self.shared_fcs_channel, + out_channels=2, + fcs_num=self.head_fcs_num, + fcs_channel=self.head_fcs_channel, + ) + + # use prior in model initialization to improve stability + # this will overwrite other weight init + if self.cls_prior_prob > 0: + bias_value = -(math.log((1 - self.cls_prior_prob) / self.cls_prior_prob)) + torch.nn.init.constant_(self.cls_head.head.bias, bias_value) + + def forward_train(self, proposal_feats, proposal_list, gt_segments, gt_labels): + proposal_feats = self.shared_conv_fc(proposal_feats) # [sum(K),C] + cls_pred = self.cls_head(proposal_feats) # [sum(K),num_classes], logits + reg_pred = self.reg_head(proposal_feats) # [sum(K),2] + + refined_proposals_list, _ = self.refine_proposals(proposal_list, reg_pred, cls_pred) + + loss = self.losses(cls_pred, reg_pred, proposal_list, gt_segments, gt_labels) + return loss, refined_proposals_list + + def forward_test(self, proposal_feats, proposal_list): + proposal_feats = self.shared_conv_fc(proposal_feats) # [sum(K),C] + cls_pred = self.cls_head(proposal_feats) # [sum(K),num_classes], logits + reg_pred = self.reg_head(proposal_feats) # [sum(K),2] + + refined_proposals_list, proposal_score_list = self.refine_proposals(proposal_list, reg_pred, cls_pred) + return refined_proposals_list, proposal_score_list + + @torch.no_grad() + def prepare_targets(self, gt_segments, gt_labels, proposal_list): + # convert gt to one hot encoding for multi class + gt_segments, gt_labels = convert_gt_to_one_hot(gt_segments, gt_labels, self.num_classes) + + gt_cls_list, gt_reg_list, gt_iou_list, pos_idxs_list, neg_idxs_list = [], [], [], [], [] + for i, (gt_segment, gt_label, proposal) in enumerate(zip(gt_segments, gt_labels, proposal_list)): + if len(gt_segment) == 0: # make a pseudo gt_segment + gt_segment = torch.tensor([[0, 0]], dtype=torch.float32, device=proposal.device) + gt_label = torch.zeros(self.num_classes, device=proposal.device).to(torch.int64) + + # assign GT + ious, assigned_gt_idxs, assigned_labels = self.assigner.assign(proposal, gt_segment, gt_label) + + # sample positive and negative anchors + pos_idxs, neg_idxs = self.sampler.sample(assigned_gt_idxs) + pos_idxs_list.append(pos_idxs) + neg_idxs_list.append(neg_idxs) + + # classification target: pos_mask + neg_mask + gt_cls = assigned_labels.float().clamp(min=0, max=1)[pos_idxs + neg_idxs] + gt_iou = ious[pos_idxs + neg_idxs] + gt_cls_list.append(gt_cls) + gt_iou_list.append(gt_iou) + + # regression target: pos_mask + gt_reg = compute_delta(proposal[pos_idxs], gt_segment[assigned_gt_idxs[pos_idxs] - 1]) + gt_reg_list.append(gt_reg) + + gt_cls_concat = torch.cat(gt_cls_list, dim=0) # [B*(pos+neg),num_classes] + gt_reg_concat = torch.cat(gt_reg_list, dim=0) # [B*(pos),2] + gt_iou_concat = torch.cat(gt_iou_list, dim=0) # [B*(pos+neg)] + return gt_cls_concat, gt_reg_concat, gt_iou_concat, pos_idxs_list, neg_idxs_list + + def losses(self, cls_pred, reg_pred, proposal_list, gt_segments, gt_labels): + # get gt targets and positive negative mask + gt_cls, gt_reg, gt_iou, pos_idxs_list, neg_idxs_list = self.prepare_targets( + gt_segments, gt_labels, proposal_list + ) + + num_pos = sum([len(pos_idxs) for pos_idxs in pos_idxs_list]) + num_neg = sum([len(neg_idxs) for neg_idxs in neg_idxs_list]) + + # classification loss + if self.multiply_with_iou: + gt_cls *= gt_iou.unsqueeze(-1) + + sampled_cls_pred = [] + cls_pred = torch.split(cls_pred, [proposal.shape[0] for proposal in proposal_list], dim=0) + for pred, pos_idxs, neg_idxs in zip(cls_pred, pos_idxs_list, neg_idxs_list): + sampled_cls_pred.append(pred[pos_idxs + neg_idxs]) + sampled_cls_pred = torch.cat(sampled_cls_pred, dim=0) + + loss_cls = self.cls_loss(sampled_cls_pred, gt_cls.float()) + loss_cls /= num_pos + num_neg + + # regression loss + sampled_reg_pred = [] + reg_pred = torch.split(reg_pred, [proposal.shape[0] for proposal in proposal_list], dim=0) + for pred, pos_idxs in zip(reg_pred, pos_idxs_list): + sampled_reg_pred.append(pred[pos_idxs]) + sampled_reg_pred = torch.cat(sampled_reg_pred, dim=0) + + if num_pos == 0: # not have positive sample + # do not have positive samples in regression loss + loss_reg = torch.Tensor([0]).sum().to(sampled_reg_pred.device) + else: + loss_reg = self.reg_loss(sampled_reg_pred, gt_reg) + loss_reg /= num_pos + + losses = {"cls_loss": loss_cls, "reg_loss": loss_reg} + return losses + + @torch.no_grad() + def refine_proposals(self, proposal_list, reg_pred, score_pred): + new_proposal_list = [] + new_score_list = [] + cur = 0 + for proposal in proposal_list: + N = proposal.shape[0] + new_proposal_list.append(delta_to_pred(proposal, reg_pred[cur : cur + N])) + new_score_list.append(score_pred[cur : cur + N].sigmoid()) + cur += N + return new_proposal_list, new_score_list + + +class ConvFC(nn.Module): + def __init__(self, in_channels=256, roi_size=32, convs_num=4, convs_channel=128, fcs_num=1, fcs_channel=512): + super(ConvFC, self).__init__() + + self.convs_num = convs_num + self.fcs_num = fcs_num + last_layer_dim = in_channels + + # convs + self.convs = nn.Sequential() + if convs_num > 0: + for i in range(convs_num): + in_channel = last_layer_dim if i == 0 else convs_channel + self.convs.append( + nn.Sequential( + nn.Conv1d(in_channel, convs_channel, kernel_size=3, stride=1, padding=1), + nn.ReLU(inplace=True), + ) + ) + last_layer_dim = convs_channel + + # fc + self.fcs = nn.Sequential() + if fcs_num > 0: + for i in range(fcs_num): + in_channel = last_layer_dim * roi_size if i == 0 else fcs_channel + self.fcs.append( + nn.Sequential( + nn.Linear(in_channel, fcs_channel), + nn.ReLU(inplace=True), + ) + ) + + self.init_weights() + + def init_weights(self): + for m in self.modules(): + if isinstance(m, (nn.Conv1d, nn.Linear)): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, roi_ft): + # roi_ft [sum(K),C,res] + if self.convs_num > 0: + roi_ft = self.convs(roi_ft) # [sum(K),C,res] + + if self.fcs_num > 0: + roi_ft = roi_ft.flatten(1) + roi_ft = self.fcs(roi_ft) # [sum(K),C] + return roi_ft + + +class FCHead(nn.Module): + def __init__(self, in_channels, out_channels, fcs_num=3, fcs_channel=128): + super(FCHead, self).__init__() + assert fcs_num > 0 + + self.fcs = nn.Sequential() + for i in range(fcs_num): + in_channel = in_channels if i == 0 else fcs_channel + self.fcs.append( + nn.Sequential( + nn.Linear(in_channel, fcs_channel), + nn.ReLU(inplace=True), + ) + ) + self.head = nn.Linear(fcs_channel, out_channels) + + self.init_weights() + + def init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, x): + x = self.fcs(x) + x = self.head(x) + return x diff --git a/OpenTAD/opentad/models/roi_heads/proposal_head/etad_head.py b/OpenTAD/opentad/models/roi_heads/proposal_head/etad_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fc7d3b8dd29f3ab801bdb8948f5642df77a030cd --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/proposal_head/etad_head.py @@ -0,0 +1,256 @@ +import math +import torch +import torch.nn as nn +import torch.nn.functional as F +from .convfc_head import ConvFC, FCHead +from ...builder import HEADS +from ...utils.iou_tools import compute_batched_iou_torch + + +@HEADS.register_module() +class ETADHead(nn.Module): + def __init__( + self, + in_channels, + roi_size, + feat_channels, + fcs_num, + fcs_channels, + loss=None, + ): + super().__init__() + + self.in_channels = in_channels + self.roi_size = roi_size + self.feat_channels = feat_channels + self.fcs_num = fcs_num + self.fcs_channels = fcs_channels + + # initialize layers + self._init_layers() + + # loss + self.pos_iou_thresh = loss.pos_iou_thresh + self.cls_weight = loss.cls_weight + self.reg_weight = loss.reg_weight + self.boundary_weight = loss.boundary_weight + + def _init_layers(self): + """Initialize layers of the head.""" + self._init_shared() + self._init_heads() + + def _init_shared(self): + """Initialize shared conv fc layers""" + self.shared_conv_fc = ConvFC( + in_channels=self.in_channels, + roi_size=self.roi_size, + convs_num=0, + fcs_num=1, + fcs_channel=self.feat_channels, + ) + + def _init_heads(self): + # extended features + self.iou_head = FCHead( + in_channels=self.feat_channels, + out_channels=2, + fcs_num=self.fcs_num, + fcs_channel=self.fcs_channels, + ) + self.se_head = FCHead( + in_channels=self.feat_channels, + out_channels=2, + fcs_num=self.fcs_num, + fcs_channel=self.fcs_channels, + ) + self.reg_head = FCHead( + in_channels=self.feat_channels, + out_channels=4, + fcs_num=self.fcs_num, + fcs_channel=self.fcs_channels, + ) + + def forward_train(self, proposal_feats, proposal_list, gt_starts, gt_ends, batch_gt_segment): + bs, N, _, _ = proposal_feats.shape + proposal_feats = proposal_feats.flatten(0, 1) + + # proposal feature + proposal_feats = self.shared_conv_fc(proposal_feats) + + # head + iou_out = self.iou_head(proposal_feats).sigmoid() # [bs*N, 2] + reg_out = self.reg_head(proposal_feats) # [bs*N, 4] + se_out = self.se_head(proposal_feats).sigmoid() # [bs*N, 2] + + iou_out = iou_out.unflatten(0, (bs, N)) # [bs,N,2] + reg_out = reg_out.unflatten(0, (bs, N)) # [bs,N,4] + se_out = se_out.unflatten(0, (bs, N)) # [bs,N,2] + + refined_proposals = self.refine_proposals(proposal_list, reg_out) + loss = self.losses(iou_out, reg_out, se_out, proposal_list, gt_starts, gt_ends, batch_gt_segment) + return loss, refined_proposals + + def forward_test(self, proposal_feats, proposal_list): + bs, N, _, _ = proposal_feats.shape + proposal_feats = proposal_feats.flatten(0, 1) + + # proposal feature + proposal_feats = self.shared_conv_fc(proposal_feats) + + # head + iou_out = self.iou_head(proposal_feats).sigmoid() # [bs*N, 2] + reg_out = self.reg_head(proposal_feats) # [bs*N, 4] + se_out = self.se_head(proposal_feats).sigmoid() # [bs*N, 2] + + iou_out = iou_out.unflatten(0, (bs, N)) # [bs,N,2] + reg_out = reg_out.unflatten(0, (bs, N)) # [bs,N,4] + se_out = se_out.unflatten(0, (bs, N)) # [bs,N,2] + + refined_proposals = self.refine_proposals(proposal_list, reg_out) + return refined_proposals, iou_out + + @torch.no_grad() + def refine_proposals(self, anchors, regs): + regs = regs.view(anchors.shape[0], -1, regs.shape[-1]).detach() # [B,K,6] + + xmins = anchors[:, :, 0] + xmaxs = anchors[:, :, 1] + xlens = xmaxs - xmins + xcens = (xmins + xmaxs) * 0.5 + + # refine anchor by start end + xlens1 = xlens + xlens * (regs[:, :, 1] - regs[:, :, 0]) + xcens1 = xcens + xlens * (regs[:, :, 0] + regs[:, :, 1]) * 0.5 + xmins1 = xcens1 - xlens1 * 0.5 + xmaxs1 = xcens1 + xlens1 * 0.5 + + # refine anchor by center width + xcens2 = xcens + regs[:, :, 2] * xlens + xlens2 = xlens * torch.exp(regs[:, :, 3]) + xmins2 = xcens2 - xlens2 * 0.5 + xmaxs2 = xcens2 + xlens2 * 0.5 + + nxmin = (xmins1 + xmins2) * 0.5 + nxmax = (xmaxs1 + xmaxs2) * 0.5 + new_anchors = torch.stack((nxmin, nxmax), dim=2) + return new_anchors + + @torch.no_grad() + def prepare_targets(self, proposals, gt_starts, gt_ends, batch_gt_segment): + batch_gt_iou = compute_batched_iou_torch(batch_gt_segment, proposals) # [B,K] + batch_gt_reg = self._get_gt_regs(batch_gt_segment, proposals) # [B,K,6] + batch_gt_cls_s, batch_gt_cls_e = self._get_gt_bounary_cls(gt_starts, gt_ends, proposals) + return batch_gt_iou, batch_gt_reg, batch_gt_cls_s, batch_gt_cls_e + + def _get_gt_regs(self, gt, anchors): + # gt_segment [B,K,2] anchors_init[B,K,2] + anchor_len = torch.clamp(anchors[:, :, 1] - anchors[:, :, 0], min=1e-6) + gt_len = torch.clamp(gt[:, :, 1] - gt[:, :, 0], min=1e-6) + delta_s = (gt[:, :, 0] - anchors[:, :, 0]) / anchor_len + delta_e = (gt[:, :, 1] - anchors[:, :, 1]) / anchor_len + delta_c = (delta_s + delta_e) * 0.5 + delta_w = torch.log(gt_len / anchor_len + 1e-6) + delta = torch.stack([delta_s, delta_e, delta_c, delta_w], dim=-1) + return delta + + def _get_gt_bounary_cls(self, gt_start, gt_end, anchors): + # gt_start [B,200] anchors_init[B,K,2] + anchors_start = anchors[..., 0].long().clamp(min=0, max=gt_start.shape[1] - 1) + anchors_end = anchors[..., 1].long().clamp(min=0, max=gt_end.shape[1] - 1) + gt_cls_s = torch.gather(gt_start, 1, anchors_start) + gt_cls_e = torch.gather(gt_end, 1, anchors_end) + return gt_cls_s, gt_cls_e + + def losses(self, iou, reg, se, proposal_list, gt_starts, gt_ends, batch_gt_segment): + gt_iou, gt_reg, gt_cls_s, gt_cls_e = self.prepare_targets(proposal_list, gt_starts, gt_ends, batch_gt_segment) + + # iou + loss_iou_cls = bl_sample_loss(iou[..., 0], gt_iou, pos_thresh=0.9) + loss_iou_reg = l2_sample_loss(iou[..., 1], gt_iou, high_thresh=0.7, low_thresh=0.3) + loss_iou = loss_iou_cls * self.cls_weight + loss_iou_reg * self.reg_weight + + # boundary regression + loss_reg_start = smoothL1_regress_loss(reg[..., 0], gt_iou, gt_reg[..., 0], thresh=self.pos_iou_thresh) + loss_reg_end = smoothL1_regress_loss(reg[..., 1], gt_iou, gt_reg[..., 1], thresh=self.pos_iou_thresh) + loss_reg_center = smoothL1_regress_loss(reg[..., 2], gt_iou, gt_reg[..., 2], thresh=self.pos_iou_thresh) + loss_reg_width = smoothL1_regress_loss(reg[..., 3], gt_iou, gt_reg[..., 3], thresh=self.pos_iou_thresh) + loss_reg = self.boundary_weight * (loss_reg_start + loss_reg_end + loss_reg_center + loss_reg_width) + + # boundary classification + loss_cls_start = bl_sample_loss(se[..., 0], gt_cls_s, pos_thresh=0.5) + loss_cls_end = bl_sample_loss(se[..., 1], gt_cls_e, pos_thresh=0.5) + loss_cls = 0.5 * (loss_cls_start + loss_cls_end) + + # total loss + loss_pem = loss_iou + loss_reg + loss_cls + + losses = {"loss_pem": loss_pem} + return losses + + +def bl_sample_loss(output, gt_iou, pos_thresh=0.9): + gt_iou = gt_iou.cuda() + + pmask = (gt_iou > pos_thresh).float() + nmask = (gt_iou <= pos_thresh).float() + + num_pos = torch.sum(pmask) + num_neg = torch.sum(nmask) + + if num_pos == 0: # in case of nan + loss = -torch.mean(torch.log(1.0 - output + 1e-6)) + return loss + + r_l = num_pos / num_neg + nmask_sample = torch.rand(nmask.shape).cuda() + nmask_sample = nmask_sample * nmask + nmask_sample = (nmask_sample > (1 - r_l)).float() + + loss_pos = pmask * torch.log(output + 1e-6) + loss_neg = nmask_sample * torch.log(1.0 - output + 1e-6) + loss = -torch.sum(loss_pos + loss_neg) / (num_pos + torch.sum(nmask_sample)) + return loss + + +def l2_sample_loss(output, gt_iou, high_thresh=0.7, low_thresh=0.3): + gt_iou = gt_iou.cuda() + + u_hmask = (gt_iou > high_thresh).float() + u_mmask = ((gt_iou <= high_thresh) & (gt_iou > low_thresh)).float() + u_lmask = (gt_iou <= low_thresh).float() + + num_h = torch.sum(u_hmask) + num_m = torch.sum(u_mmask) + num_l = torch.sum(u_lmask) + + if num_h == 0: # in case of nan + loss = F.mse_loss(output, gt_iou, reduction="none") + loss = torch.mean(loss) + return loss + + r_m = num_h / num_m + u_smmask = torch.rand(u_hmask.shape).cuda() + u_smmask = u_smmask * u_mmask + u_smmask = (u_smmask > (1 - r_m)).float() + + r_l = num_h / num_l + u_slmask = torch.rand(u_hmask.shape).cuda() + u_slmask = u_slmask * u_lmask + u_slmask = (u_slmask > (1 - r_l)).float() + + mask = u_hmask + u_smmask + u_slmask + loss = F.mse_loss(output, gt_iou, reduction="none") + loss = torch.sum(loss * mask) / torch.sum(mask) + return loss + + +def smoothL1_regress_loss(output, gt_iou, gt_reg, thresh=0.7): + mask = (gt_iou > thresh).float().cuda() + + if torch.sum(mask) == 0: # not have positive sample + return torch.Tensor([0]).sum().cuda() + + loss = F.smooth_l1_loss(output, gt_reg, reduction="none") + loss = torch.sum(loss * mask) / torch.sum(mask) + return loss diff --git a/OpenTAD/opentad/models/roi_heads/proposal_head/pem_head.py b/OpenTAD/opentad/models/roi_heads/proposal_head/pem_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6d9a5f724ef8e2192c3657c035ccb3b228d36b9a --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/proposal_head/pem_head.py @@ -0,0 +1,119 @@ +import math +import torch +import torch.nn as nn +import torch.nn.functional as F +from ...builder import HEADS, build_loss +from ...utils.iou_tools import compute_iou_torch + + +@HEADS.register_module() +class PEMHead(nn.Module): + r"""Proposal Evaluation Head, which is proposed in BMN. + Input is a proposal map [B,C,D,T], then after several conv layers with kernel size 3x3. + """ + + def __init__( + self, + in_channels, + feat_channels, + num_classes, + num_convs, + kernel_size=3, + loss=None, + ): + super().__init__() + + self.in_channels = in_channels + self.feat_channels = feat_channels + self.num_classes = num_classes + self.num_convs = num_convs + self.kernel_size = kernel_size + + # initialize layers + self._init_layers() + + # loss + self.cls_loss = build_loss(loss.cls_loss) + self.reg_loss = build_loss(loss.reg_loss) + + def _init_layers(self): + self.head = nn.Sequential() + for i in range(self.num_convs): + self.head.append( + nn.Sequential( + nn.Conv2d( + self.in_channels if i == 0 else self.feat_channels, + self.feat_channels, + kernel_size=self.kernel_size, + stride=1, + padding=self.kernel_size // 3, + ), + nn.ReLU(inplace=True), + ) + ) + self.head.append( + nn.Conv2d( + self.feat_channels, + self.num_classes, + kernel_size=1, + ) + ) + + def forward_train(self, proposal_feats, proposal_map, valid_mask, gt_segments): + proposal_pred = self.head(proposal_feats) # [B,2,D,T] + + loss = self.losses(proposal_pred, proposal_map, valid_mask, gt_segments) + return loss + + def forward_test(self, proposal_feats): + proposal_pred = self.head(proposal_feats) # [B,2,D,T] + return proposal_pred + + @torch.no_grad() + def prepare_targets(self, proposals, gt_segments): + proposals = proposals.to(gt_segments[0].device) + + gt_ious = [] + for gt_segment in gt_segments: + gt_iou = compute_iou_torch(gt_segment, proposals) # [B,N] + gt_iou = torch.max(gt_iou, dim=1)[0] + + gt_ious.append(gt_iou) + + gt_ious = torch.stack(gt_ious) + return gt_ious + + def losses(self, pred, proposal_map, valid_mask, gt_segments): + # pred [B,2,D,T], proposal_map [D,T,2], valid_mask [D,T] + + pred = pred[:, :, valid_mask].sigmoid() # [B, 2, N] + + gt_ious = self.prepare_targets(proposal_map[valid_mask, :], gt_segments) + + # classification loss - balanced BCE + loss_cls = self.cls_loss(pred[:, 0, :], gt_ious) + + # regression loss - l2 loss + loss_reg = self.reg_loss(pred[:, 1, :], gt_ious) + + losses = {"loss_cls": loss_cls, "loss_reg": loss_reg} + return losses + + +@HEADS.register_module() +class TSIHead(PEMHead): + def losses(self, pred, proposal_map, valid_mask, gt_segments): + # pred [B,2,D,T], proposal_map [D,T,2], valid_mask [D,T] + + pred = pred[:, :, valid_mask].sigmoid() # [B, 2, N] + + proposal = proposal_map[valid_mask, :] + + # classification loss - balanced BCE + loss_cls, gt_ious = self.cls_loss(pred[:, 0, :], proposal, gt_segments) + + # regression loss - l2 loss + loss_reg = self.reg_loss(pred[:, 1, :], gt_ious) + + losses = {"loss_cls": loss_cls, "loss_reg": loss_reg} + return losses diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/__init__.py b/OpenTAD/opentad/models/roi_heads/roi_extractors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d86c02ea7e13dace656f652e24ae43430774444 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/__init__.py @@ -0,0 +1,6 @@ +from .bmn_extractor import BMNExtractor +from .gtad_extractor import GTADExtractor +from .roialign_extractor import ROIAlignExtractor +from .corner_extractor import CornerExtractor + +__all__ = ["BMNExtractor", "GTADExtractor", "ROIAlignExtractor", "CornerExtractor"] diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/Align1D_cuda.cpp b/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/Align1D_cuda.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a02b45a76c53e7cbd5dd8158ed4aa07cea215e1 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/Align1D_cuda.cpp @@ -0,0 +1,41 @@ +#include +#include + +// CUDA forward declarations +at::Tensor Align_forward_cuda(const at::Tensor& input, + const at::Tensor& rois, + const float spatial_scale, + const int pooled_height, + const int sampling_ratio); + +at::Tensor Align_backward_cuda(const at::Tensor& grad, + const at::Tensor& rois, + const float spatial_scale, + const int pooled_height, + const int batch_size, + const int channels, + const int height, + const int sampling_ratio); + +// C++ interface +at::Tensor Align_forward(const at::Tensor& input, // (bs,ch,t) + const at::Tensor& rois, // (bs, start, end) + const int pooled_height, + const int sampling_ratio){ + return Align_forward_cuda( input, rois, 1.0, pooled_height, sampling_ratio); + } + +at::Tensor Align_backward(const at::Tensor& grad, + const at::Tensor& rois, + const int pooled_height, + const int batch_size, + const int channels, + const int height, + const int sampling_ratio){ + return Align_backward_cuda(grad, rois, 1.0, pooled_height, batch_size, channels, height, sampling_ratio); + } + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("forward", &Align_forward, "Align forward (CUDA)"); + m.def("backward", &Align_backward, "Align backward (CUDA)"); +} diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/Align1D_cuda_kernal.cu b/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/Align1D_cuda_kernal.cu new file mode 100644 index 0000000000000000000000000000000000000000..3bdaa73933959f0d33b5ce54b250b5150a8ad821 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/Align1D_cuda_kernal.cu @@ -0,0 +1,287 @@ +// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +// Modifies by Frost for 1D ussage +#include +#include +#include +#include +#include +#include + + + +// TODO make it in a common file +#define CUDA_1D_KERNEL_LOOP(i, n) \ + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; \ + i += blockDim.x * gridDim.x) + + +template +__device__ T linear_interpolate(const T* bottom_data, + const int height, + T t, + const int index /* index for debug only*/) { + + // deal with cases that inverse elements are out of feature map boundary + if (t < -1.0 || t > height) { + //empty + return 0; + } + + if (t <= 0) t = 0; + + int t_low = (int) t; + int t_high; + + // get closest integers to t + if (t_low >= height - 1) { + t_high = t_low = height - 1; + t = (T) t_low; + } else { + t_high = t_low + 1; + } + + // get the distance to t + T lt = t - t_low; + T ht = 1. - lt; + + // do linear interpolation + T v1 = bottom_data[t_low]; + T v2 = bottom_data[t_high]; + T w1 = ht, w2 = lt; + + T val = (w1 * v1 + w2 * v2); + // printf("Check Linear Interpolate: w1=%f, v1=%f, w2=%f, v2=%f \n", w1, v1, w2, v2); + return val; +} + +template +__global__ void Align1DForward(const int nthreads, const T* bottom_data, + const T spatial_scale, const int channels, + const int height, + const int pooled_height, + const int sampling_ratio, + const T* bottom_rois, T* top_data) { + CUDA_1D_KERNEL_LOOP(index, nthreads) { + // (n, c, pt) is an element in the pooled output + int pt = index % pooled_height; + int c = (index / pooled_height) % channels; + int n = index / pooled_height / channels; + + // printf("Debug Main Loop: get pt, c, n are %d, %d, %d \n", pt, c, n); + + const T* offset_bottom_rois = bottom_rois + n * 3; + int roi_batch_ind = offset_bottom_rois[0]; + + // Do not using rounding; this implementation detail is critical + T roi_start = offset_bottom_rois[1] * spatial_scale; + T roi_end = offset_bottom_rois[2] * spatial_scale; + // printf("Debug roi boundary: w1, w2, is %f, %f \n", roi_start,roi_end,); + + // Force malformed ROIs to be 1x1 + T roi_height = max(roi_end- roi_start, (T)1.); + T bin_size = static_cast(roi_height) / static_cast(pooled_height); + + const T* offset_bottom_data = bottom_data + (roi_batch_ind * channels + c) * height; + + // We use roi_bin_grid to sample the grid and mimic integral + int roi_bin_grid = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_height / pooled_height); // e.g., = 2 + // printf("sampling_ratio %d \n", roi_bin_grid); + + // We do average (integral) pooling inside a bin + const T count = roi_bin_grid; // e.g. = 4 + + T output_val = 0.; + for (int it = 0; it < roi_bin_grid; it ++) // e.g., it = 0, 1 + { + const T t = roi_start + pt * bin_size + static_cast(it + .5f) * bin_size / static_cast(roi_bin_grid); // e.g., 0.5, 1.5 + + T val = linear_interpolate(offset_bottom_data, height, t, index); + // printf("Debug linear_interpolate: input=height:%d, t:%f, ... ; output=val:%f \n", height, t, val); + output_val += val; + } + output_val /= count; + + top_data[index] = output_val; + } +} + + +template +__device__ void linear_interpolate_gradient( + const int height, + T t, + T & w1, T & w2, + int & t_low, int & t_high, + const int index /* index for debug only*/) { + + // deal with cases that inverse elements are out of feature map boundary + if (t < -1.0 || t > height) { + //empty + w1 = w2 = 0.; + t_low = t_high = -1; + return; + } + + if (t <= 0) t = 0; + + t_low = (int) t; + + if (t_low >= height - 1) { + t_high = t_low = height - 1; + t = (T) t_low; + } else { + t_high = t_low + 1; + } + + T lt = t - t_low; + T ht = 1. - lt; + + // T val = (w1 * v1 + w2 * v2); + // T w1 = ht, w2 = lt; + w1 = ht , w2 = lt; + + return; +} + +template +__global__ void Align1DBackwardFeature(const int nthreads, const T* top_diff, + const int num_rois, const T spatial_scale, + const int channels, const int height, + const int pooled_height, + const int sampling_ratio, + T* bottom_diff, + const T* bottom_rois) { + CUDA_1D_KERNEL_LOOP(index, nthreads) { + // (n, c, pt) is an element in the pooled output + int pt = (index ) % pooled_height; + int c = (index / pooled_height) % channels; + int n = index / pooled_height / channels; + + const T* offset_bottom_rois = bottom_rois + n * 3; + int roi_batch_ind = offset_bottom_rois[0]; + + // Do not using rounding; this implementation detail is critical + T roi_start= offset_bottom_rois[1] * spatial_scale; + T roi_end= offset_bottom_rois[2] * spatial_scale; + + // Force malformed ROIs to be 1x1 + T roi_height = max(roi_end- roi_start, (T)1.); + T bin_size = static_cast(roi_height) / static_cast(pooled_height); + + T* offset_bottom_diff = bottom_diff + (roi_batch_ind * channels + c) * height; + + int top_offset = (n * channels + c) * pooled_height; + const T* offset_top_diff = top_diff + top_offset; + const T top_diff_this_bin = offset_top_diff[pt]; + + // We use roi_bin_grid to sample the grid and mimic integral + int roi_bin_grid= (sampling_ratio > 0) ? sampling_ratio : ceil(roi_height / pooled_height); // e.g., = 2 + + // We do average (integral) pooling inside a bin + const T count = roi_bin_grid; // e.g. = 4 + + for (int it = 0; it < roi_bin_grid; it ++) // e.g., iy = 0, 1 + { + const T t = roi_start+ pt * bin_size+ static_cast(it + .5f) * bin_size/ static_cast(roi_bin_grid); // e.g., 0.5, 1.5 + + T w1, w2; + int t_low, t_high; + + linear_interpolate_gradient(height, t, w1, w2, t_low, t_high, index); + + T g1 = top_diff_this_bin * w1 / count; + T g2 = top_diff_this_bin * w2 / count; + + if (t_low >= 0 && t_high >= 0) + { + atomicAdd(offset_bottom_diff + t_low, static_cast(g1)); + atomicAdd(offset_bottom_diff + t_high, static_cast(g2)); + } // if + } // it + } // CUDA_1D_KERNEL_LOOP +} // RoIAlignBackward + + +at::Tensor Align_forward_cuda(const at::Tensor& input, + const at::Tensor& rois, + const float spatial_scale, + const int pooled_height, + const int sampling_ratio) { + AT_ASSERTM(input.type().is_cuda(), "input must be a CUDA tensor"); + AT_ASSERTM(rois.type().is_cuda(), "rois must be a CUDA tensor"); + auto num_rois = rois.size(0); + auto channels = input.size(1); + auto height = input.size(2); + + auto output = at::empty({num_rois, channels, pooled_height}, input.options()); + auto output_size = num_rois * pooled_height * channels; + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + dim3 grid(std::min(at::ceil_div((long)output_size, 512L), 4096L)); + dim3 block(512); + + // printf("Debug main function: height:%d\n", height); + + if (output.numel() == 0) { + C10_CUDA_CHECK(cudaGetLastError()); + return output; + } + + AT_DISPATCH_FLOATING_TYPES(input.type(), "Align1D_forward", [&] { + Align1DForward<<>>( + output_size, + input.contiguous().data(), + spatial_scale, + channels, + height, + pooled_height, + sampling_ratio, + rois.contiguous().data(), + output.data()); + }); + C10_CUDA_CHECK(cudaGetLastError()); + return output; +} + +// TODO remove the dependency on input and use instead its sizes -> save memory +at::Tensor Align_backward_cuda(const at::Tensor& grad, + const at::Tensor& rois, + const float spatial_scale, + const int pooled_height, + const int batch_size, + const int channels, + const int height, + const int sampling_ratio) { + AT_ASSERTM(grad.type().is_cuda(), "grad must be a CUDA tensor"); + AT_ASSERTM(rois.type().is_cuda(), "rois must be a CUDA tensor"); + + auto num_rois = rois.size(0); + auto grad_input = at::zeros({batch_size, channels, height}, grad.options()); + + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + dim3 grid(std::min(at::ceil_div((long)grad.numel(), 512L), 4096L)); + dim3 block(512); + + // handle possibly empty gradients + if (grad.numel() == 0) { + C10_CUDA_CHECK(cudaGetLastError()); + return grad_input; + } + + AT_DISPATCH_FLOATING_TYPES(grad.type(), "ROIAlign_backward", [&] { + Align1DBackwardFeature<<>>( + grad.numel(), + grad.contiguous().data(), + num_rois, + spatial_scale, + channels, + height, + pooled_height, + sampling_ratio, + grad_input.data(), + rois.contiguous().data()); + }); + C10_CUDA_CHECK(cudaGetLastError()); + return grad_input; +} \ No newline at end of file diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/align.py b/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/align.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9089a0828cf22e4a36030cf29ca1dca6335217 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/align.py @@ -0,0 +1,89 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +import torch +from torch import nn +from torch.autograd import Function +from torch.autograd.function import once_differentiable +import Align1D as _align_1d + + +class _Align1D(Function): + @staticmethod + def forward(ctx, input, roi, feature_dim, ratio): + ctx.save_for_backward(roi) + ctx.feature_dim = feature_dim + ctx.input_shape = input.size() + ctx.sampling_ratio = ratio + output = _align_1d.forward(input, roi, feature_dim, ratio) + return output + + @staticmethod + @once_differentiable + def backward(ctx, grad_output): + (rois,) = ctx.saved_tensors + feature_dim = ctx.feature_dim + bs, ch, t = ctx.input_shape + ratio = ctx.sampling_ratio + grad_input = _align_1d.backward(grad_output, rois, feature_dim, bs, ch, t, ratio) + return grad_input, None, None, None, None + + +align1d = _Align1D.apply + + +class Align1DLayer(nn.Module): + def __init__(self, feature_dim, ratio=0): + super(Align1DLayer, self).__init__() + self.feature_dim = feature_dim + self.ratio = ratio + + def forward(self, input, rois): + # print('- input shape is', input.shape) + # print('- input mean is', input.mean()) + # print('- rois shape is', rois.shape) + # print('- rois is on', rois.get_device()) + assert input.device == rois.device, ( + "Align operation requires " + + "both feature and roi are on the same device! " + + "Get feature on {} but roi on {}".format(input.device, rois.device) + ) + + # out = align1d(input, rois, self.feature_dim, self.ratio) + + # this is a trick for deterministic implementation + # see https://github.com/open-mmlab/mmdetection/issues/9831 + out = align1d( + input.half().double(), + rois.half().double(), + self.feature_dim, + self.ratio, + ).to(input.dtype) + + # print('- output shape is', out.shape) + # print('- output mean is', out.mean()) + return out + + def __repr__(self): + tmpstr = self.__class__.__name__ + "(" + tmpstr += f"feature_dim={str(self.feature_dim)}, " + tmpstr += f"sampling_ratio={str(self.ratio)})" + return tmpstr + + +if __name__ == "__main__": + layer = Align1DLayer(3, ratio=6) + # layer = torch.nn.DataParallel(layer, device_ids=[0,1]) + # input = torch.tensor([[[1.,2,3,4,5,6,7,8,9,10],[11,12,13,14,15,16,17,18,19,20]]]).cuda() + input = torch.tensor( + [ + [ + [0.0, 1.0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], + [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30], + ] + ] + ).cuda() + # proposal = torch.tensor([[0,-0.5,9.5],[0,0.1,0.9]]).cuda() + proposal = torch.tensor([[0, 1.5, 19.5]]).cuda() + output = layer(input, proposal) + # print("output has shape {}, with mean {}".format(output.shape, torch.mean(output))) + torch.set_printoptions(linewidth=180) + print(output) diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/setup.py b/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3d96218f52efb5fd6fe4c060d1cd072a1d9fdf --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/align1d/setup.py @@ -0,0 +1,24 @@ +from setuptools import setup +from torch.utils.cpp_extension import CUDAExtension, BuildExtension + +setup( + name="Align1D", + version="2.5.0", + author="Frost Mengmeng Xu", + author_email="xu.frost@gmail.com", + description="A small package for 1d aligment in cuda", + long_description="Update: support pytorch 1.11", + long_description_content_type="text/markdown", + url="https://github.com/Frostinassiky/G-TAD", + ext_modules=[ + CUDAExtension( + name="Align1D", + sources=[ + "Align1D_cuda.cpp", + "Align1D_cuda_kernal.cu", + ], + extra_compile_args={"cxx": [], "nvcc": ["--expt-relaxed-constexpr", "-allow-unsupported-compiler"]}, + ) + ], + cmdclass={"build_ext": BuildExtension}, +) diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/bmn_extractor.py b/OpenTAD/opentad/models/roi_heads/roi_extractors/bmn_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..c9fa17ce3af21a688f721997f6ba26f29acd2949 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/bmn_extractor.py @@ -0,0 +1,113 @@ +import torch +import torch.nn as nn +import numpy as np +import math +from ...builder import ROI_EXTRACTORS + + +@ROI_EXTRACTORS.register_module() +class BMNExtractor(nn.Module): + """BM layer, implemented in BMN""" + + def __init__( + self, + in_channels=256, + hid_channels=128, + roi_channels=512, + out_channels=128, + tscale=128, + dscale=128, + num_sample=32, + num_sample_perbin=3, + prop_extend_ratio=0.5, + ): + super(BMNExtractor, self).__init__() + + self.num_sample = num_sample + self.num_sample_perbin = num_sample_perbin + self.prop_extend_ratio = prop_extend_ratio + + self.reduce_dim = nn.Sequential( + nn.Conv1d( + in_channels=in_channels, + out_channels=hid_channels, + kernel_size=3, + stride=1, + padding=1, + ), + nn.ReLU(inplace=True), + ) + + self.conv3d = nn.Sequential( + nn.Conv2d( + hid_channels, + roi_channels, + kernel_size=(self.num_sample, 1), + stride=(self.num_sample, 1), + ), + nn.ReLU(inplace=True), + ) + + self.conv2d = nn.Sequential( + nn.Conv2d(roi_channels, out_channels, kernel_size=1, stride=1, padding=0), + nn.ReLU(inplace=True), + ) + self._get_interp1d_mask(tscale, dscale) + + def forward(self, x): + x = self.reduce_dim(x) # [B, 128, tscale] + map_base = torch.tensordot(x, self.sample_mask.to(x.device), dims=([2], [0])) # [B, 128, 32, dscale, tscale] + dscale, tscale = map_base.shape[-2:] + map_base = map_base.flatten(3, 4) # [B, 128, 32, dscale * tscale] + map_3d = self.conv3d(map_base) # [B, 512, 1, dscale*tscale] + map_2d = map_3d.squeeze(2).unflatten(2, (dscale, tscale)) # [B, 512, dscale, tscale] + map_2d = self.conv2d(map_2d) # [B, out_dim, dscale, tscale] + return map_2d + + def _get_interp1d_mask(self, tscale, dscale): + # generate sample mask for each point in Boundary-Matching Map + mask_mat = [] + for start_index in range(tscale): + mask_mat_vector = [] + for duration_index in range(dscale): + if start_index + duration_index < tscale: + p_xmin = start_index + p_xmax = start_index + duration_index + center_len = float(p_xmax - p_xmin) + 1 + sample_xmin = p_xmin - center_len * self.prop_extend_ratio + sample_xmax = p_xmax + center_len * self.prop_extend_ratio + p_mask = self._get_interp1d_bin_mask( + sample_xmin, + sample_xmax, + tscale, + self.num_sample, + self.num_sample_perbin, + ) + else: + p_mask = np.zeros([tscale, self.num_sample]) + mask_mat_vector.append(p_mask) + mask_mat_vector = np.stack(mask_mat_vector, axis=2) + mask_mat.append(mask_mat_vector) + mask_mat = np.stack(mask_mat, axis=3).astype(np.float32) + self.sample_mask = torch.Tensor(mask_mat) + + def _get_interp1d_bin_mask(self, seg_xmin, seg_xmax, tscale, num_sample, num_sample_perbin): + # generate sample mask for a boundary-matching pair + plen = float(seg_xmax - seg_xmin) + plen_sample = plen / (num_sample * num_sample_perbin - 1.0) + total_samples = [seg_xmin + plen_sample * ii for ii in range(num_sample * num_sample_perbin)] + p_mask = [] + for idx in range(num_sample): + bin_samples = total_samples[idx * num_sample_perbin : (idx + 1) * num_sample_perbin] + bin_vector = np.zeros([tscale]) + for sample in bin_samples: + sample_upper = math.ceil(sample) + sample_decimal, sample_down = math.modf(sample) + if int(sample_down) <= (tscale - 1) and int(sample_down) >= 0: + bin_vector[int(sample_down)] += 1 - sample_decimal + if int(sample_upper) <= (tscale - 1) and int(sample_upper) >= 0: + bin_vector[int(sample_upper)] += sample_decimal + bin_vector = 1.0 / num_sample_perbin * bin_vector + p_mask.append(bin_vector) + p_mask = np.stack(p_mask, axis=1) + return p_mask diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/boundary_max_pooling_cuda.cpp b/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/boundary_max_pooling_cuda.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b7e8d2e2268d43d9232353672a0e0946e6e98aa --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/boundary_max_pooling_cuda.cpp @@ -0,0 +1,48 @@ +#include +#include + + +int boundary_max_pooling_cuda_forward( + const at::Tensor& input, + const at::Tensor& segments, + const at::Tensor& output +); + +int boundary_max_pooling_cuda_backward( + const at::Tensor& grad_output, + const at::Tensor& input, + const at::Tensor& segments, + const at::Tensor& grad_input +); + +at::Tensor boundary_max_pooling_forward( + const at::Tensor& input, + const at::Tensor& segments) { + + const int batch_size = input.size(0); + const int channels = input.size(1); + const int seg_num = segments.size(1); + + auto output = torch::zeros({batch_size, channels, seg_num}, input.options()); + boundary_max_pooling_cuda_forward(input, segments, output); + return output; +} + +at::Tensor boundary_max_pooling_backward( + const at::Tensor& grad_output, + const at::Tensor& input, + const at::Tensor& segments) { + + const int batch_size = input.size(0); + const int channels = input.size(1); + const int t_dim = input.size(2); + + auto grad_input = torch::zeros({batch_size, channels, t_dim}, grad_output.options()); + boundary_max_pooling_cuda_backward(grad_output, input, segments, grad_input); + return grad_input; +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("forward", &boundary_max_pooling_forward, "Boundary max pooling forward (CUDA)"); + m.def("backward", &boundary_max_pooling_backward, "Boundary max pooling backward (CUDA)"); +} \ No newline at end of file diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/boundary_max_pooling_kernel.cu b/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/boundary_max_pooling_kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..20d4dc5460e4a292b09f4d61b678ebaa52e8d2ce --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/boundary_max_pooling_kernel.cu @@ -0,0 +1,152 @@ +#include +#include +#include + + +#define CUDA_1D_KERNEL_LOOP(i, n) \ + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; \ + i += blockDim.x * gridDim.x) + +#define THREADS_PER_BLOCK 1024 + +inline int GET_BLOCKS(const int N) { + int optimal_block_num = (N + THREADS_PER_BLOCK - 1) / THREADS_PER_BLOCK; + int max_block_num = 65000; + return min(optimal_block_num, max_block_num); +} + + +template +__global__ void BoundaryPoolingForward( + const int nthreads, + const scalar_t* input, + const scalar_t* segments, + scalar_t* output, + const int channels, + const int tscale, + const int seg_num) { + CUDA_1D_KERNEL_LOOP(index, nthreads) { + const int k = index % seg_num; + const int c = (index / seg_num) % channels; + const int n = index / seg_num / channels; + const int seg_type = c / (channels / 2); + const int seg_index = n * seg_num * 4 + k * 4 + seg_type * 2; + scalar_t maxn, val; + int l = static_cast(segments[seg_index]); + int r = static_cast(segments[seg_index + 1]); + l = min(max(0, l), tscale - 1); + r = min(max(0, r), tscale - 1); + maxn = input[n * channels * tscale + c * tscale + l]; + for (int i = l + 1; i <= r; i++) { + val = input[n * channels * tscale + c * tscale + i]; + if (val > maxn) { + maxn = val; + } + } + output[index] = maxn; + } +} + +template +__global__ void BoundaryPoolingBackward( + const int nthreads, + const scalar_t* grad_output, + const scalar_t* input, + const scalar_t* segments, + scalar_t* grad_input, + const int channels, + const int tscale, + const int seg_num) { + CUDA_1D_KERNEL_LOOP(index, nthreads) { + const int k = index % seg_num; + const int c = (index / seg_num) % channels; + const int n = index / seg_num / channels; + const int seg_type = c / (channels / 2); + const int seg_index = n * seg_num * 4 + k * 4 + seg_type * 2; + scalar_t maxn, val; + int argmax; + int l = static_cast(segments[seg_index]); + int r = static_cast(segments[seg_index + 1]); + l = min(max(0, l), tscale - 1); + r = min(max(0, r), tscale - 1); + maxn = input[n * channels * tscale + c * tscale + l]; + argmax = l; + for (int i = l + 1; i <= r; i++) { + val = input[n * channels * tscale + c * tscale + i]; + if (val > maxn) { + maxn = val; + argmax = i; + } + } + scalar_t grad = grad_output[index]; + atomicAdd(grad_input + n * channels * tscale + c * tscale + argmax, grad); + } +} + +int boundary_max_pooling_cuda_forward( + const at::Tensor& input, + const at::Tensor& segments, + const at::Tensor& output) { + AT_ASSERTM(input.type().is_cuda(), "input must be a CUDA tensor"); + AT_ASSERTM(segments.type().is_cuda(), "segments must be a CUDA tensor"); + const int batch_size = input.size(0); + const int channels = input.size(1); + const int tscale = input.size(2); + const int seg_num = segments.size(1); + const int output_size = batch_size * channels * seg_num; + + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + input.scalar_type(), "BoundaryMaxPoolingForward", ([&] { + + BoundaryPoolingForward + <<>>( + output_size, + input.data_ptr(), + segments.data_ptr(), + output.data_ptr(), + channels, + tscale, + seg_num); + })); + + C10_CUDA_CHECK(cudaGetLastError()); + return 1; +} + +int boundary_max_pooling_cuda_backward( + const at::Tensor& grad_output, + const at::Tensor& input, + const at::Tensor& segments, + const at::Tensor& grad_input) { + AT_ASSERTM(input.type().is_cuda(), "input must be a CUDA tensor"); + AT_ASSERTM(segments.type().is_cuda(), "segments must be a CUDA tensor"); + AT_ASSERTM(grad_output.type().is_cuda(), "grad_output must be a CUDA tensor"); + const int batch_size = grad_output.size(0); + const int channels = grad_output.size(1); + const int tscale = grad_output.size(2); + const int seg_num = segments.size(1); + + const int output_size = batch_size * channels * seg_num; + + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + input.scalar_type(), "BoundaryMaxPoolingBackward", ([&] { + + BoundaryPoolingBackward + <<>>( + output_size, + grad_output.data_ptr(), + input.data_ptr(), + segments.data_ptr(), + grad_input.data_ptr(), + channels, + tscale, + seg_num); + })); + + C10_CUDA_CHECK(cudaGetLastError()); + return 1; +} \ No newline at end of file diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/boundary_pooling_op.py b/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/boundary_pooling_op.py new file mode 100644 index 0000000000000000000000000000000000000000..98680cbc77df3997b96d2a9550b42e1253db21d6 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/boundary_pooling_op.py @@ -0,0 +1,28 @@ +import torch.nn as nn +from torch.autograd import Function + +import boundary_max_pooling_cuda + + +class BoundaryMaxPoolingFunction(Function): + @staticmethod + def forward(ctx, input, segments): + output = boundary_max_pooling_cuda.forward(input, segments) + ctx.save_for_backward(input, segments) + return output + + @staticmethod + def backward(ctx, grad_output): + if not grad_output.is_contiguous(): + grad_output = grad_output.contiguous() + input, segments = ctx.saved_tensors + grad_input = boundary_max_pooling_cuda.backward(grad_output, input, segments) + return grad_input, None + + +class BoundaryMaxPooling(nn.Module): + def __init__(self): + super(BoundaryMaxPooling, self).__init__() + + def forward(self, input, segments): + return BoundaryMaxPoolingFunction.apply(input, segments) diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/setup.py b/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee0efa008f2a3d62e638b137ce51f768906d5c8 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/boundary_pooling/setup.py @@ -0,0 +1,21 @@ +from setuptools import setup +from torch.utils.cpp_extension import CUDAExtension, BuildExtension + +setup( + name="AFSD", + version="1.0", + description="Learning Salient Boundary Feature for Anchor-free " "Temporal Action Localization", + author="Chuming Lin, Chengming Xu", + author_email="chuminglin@tencent.com, cmxu18@fudan.edu.cn", + ext_modules=[ + CUDAExtension( + name="boundary_max_pooling_cuda", + sources=[ + "boundary_max_pooling_cuda.cpp", + "boundary_max_pooling_kernel.cu", + ], + extra_compile_args={"cxx": [], "nvcc": ["--expt-relaxed-constexpr", "-allow-unsupported-compiler"]}, + ) + ], + cmdclass={"build_ext": BuildExtension}, +) diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/corner_extractor.py b/OpenTAD/opentad/models/roi_heads/roi_extractors/corner_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8dfa14d5b913a6e5e8ca6c4d2d30e91ff66379 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/corner_extractor.py @@ -0,0 +1,87 @@ +import torch +from ...builder import ROI_EXTRACTORS + + +@ROI_EXTRACTORS.register_module() +class CornerExtractor(object): + def __init__(self, beta=8.0, base_stride=2, tscale=256): + super(CornerExtractor, self).__init__() + self.beta = beta + self.tscale = tscale + self.base_stride = base_stride + + def __call__(self, feat_frmlvl, loc_boxes): + """ + Args: + feat_frmlvl: B, channel, temporal + loc_box: list of B length, B*[num_props_v, 2] + Returns: + start_feats: B*num_props, channel, temporal (3) + end_feats: B*num_props, channel, temporal (3) + """ + B, C, T = feat_frmlvl.shape + + # for each video + start_feats_center = [] + start_feats_left = [] + start_feats_right = [] + end_feats_center = [] + end_feats_left = [] + end_feats_right = [] + for i, loc_box in enumerate(loc_boxes): + loc_box = torch.clamp(loc_box, min=0.0, max=(self.tscale) - 1) + boundary_length = (loc_box[:, 1] - loc_box[:, 0] + 1) / self.beta + + # Starts + starts = torch.clamp( + (loc_box[:, 0] / self.base_stride).to(dtype=torch.long), + min=0, + max=T - 1, + ) + starts_left = torch.clamp( + ((loc_box[:, 0] - boundary_length) / self.base_stride).to(dtype=torch.long), + min=0, + max=T - 1, + ) + starts_right = torch.clamp( + ((loc_box[:, 0] + boundary_length) / self.base_stride).to(dtype=torch.long), + min=0, + max=T - 1, + ) + + start_feats_center.append(feat_frmlvl[i, :, starts].permute(1, 0)) + start_feats_left.append(feat_frmlvl[i, :, starts_left].permute(1, 0)) + start_feats_right.append(feat_frmlvl[i, :, starts_right].permute(1, 0)) + + # Ends + ends = torch.clamp( + (loc_box[:, 1] / self.base_stride).to(dtype=torch.long), + min=0, + max=T - 1, + ) + ends_left = torch.clamp( + ((loc_box[:, 1] - boundary_length) / self.base_stride).to(dtype=torch.long), + min=0, + max=T - 1, + ) + ends_right = torch.clamp( + ((loc_box[:, 1] + boundary_length) / self.base_stride).to(dtype=torch.long), + min=0, + max=T - 1, + ) + + end_feats_center.append(feat_frmlvl[i, :, ends].permute(1, 0)) + end_feats_left.append(feat_frmlvl[i, :, ends_left].permute(1, 0)) + end_feats_right.append(feat_frmlvl[i, :, ends_right].permute(1, 0)) + + start_feats_center = torch.cat(start_feats_center, dim=0) + start_feats_left = torch.cat(start_feats_left, dim=0) + start_feats_right = torch.cat(start_feats_right, dim=0) + start_feats = torch.stack((start_feats_left, start_feats_center, start_feats_right), dim=-1) + + end_feats_center = torch.cat(end_feats_center, dim=0) + end_feats_left = torch.cat(end_feats_left, dim=0) + end_feats_right = torch.cat(end_feats_right, dim=0) + end_feats = torch.stack((end_feats_left, end_feats_center, end_feats_right), dim=-1) + + return torch.cat((start_feats, end_feats), dim=-1) diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/gtad_extractor.py b/OpenTAD/opentad/models/roi_heads/roi_extractors/gtad_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed4620e9c475fbbe42284d16d39dd56c3a68fc7 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/gtad_extractor.py @@ -0,0 +1,83 @@ +import torch +import torch.nn as nn +from ...builder import ROI_EXTRACTORS +from ...bricks import GCNeXt +from ...bricks.gcnext import get_graph_feature +from .align1d.align import Align1DLayer + + +@ROI_EXTRACTORS.register_module() +class GTADExtractor(nn.Module): + """GraphAlign layer, implemented in GTAD""" + + def __init__( + self, + in_channels=256, + out_channels=128, + tscale=128, + dscale=128, + k=3, + roi_size=32, + context_size=4, + prop_extend_ratio=0.5, + ): + super(GTADExtractor, self).__init__() + + self.k = k + self.prop_extend_ratio = prop_extend_ratio + + self.gcnext = GCNeXt(in_channels, in_channels, k=3, groups=32) + + self.align_inner = Align1DLayer(roi_size, ratio=0) + self.align_context = Align1DLayer(context_size) + + self.conv2d = nn.Sequential( + nn.Conv2d( + in_channels * (roi_size + context_size), + out_channels, + kernel_size=1, + stride=1, + padding=0, + ), + nn.ReLU(inplace=True), + ) + self._get_anchors(tscale, dscale) + + def forward(self, x): + bs = x.shape[0] + device = x.device + dscale, tscale = self.anchors.shape[:2] + + x = self.gcnext(x) + + # add batch idx + anchors = self.anchors.reshape(-1, 2).unsqueeze(0).repeat(bs, 1, 1) + bs_idxs = torch.arange(bs).view(bs, 1, 1).float() + bs_idxs = bs_idxs.repeat(1, anchors.shape[1], 1) + anchors = torch.cat((bs_idxs, anchors), dim=2).to(device) # [B,K,3] + anchors = anchors.view(-1, 3) # [B*dscale*tscale,3] + + feat_inner = self.align_inner(x, anchors) # (bs*dscale*tscal, ch, roi_size) + + feat = get_graph_feature(x, k=self.k, style=2) # (bs,ch,100) -> (bs, ch, 100, k) + feat = feat.mean(dim=-1, keepdim=False) # (bs. 2*ch, 100) + feat_context = self.align_context(feat, anchors) # (bs*dscale*tscal, ch, roi_size//2) + feat = torch.cat((feat_inner, feat_context), dim=2).view(bs, dscale, tscale, -1) + feat = feat.permute(0, 3, 1, 2).contiguous() # (bs,2*ch*(-1),t,t) + + map_2d = self.conv2d(feat) # [B, out_dim, dscale, tscale] + return map_2d + + def _get_anchors(self, tscale, dscale): + anchors = [] + for dur_idx in range(dscale): + for start_idx in range(tscale): + end_idx = start_idx + dur_idx + 1 + if end_idx <= tscale: + center_len = dur_idx + 1 + sample_xmin = start_idx - center_len * self.prop_extend_ratio + sample_xmax = end_idx + center_len * self.prop_extend_ratio + anchors.append([sample_xmin, sample_xmax]) + else: + anchors.append([0, 0]) + self.anchors = torch.Tensor(anchors).reshape(dscale, tscale, 2) diff --git a/OpenTAD/opentad/models/roi_heads/roi_extractors/roialign_extractor.py b/OpenTAD/opentad/models/roi_heads/roi_extractors/roialign_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..c7fea53f9fd2b310f63d200b90f2bc2b2adc77f7 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/roi_extractors/roialign_extractor.py @@ -0,0 +1,150 @@ +import torch +import torch.nn as nn +import torchvision +from ...builder import ROI_EXTRACTORS +from .align1d.align import Align1DLayer + + +@ROI_EXTRACTORS.register_module() +class ROIAlignExtractor(nn.Module): + def __init__( + self, + roi_size=8, + extend_ratio=0.5, + base_stride=1, + fpn_extract=False, + base_scale=8, + method="torchvision", + deterministic=False, + ): + super(ROIAlignExtractor, self).__init__() + + self.roi_size = roi_size + self.extend_ratio = extend_ratio + self.base_stride = base_stride + self.fpn_extract = fpn_extract + self.base_scale = base_scale + self.method = method + self.deterministic = deterministic + + if self.method == "align1d": + self.align1d = Align1DLayer(self.roi_size, ratio=0) + + def forward(self, feat_list, proposals): + # proposals: list [K,2]: 0~tscale + + if self.fpn_extract: # todo, maybe wrong + assert isinstance(feat_list, (list, tuple)) + num_levels = len(feat_list) + + # assign proposals to different levels + # proposals_scale < base_scale, level 0 + # base_scale <= proposals_scale < base_scale*2 , level 1 + # base_scale*2 <= proposals_scale < base_scale*4 , level 2 + concat_proposals = torch.cat(proposals, dim=0) # [sum(K),2] + proposals_scale = (concat_proposals[:, 1] - concat_proposals[:, 0]).clamp(min=1e-6) # [sum(K)] + proposals_level = torch.ceil(torch.log2(proposals_scale / (self.base_scale * self.base_stride))) + proposals_level = proposals_level.clamp(min=0, max=num_levels - 1).long() # [sum(K)] long + + # add proposals batch idxs + proposals_batch_idxs = [torch.ones(proposal.shape[0]) * i for i, proposal in enumerate(proposals)] + proposals_batch_idxs = torch.cat(proposals_batch_idxs, dim=0).to(concat_proposals.device).long() + proposals_batch_idxs = proposals_batch_idxs.unsqueeze(-1) # [sum(K), 1] + + # get proposal feature + proposals_feat = feat_list[0].new_zeros( + concat_proposals.shape[0], feat_list[0].shape[1], self.roi_size + ) # [sum(K),C,res] + for i in range(num_levels): + mask = proposals_level == i + idxs = mask.nonzero(as_tuple=False).squeeze(1) + if idxs.numel() > 0: + ext_proposals_ = self._get_extend_proposals(concat_proposals[idxs]) / 2**i # [sum(K)',2] + ext_proposals_ = torch.cat((proposals_batch_idxs[idxs], ext_proposals_), dim=1) # [sum(K)',3] + proposals_feat_ = self.align_tool(feat_list[i], ext_proposals_) # directly use align_tool + proposals_feat[idxs] = proposals_feat_.squeeze(-1) # [sum(K),C,res] + # return the concat proposals_feat + + else: # use the first level + if isinstance(feat_list, (list, tuple)): + feat = feat_list[0] + elif isinstance(feat_list, torch.Tensor): + feat = feat_list + else: + raise TypeError("feat_list must be list or tensor") + + ext_proposals = self._get_extend_proposals(proposals) # [B,K,2] + proposals_feat = self._align(feat, ext_proposals) + return proposals_feat # [B,K,C,res] + + def _get_extend_proposals(self, proposals): + def extend(proposals): + proposals_len = proposals[..., 1] - proposals[..., 0] + proposals = torch.stack( + ( + proposals[..., 0] - self.extend_ratio * proposals_len, + proposals[..., 1] + self.extend_ratio * proposals_len, + ), + dim=-1, + ) + return proposals + + if isinstance(proposals, list): # list [K,2] + return [extend(proposal) / self.base_stride for proposal in proposals] + elif isinstance(proposals, torch.Tensor): # [B,K,2] + return extend(proposals) / self.base_stride + + def _align(self, feature, proposals): + # add batch idx + if isinstance(proposals, list): + batch_proposals = [] + for batch_id, proposal in enumerate(proposals): + proposal_id = proposal.new_full((proposal.shape[0], 1), batch_id) + batch_proposals.append(torch.cat((proposal_id, proposal), dim=-1)) + batch_proposals = torch.cat(batch_proposals, dim=0) + + proposals_feat = self.align_tool(feature, batch_proposals) # [sum(K),C,res,1] + proposals_feat = proposals_feat.squeeze(-1) # [sum(K),C,res] + + elif isinstance(proposals, torch.Tensor): + # proposals.dim() == 3: # [B,K,2] + bs, K = proposals.shape[:2] + bs_idxs = torch.arange(bs).view(bs, 1, 1).repeat(1, K, 1).to(proposals.device) + proposals = torch.cat((bs_idxs, proposals), dim=2) # [B,K,3] + proposals = proposals.view(-1, 3) # [B*K,3] + + proposals_feat = self.align_tool(feature, proposals) # [B*K,C,res,1] + proposals_feat = proposals_feat.unflatten(dim=0, sizes=(bs, K)).squeeze(-1) # [B,K,C,res] + return proposals_feat + + def align_tool(self, feature, proposals): + if self.deterministic: + original_dtype = feature.dtype + feature = feature.half().double() + proposals = proposals.half().double() + + if self.method == "torchvision": + # use torchvision align + pseudo_input = feature.unsqueeze(3) # [B,C,T,1] + pseudo_bbox = torch.stack( + ( + proposals[:, 0], + torch.zeros_like(proposals[:, 0]), + proposals[:, 1], + torch.ones_like(proposals[:, 0]), + proposals[:, 2], + ), + dim=1, + ) # B*K, 5 + proposals_feat = torchvision.ops.roi_align( + pseudo_input, + pseudo_bbox, + output_size=(self.roi_size, 1), + aligned=True, + ) + elif self.method == "align1d": # use align1d align + proposals_feat = self.align1d(feature, proposals) + + if self.deterministic: + proposals_feat = proposals_feat.to(original_dtype) + return proposals_feat diff --git a/OpenTAD/opentad/models/roi_heads/standard_map_head.py b/OpenTAD/opentad/models/roi_heads/standard_map_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c6395cef398c6d9f6b773fddb9aa2fbf95975cd9 --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/standard_map_head.py @@ -0,0 +1,37 @@ +import torch.nn as nn +from ..builder import HEADS, build_proposal_generator, build_roi_extractor, build_head + + +@HEADS.register_module() +class StandardProposalMapHead(nn.Module): + def __init__( + self, + proposal_generator, + proposal_roi_extractor, + proposal_head=None, + ): + super().__init__() + + self.proposal_generator = build_proposal_generator(proposal_generator) + self.proposal_roi_extractor = build_roi_extractor(proposal_roi_extractor) + self.proposal_head = build_head(proposal_head) + + def forward_train(self, x, proposal_list, gt_segments, gt_labels, **kwargs): + # proposals generator + proposal_map, valid_mask = self.proposal_generator() + + # roi align to get the proposal feature + proposal_feats = self.proposal_roi_extractor(x) + + # head forward + losses = self.proposal_head.forward_train(proposal_feats, proposal_map, valid_mask, gt_segments) + + return losses + + def forward_test(self, x, **kwargs): + # proposal feature + proposal_feats = self.proposal_roi_extractor(x) + + # head forward + proposal_pred = self.proposal_head.forward_test(proposal_feats) + return proposal_pred diff --git a/OpenTAD/opentad/models/roi_heads/standard_roi_head.py b/OpenTAD/opentad/models/roi_heads/standard_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..581ef9062b1bad81c0c956c1d81757c517dadf6c --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/standard_roi_head.py @@ -0,0 +1,54 @@ +import torch.nn as nn +from ..builder import HEADS, build_proposal_generator, build_roi_extractor, build_head + + +@HEADS.register_module() +class StandardRoIHead(nn.Module): + def __init__( + self, + proposal_roi_extractor, + proposal_head, + proposal_generator=None, + ): + super().__init__() + + self.proposal_roi_extractor = build_roi_extractor(proposal_roi_extractor) + + self.proposal_head = build_head(proposal_head) + + if proposal_generator != None: + self.proposal_generator = build_proposal_generator(proposal_generator) + + @property + def with_proposal_generator(self): + """bool: whether the roi head's proposals are initialized by proposal_generator""" + return hasattr(self, "proposal_generator") and self.proposal_generator is not None + + def forward_train(self, x, proposal_list, gt_segments, gt_labels, **kwargs): + # (Optional) proposals generator + if self.with_proposal_generator: + proposal_list = self.proposal_generator() + + # roi align to get the proposal feature + proposal_feats = self.proposal_roi_extractor(x, proposal_list) # [B,K,C,res] + + # head forward + losses, _ = self.proposal_head.forward_train( + proposal_feats, + proposal_list, + gt_segments, + gt_labels, + ) + return losses + + def forward_test(self, x, proposal_list, **kwargs): + # (Optional) proposals generator + if self.with_proposal_generator: + proposal_list = self.proposal_generator() + + # proposal feature + proposal_feats = self.proposal_roi_extractor(x, proposal_list) # [B,K,C,res] + + # head forward + proposals, scores = self.proposal_head.forward_test(proposal_feats, proposal_list) + return proposals, scores diff --git a/OpenTAD/opentad/models/roi_heads/vsgn_roi_head.py b/OpenTAD/opentad/models/roi_heads/vsgn_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..520df755a9c192b666318b949c63d9e1845c719e --- /dev/null +++ b/OpenTAD/opentad/models/roi_heads/vsgn_roi_head.py @@ -0,0 +1,99 @@ +import torch +import torch.nn as nn +from ..dense_heads.vsgn_rpn_head import prepare_targets, giou_loss +from ..builder import HEADS, build_roi_extractor + + +@HEADS.register_module() +class VSGNRoIHead(nn.Module): + def __init__( + self, + in_channels=256, + iou_thr=0.7, + roi_extractor=None, + loss_loc=None, + ): + super(VSGNRoIHead, self).__init__() + self.in_channels = in_channels + self.iou_thr = iou_thr + + self.roi_extractor = build_roi_extractor(roi_extractor) + self.get_loc_towers() + + # maintain an EMA of #foreground to stabilize the loss normalizer + # useful for small mini-batch training + self.loss_normalizer_reg = 100 + self.loss_normalizer_momentum = 0.9 + + def get_loc_towers(self): + self.start_conv = nn.Sequential( + nn.Conv1d( + in_channels=self.in_channels, + out_channels=self.in_channels, + kernel_size=3, + stride=2, + padding=0, + groups=1, + ), + nn.ReLU(inplace=True), + nn.Conv1d(in_channels=self.in_channels, out_channels=1, kernel_size=1), + ) + + self.end_conv = nn.Sequential( + nn.Conv1d( + in_channels=self.in_channels, + out_channels=self.in_channels, + kernel_size=3, + stride=2, + padding=0, + groups=1, + ), + nn.ReLU(inplace=True), + nn.Conv1d(in_channels=self.in_channels, out_channels=1, kernel_size=1), + ) + + def forward_train(self, feats, roi_bounds, gt_segments=None, gt_labels=None, return_loss=True): + # extract start, end corner features + roi_feats = self.roi_extractor(feats[0], roi_bounds) # bs*num_props_v, C, temporal (6) + start_feats, end_feats = torch.chunk(roi_feats, 2, dim=-1) + + # get offsets + start_offsets = self.start_conv(start_feats).squeeze(-1) + end_offsets = self.end_conv(end_feats).squeeze(-1) + + # refine proposals + B, N = roi_bounds.shape[:2] + loc_pred = torch.stack( + [ + roi_bounds[:, :, 0] + start_offsets.reshape(B, N), + roi_bounds[:, :, 1] + end_offsets.reshape(B, N), + ], + dim=-1, + ) + + if return_loss: + # Special GT for VSGN: + # 1) Labels shift by including background = 0; + # 2) gt_segments has the third dimension as gt_labels + gts = [torch.cat((gt_b, gt_l[:, None] + 1), dim=-1) for gt_b, gt_l in zip(gt_segments, gt_labels)] + return self.cal_loc_loss(loc_pred, gts, roi_bounds) + else: + return loc_pred + + def forward_test(self, feats, roi_bounds, **kwargs): + return self.forward_train(feats, roi_bounds, return_loss=False) + + def cal_loc_loss(self, loc_pred, gt_bbox, anchors): + cls_labels, loc_targets = prepare_targets(anchors, gt_bbox, self.iou_thr) + + pos_inds = torch.nonzero(cls_labels > 0).squeeze(1) + loc_pred = loc_pred.flatten(0, 1) + + # update the loss normalizer + self.loss_normalizer_reg = self.loss_normalizer_momentum * self.loss_normalizer_reg + ( + 1 - self.loss_normalizer_momentum + ) * max(pos_inds.numel(), 1) + + loc_loss = giou_loss(loc_pred[pos_inds], loc_targets[pos_inds]) / self.loss_normalizer_reg + + return {"loss_stage2_loc": loc_loss} diff --git a/OpenTAD/opentad/models/transformer/__init__.py b/OpenTAD/opentad/models/transformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3cf3b7c10ffa54da58852865c357013805cbc69 --- /dev/null +++ b/OpenTAD/opentad/models/transformer/__init__.py @@ -0,0 +1,19 @@ +from .encoder.detr_encoder import DETREncoder +from .decoder.detr_decoder import DETRDecoder +from .detr_transformer import DETRTransformer +from .encoder.deformable_encoder import DeformableDETREncoder +from .decoder.deformable_decoder import DeformableDETRDecoder +from .deformable_detr_transformer import DeformableDETRTransformer +from .tadtr_transformer import TadTRTransformer +from .matcher.hungarian_matcher import HungarianMatcher + +__all__ = [ + "DETRTransformer", + "DeformableDETRTransformer", + "TadTRTransformer", + "DETREncoder", + "DETRDecoder", + "DeformableDETREncoder", + "DeformableDETRDecoder", + "HungarianMatcher", +] diff --git a/OpenTAD/opentad/models/transformer/decoder/deformable_decoder.py b/OpenTAD/opentad/models/transformer/decoder/deformable_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..8c78b78d8c74c97c9415b9dd02750f9f39783036 --- /dev/null +++ b/OpenTAD/opentad/models/transformer/decoder/deformable_decoder.py @@ -0,0 +1,128 @@ +import copy +import torch +import torch.nn as nn +from ...builder import TRANSFORMERS +from ..layers import BaseTransformerLayer, MultiheadAttention, MultiScaleDeformableAttention, FFN, inverse_sigmoid + + +@TRANSFORMERS.register_module() +class DeformableDETRDecoder(nn.Module): + def __init__( + self, + embed_dim=256, + num_heads=8, + num_points=4, + attn_dropout=0.1, + ffn_dim=2048, + ffn_dropout=0.1, + num_layers=6, + num_feature_levels=4, + batch_first=True, + return_intermediate=True, + ): + super().__init__() + + self.embed_dim = embed_dim + self.num_heads = num_heads + self.attn_dropout = attn_dropout + self.ffn_dim = ffn_dim + self.ffn_dropout = ffn_dropout + self.num_layers = num_layers + self.num_points = num_points + self.num_feature_levels = num_feature_levels + self.batch_first = batch_first + self.return_intermediate = return_intermediate + + self._init_transformer_layers() + self.bbox_embed = None + self.class_embed = None + + def _init_transformer_layers(self): + transformer_layers = BaseTransformerLayer( + attn=[ + MultiheadAttention( + embed_dim=self.embed_dim, + num_heads=self.num_heads, + attn_drop=self.attn_dropout, + batch_first=self.batch_first, + ), + MultiScaleDeformableAttention( + embed_dim=self.embed_dim, + num_heads=self.num_heads, + dropout=self.attn_dropout, + batch_first=self.batch_first, + num_points=self.num_points, + num_levels=self.num_feature_levels, + ), + ], + ffn=FFN( + embed_dim=self.embed_dim, + ffn_dim=self.ffn_dim, + ffn_drop=self.ffn_dropout, + ), + norm=nn.LayerNorm( + normalized_shape=self.embed_dim, + ), + operation_order=("self_attn", "norm", "cross_attn", "norm", "ffn", "norm"), + ) + self.layers = nn.ModuleList([copy.deepcopy(transformer_layers) for _ in range(self.num_layers)]) + + def forward( + self, + query, + key, + value, + query_pos=None, + key_pos=None, + attn_masks=None, + query_key_padding_mask=None, + key_padding_mask=None, + reference_points=None, + spatial_shapes=None, # nlvl + level_start_index=None, # nlvl + valid_ratios=None, # [bs, nlvl] + **kwargs, + ): + output = query + + intermediate = [] + intermediate_reference_points = [] + for layer_idx, layer in enumerate(self.layers): + reference_points_input = reference_points[:, :, None, :] * valid_ratios[:, None, :, None] + # [B,T,lvl,2/1] + + output = layer( + output, + key, + value, + query_pos=query_pos, + key_pos=key_pos, + attn_masks=attn_masks, + query_key_padding_mask=query_key_padding_mask, + key_padding_mask=key_padding_mask, + reference_points=reference_points_input, + spatial_shapes=spatial_shapes, # nlvl + level_start_index=level_start_index, # nlvl + **kwargs, + ) + + if self.bbox_embed is not None: + tmp = self.bbox_embed[layer_idx](output) + if reference_points.shape[-1] == 2: + new_reference_points = tmp + inverse_sigmoid(reference_points) + new_reference_points = new_reference_points.sigmoid() + else: + assert reference_points.shape[-1] == 1 + new_reference_points = tmp + new_reference_points[..., 0] = tmp[..., 0] + inverse_sigmoid(reference_points).squeeze(-1) + new_reference_points = new_reference_points.sigmoid() + reference_points = new_reference_points.detach() + + if self.return_intermediate: + intermediate.append(output) + intermediate_reference_points.append(reference_points) + + if self.return_intermediate: + return torch.stack(intermediate), torch.stack(intermediate_reference_points) + + return output, reference_points diff --git a/OpenTAD/opentad/models/transformer/decoder/detr_decoder.py b/OpenTAD/opentad/models/transformer/decoder/detr_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..4cd2c9fd2e78f8978ab6e18c9518fd88c88785f9 --- /dev/null +++ b/OpenTAD/opentad/models/transformer/decoder/detr_decoder.py @@ -0,0 +1,111 @@ +import copy +import torch +import torch.nn as nn +from ...builder import TRANSFORMERS +from ..layers import BaseTransformerLayer, MultiheadAttention, FFN + + +@TRANSFORMERS.register_module() +class DETRDecoder(nn.Module): + def __init__( + self, + embed_dim=256, + num_heads=8, + attn_dropout=0.1, + ffn_dim=2048, + ffn_dropout=0.1, + num_layers=6, + post_norm=True, + batch_first=True, + return_intermediate=True, + ): + super().__init__() + + self.embed_dim = embed_dim + self.num_heads = num_heads + self.attn_dropout = attn_dropout + self.ffn_dim = ffn_dim + self.ffn_dropout = ffn_dropout + self.num_layers = num_layers + self.batch_first = batch_first + self.return_intermediate = return_intermediate + + self._init_transformer_layers() + + if post_norm: + self.post_norm_layer = nn.LayerNorm(self.embed_dim) + else: + self.post_norm_layer = None + + def _init_transformer_layers(self): + transformer_layers = BaseTransformerLayer( + attn=MultiheadAttention( + embed_dim=self.embed_dim, + num_heads=self.num_heads, + attn_drop=self.attn_dropout, + batch_first=self.batch_first, + ), + ffn=FFN( + embed_dim=self.embed_dim, + ffn_dim=self.ffn_dim, + ffn_drop=self.ffn_dropout, + ), + norm=nn.LayerNorm( + normalized_shape=self.embed_dim, + ), + operation_order=("self_attn", "norm", "cross_attn", "norm", "ffn", "norm"), + ) + self.layers = nn.ModuleList([copy.deepcopy(transformer_layers) for _ in range(self.num_layers)]) + + def forward( + self, + query, + key, + value, + query_pos=None, + key_pos=None, + attn_masks=None, + query_key_padding_mask=None, + key_padding_mask=None, + **kwargs, + ): + if not self.return_intermediate: + for layer in self.layers: + query = layer( + query, + key, + value, + query_pos=query_pos, + key_pos=key_pos, + attn_masks=attn_masks, + query_key_padding_mask=query_key_padding_mask, + key_padding_mask=key_padding_mask, + **kwargs, + ) + + if self.post_norm_layer is not None: + query = self.post_norm_layer(query)[None] + return query + + # return intermediate + intermediate = [] + for layer in self.layers: + query = layer( + query, + key, + value, + query_pos=query_pos, + key_pos=key_pos, + attn_masks=attn_masks, + query_key_padding_mask=query_key_padding_mask, + key_padding_mask=key_padding_mask, + **kwargs, + ) + + if self.return_intermediate: + if self.post_norm_layer is not None: + intermediate.append(self.post_norm_layer(query)) + else: + intermediate.append(query) + + return torch.stack(intermediate) diff --git a/OpenTAD/opentad/models/transformer/deformable_detr_transformer.py b/OpenTAD/opentad/models/transformer/deformable_detr_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..eace8db0c4be925656cc9fcc79d588b3bdd773d5 --- /dev/null +++ b/OpenTAD/opentad/models/transformer/deformable_detr_transformer.py @@ -0,0 +1,255 @@ +import math +import copy +import torch +import torch.nn as nn +from .layers import MultiScaleDeformableAttention, MLP, inverse_sigmoid, get_sine_pos_embed +from ..builder import TRANSFORMERS, build_transformer, build_loss +from ..utils.bbox_tools import proposal_se_to_cw + + +@TRANSFORMERS.register_module() +class DeformableDETRTransformer(nn.Module): + def __init__( + self, + two_stage_num_proposals, + num_classes, + position_embedding=None, + encoder=None, + decoder=None, + aux_loss=True, + loss=None, + with_box_refine=False, + as_two_stage=False, + ): + super().__init__() + + self.position_embedding = build_transformer(position_embedding) + self.encoder = build_transformer(encoder) + self.decoder = build_transformer(decoder) + self.level_embeds = nn.Parameter(torch.Tensor(self.encoder.num_feature_levels, self.encoder.embed_dim)) + + self.as_two_stage = as_two_stage + self.with_box_refine = with_box_refine + self.two_stage_num_proposals = two_stage_num_proposals + self.num_classes = num_classes + + if self.as_two_stage: + self.enc_output = nn.Linear(self.encoder.embed_dim, self.encoder.embed_dim) + self.enc_output_norm = nn.LayerNorm(self.encoder.embed_dim) + self.pos_trans = nn.Linear(self.encoder.embed_dim, self.encoder.embed_dim * 2) + self.pos_trans_norm = nn.LayerNorm(self.encoder.embed_dim * 2) + else: + self.reference_points = nn.Linear(self.encoder.embed_dim, 1) + self.query_embedding = nn.Embedding(two_stage_num_proposals, self.encoder.embed_dim * 2) + + self.init_weights() + + # define classification head and box head + self.class_embed = nn.Linear(self.decoder.embed_dim, num_classes) + self.bbox_embed = MLP(self.decoder.embed_dim, self.decoder.embed_dim, 2, num_layers=3) + + # init parameters for heads + prior_prob = 0.01 + bias_value = -math.log((1 - prior_prob) / prior_prob) + self.class_embed.bias.data = torch.ones(num_classes) * bias_value + nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0) + nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0) + + # If two-stage, the last class_embed and bbox_embed is for region proposal generation + # Decoder layers share the same heads without box refinement, while use the different + # heads when box refinement is used. + num_pred = self.decoder.num_layers + 1 if as_two_stage else self.decoder.num_layers + if self.with_box_refine: + self.class_embed = nn.ModuleList([copy.deepcopy(self.class_embed) for _ in range(num_pred)]) + self.bbox_embed = nn.ModuleList([copy.deepcopy(self.bbox_embed) for _ in range(num_pred)]) + nn.init.constant_(self.bbox_embed[0].layers[-1].bias.data[1], -2.0) + self.decoder.bbox_embed = self.bbox_embed + else: + nn.init.constant_(self.bbox_embed.layers[-1].bias.data[1], -2.0) + self.class_embed = nn.ModuleList([self.class_embed for _ in range(num_pred)]) + self.bbox_embed = nn.ModuleList([self.bbox_embed for _ in range(num_pred)]) + self.decoder.bbox_embed = None + + # hack implementation for two-stage. The last class_embed and bbox_embed is for region proposal generation + if self.as_two_stage: + self.decoder.class_embed = self.class_embed + for box_embed in self.bbox_embed: + nn.init.constant_(box_embed.layers[-1].bias.data[1], 0.0) + + # loss function + self.criterion = build_loss(loss) + self.aux_loss = aux_loss + + def init_weights(self): + for p in self.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + for m in self.modules(): + if isinstance(m, MultiScaleDeformableAttention): + m.init_weights() + if not self.as_two_stage: + nn.init.xavier_normal_(self.reference_points.weight.data, gain=1.0) + nn.init.constant_(self.reference_points.bias.data, 0.0) + nn.init.normal_(self.level_embeds) + + def get_valid_ratio(self, mask): + """Get the valid ratios of feature maps of all levels.""" + _, T = mask.shape + valid_T = torch.sum(~mask, 1) + valid_ratio = valid_T.float() / T + return valid_ratio # [0~1] + + @staticmethod + def get_reference_points(lengths, valid_ratios, device): + """Get the reference points used in decoder. + + Args: + lengths (Tensor): The shape of all feature maps, has shape (num_level). + device (obj:`device`): The device where reference_points should be. + + Returns: + Tensor: reference points used in decoder, has shape (bs, num_keys, num_levels). + """ + reference_points_list = [] + for lvl, T in enumerate(lengths): + ref = torch.linspace(0.5, T - 0.5, T, dtype=torch.float32, device=device) + ref = ref[None, ...] / (valid_ratios[:, None, lvl] * T) + reference_points_list.append(ref) + reference_points = torch.cat(reference_points_list, 1) # [B,T] + reference_points = reference_points[:, :, None] * valid_ratios[:, None] # [B,T,num_level] + return reference_points + + def gen_encoder_output_proposals(self, memory, memory_padding_mask, lengths, base_width=0.05): + proposals = [] + _cur = 0 + for lvl, T in enumerate(lengths): + valid_T = torch.sum(~memory_padding_mask[:, _cur : (_cur + T)], 1) # [B] + grid = torch.linspace(0.5, T - 0.5, T, dtype=torch.float32, device=memory.device) + grid = grid.view(1, T).repeat(memory.shape[0], 1) / valid_T.unsqueeze(-1) # [B,N_] + width = torch.ones_like(grid) * base_width * (2.0**lvl) + proposal = torch.stack((grid, width), -1) # [B,N_,2] + proposals.append(proposal) + _cur += T + + output_proposals = torch.cat(proposals, 1) # [B,N,2] + 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 = self.enc_output_norm(self.enc_output(output_memory)) + return output_memory, output_proposals + + def forward_train(self, feat_list, mask_list, gt_segments=None, gt_labels=None, is_training=True, **kwargs): + # x: [bs, c, t] + # masks: [bs, t], padding is 1. + + # generate positional embeddings for each level + pos_embed = [] + for i, mask in enumerate(mask_list): + pos_embed.append(self.position_embedding(mask) + self.level_embeds[i].view(1, 1, -1)) + + feat_flatten = torch.cat(feat_list, dim=-1).permute(0, 2, 1) # [bs, c, t] -> [bs, t, c] + mask_flatten = torch.cat(mask_list, dim=1) # [bs, t] + pos_embed_flatten = torch.cat(pos_embed, dim=1) # [bs, t, c] + lengths = torch.as_tensor([feat.shape[-1] for feat in feat_list], dtype=torch.long, device=feat_flatten.device) + level_start_index = torch.cat((lengths.new_zeros((1,)), lengths.cumsum(0)[:-1])) + + valid_ratios = torch.stack([self.get_valid_ratio(m) for m in mask_list], 1) + reference_points = self.get_reference_points(lengths, valid_ratios, device=feat_flatten.device) + + memory = self.encoder( + query=feat_flatten, + key=None, + value=None, + query_pos=pos_embed_flatten, + query_key_padding_mask=mask_flatten, + spatial_shapes=lengths, + reference_points=reference_points, + level_start_index=level_start_index, + valid_ratios=valid_ratios, + **kwargs, + ) + + bs, _, c = memory.shape + if self.as_two_stage: + output_memory, output_proposals = self.gen_encoder_output_proposals(memory, mask_flatten, lengths) + enc_outputs_class = self.class_embed[-1](output_memory) + enc_outputs_coord = (self.bbox_embed[-1](output_memory) + output_proposals).sigmoid() + topk_proposals = torch.topk(enc_outputs_class[..., 0], self.two_stage_num_proposals, dim=1)[1] + + reference_points = torch.gather(enc_outputs_coord, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 2)).detach() + pos_trans_out = self.pos_trans_norm(self.pos_trans(get_sine_pos_embed(reference_points))) + query_pos, query = torch.split(pos_trans_out, c, dim=2) + else: + query_pos, query = torch.split(self.query_embedding.weight, c, dim=1) + query_pos = query_pos.unsqueeze(0).expand(bs, -1, -1) + query = query.unsqueeze(0).expand(bs, -1, -1) + reference_points = self.reference_points(query_pos).sigmoid() + + # decoder + inter_states, inter_references_out = self.decoder( + query=query, # bs, num_queries, embed_dims + key=memory, # bs, num_tokens, embed_dims + value=memory, # bs, num_tokens, embed_dims + query_pos=query_pos, + key_padding_mask=mask_flatten, # bs, num_tokens + reference_points=reference_points, # num_queries, 2 + spatial_shapes=lengths, # nlvl + level_start_index=level_start_index, # nlvl + valid_ratios=valid_ratios, + **kwargs, + ) + + # Calculate output coordinates and classes. + outputs_classes = [] + outputs_coords = [] + for lvl in range(inter_states.shape[0]): + reference = reference_points if lvl == 0 else inter_references_out[lvl - 1] + reference = inverse_sigmoid(reference) + outputs_class = self.class_embed[lvl](inter_states[lvl]) + tmp = self.bbox_embed[lvl](inter_states[lvl]) + if reference.shape[-1] == 2: + tmp += reference + else: + assert reference.shape[-1] == 1 + tmp[..., 0] += reference.squeeze(-1) + outputs_coord = tmp.sigmoid() + outputs_classes.append(outputs_class) + outputs_coords.append(outputs_coord) + outputs_class = torch.stack(outputs_classes) # tensor shape: [num_decoder_layers, bs, num_query, num_class] + outputs_coord = torch.stack(outputs_coords) # tensor shape: [num_decoder_layers, bs, num_query, 2] + + output = {"pred_logits": outputs_class[-1], "pred_boxes": outputs_coord[-1]} + + if self.as_two_stage: + output["enc_outputs"] = {"pred_logits": enc_outputs_class, "pred_boxes": enc_outputs_coord} + + if is_training: + if self.aux_loss: + output["aux_outputs"] = [ + {"pred_logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1]) + ] + return self.losses(output, mask_list[0], gt_segments, gt_labels) + else: + return output + + def forward_test(self, x, masks, **kwargs): + return self.forward_train(x, masks, is_training=False, **kwargs) + + def losses(self, outputs, masks, gt_segments, gt_labels): + gt_segments, gt_labels = self.prepare_targets(masks, gt_segments, gt_labels) + loss_dict = self.criterion(outputs, gt_segments, gt_labels) + return loss_dict + + @torch.no_grad() + def prepare_targets(self, masks, gt_segments, gt_labels): + gt_segments = [ + bboxes / (~mask).float().sum() for bboxes, mask in zip(gt_segments, masks) + ] # normalize gt_segments + gt_segments = [proposal_se_to_cw(bboxes) for bboxes in gt_segments] + gt_labels = [labels.long() for labels in gt_labels] + return gt_segments, gt_labels diff --git a/OpenTAD/opentad/models/transformer/detr_transformer.py b/OpenTAD/opentad/models/transformer/detr_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..9e90572db1ca9ebf6695275b17b6cce396496a22 --- /dev/null +++ b/OpenTAD/opentad/models/transformer/detr_transformer.py @@ -0,0 +1,83 @@ +import torch +import torch.nn as nn +from ..builder import TRANSFORMERS, build_transformer, build_loss +from ..utils.bbox_tools import proposal_se_to_cw + + +@TRANSFORMERS.register_module() +class DETRTransformer(nn.Module): + def __init__( + self, num_queries, position_embedding=None, encoder=None, decoder=None, head=None, aux_loss=True, loss=None + ): + super().__init__() + + self.position_embedding = build_transformer(position_embedding) + self.encoder = build_transformer(encoder) + self.decoder = build_transformer(decoder) + self.head = build_transformer(head) + + self.query_embed = nn.Embedding(num_queries, self.encoder.embed_dim) + + self.criterion = build_loss(loss) + self.aux_loss = aux_loss + + self.init_weights() + + def init_weights(self): + for p in self.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + + def forward_train(self, x, masks, gt_segments=None, gt_labels=None, is_training=True, **kwargs): + # x: [bs, c, t] + # masks: [bs, t], padding is 1. + x = x.permute(0, 2, 1) # [bs, c, t] -> [bs, t, c] + pos_embed = self.position_embedding(masks) # [bs, t, c] + + query_embed = self.query_embed.weight.unsqueeze(0).repeat(x.shape[0], 1, 1) + # query_embed [bs, num_query, dim] + memory = self.encoder( + query=x, + key=None, + value=None, + query_pos=pos_embed, + query_key_padding_mask=masks, # mask shape [bs, t] + ) # [bs, t, c] + target = torch.zeros_like(query_embed) + decoder_output = self.decoder( + query=target, + key=memory, + value=memory, + key_pos=pos_embed, + query_pos=query_embed, + key_padding_mask=masks, + ) # [num_layers, bs, num_query, c] + + outputs_class, outputs_coord = self.head(decoder_output) + output = {"pred_logits": outputs_class[-1], "pred_boxes": outputs_coord[-1]} + + if is_training: + if self.aux_loss: + output["aux_outputs"] = [ + {"pred_logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1]) + ] + return self.losses(output, masks, gt_segments, gt_labels) + else: + return output + + def forward_test(self, x, masks, **kwargs): + return self.forward_train(x, masks, is_training=False, **kwargs) + + def losses(self, outputs, masks, gt_segments, gt_labels): + gt_segments, gt_labels = self.prepare_targets(masks, gt_segments, gt_labels) + loss_dict = self.criterion(outputs, gt_segments, gt_labels) + return loss_dict + + @torch.no_grad() + def prepare_targets(self, masks, gt_segments, gt_labels): + gt_segments = [ + bboxes / (~mask).float().sum() for bboxes, mask in zip(gt_segments, masks) + ] # normalize gt_segments + gt_segments = [proposal_se_to_cw(bboxes) for bboxes in gt_segments] + gt_labels = [labels.long() for labels in gt_labels] + return gt_segments, gt_labels diff --git a/OpenTAD/opentad/models/transformer/encoder/deformable_encoder.py b/OpenTAD/opentad/models/transformer/encoder/deformable_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..fe397c24df61fe7f950747832a6f0930e6c09008 --- /dev/null +++ b/OpenTAD/opentad/models/transformer/encoder/deformable_encoder.py @@ -0,0 +1,89 @@ +import copy +import torch.nn as nn +from ...builder import TRANSFORMERS +from ..layers import BaseTransformerLayer, MultiScaleDeformableAttention, FFN + + +@TRANSFORMERS.register_module() +class DeformableDETREncoder(nn.Module): + def __init__( + self, + embed_dim=256, + num_heads=8, + attn_dropout=0.1, + ffn_dim=2048, + ffn_dropout=0.1, + num_layers=6, + num_points=4, + num_feature_levels=4, + post_norm=True, + batch_first=True, + ): + super().__init__() + + self.embed_dim = embed_dim + self.num_heads = num_heads + self.attn_dropout = attn_dropout + self.ffn_dim = ffn_dim + self.ffn_dropout = ffn_dropout + self.num_layers = num_layers + self.num_points = num_points + self.num_feature_levels = num_feature_levels + self.batch_first = batch_first + + self._init_transformer_layers() + + if post_norm: + self.post_norm_layer = nn.LayerNorm(self.embed_dim) + else: + self.post_norm_layer = None + + def _init_transformer_layers(self): + transformer_layers = BaseTransformerLayer( + attn=MultiScaleDeformableAttention( + embed_dim=self.embed_dim, + num_heads=self.num_heads, + dropout=self.attn_dropout, + batch_first=self.batch_first, + num_points=self.num_points, + num_levels=self.num_feature_levels, + ), + ffn=FFN( + embed_dim=self.embed_dim, + ffn_dim=self.ffn_dim, + ffn_drop=self.ffn_dropout, + ), + norm=nn.LayerNorm( + normalized_shape=self.embed_dim, + ), + operation_order=("self_attn", "norm", "ffn", "norm"), + ) + self.layers = nn.ModuleList([copy.deepcopy(transformer_layers) for _ in range(self.num_layers)]) + + def forward( + self, + query, + key, + value, + query_pos=None, + key_pos=None, + attn_masks=None, + query_key_padding_mask=None, + key_padding_mask=None, + **kwargs, + ): + for layer in self.layers: + query = layer( + query, + key, + value, + query_pos=query_pos, + attn_masks=attn_masks, + query_key_padding_mask=query_key_padding_mask, + key_padding_mask=key_padding_mask, + **kwargs, + ) + + if self.post_norm_layer is not None: + query = self.post_norm_layer(query) + return query diff --git a/OpenTAD/opentad/models/transformer/encoder/detr_encoder.py b/OpenTAD/opentad/models/transformer/encoder/detr_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..c93020f36d503babf9a766aa206a576f93d9467f --- /dev/null +++ b/OpenTAD/opentad/models/transformer/encoder/detr_encoder.py @@ -0,0 +1,84 @@ +import copy +import torch.nn as nn +from ...builder import TRANSFORMERS +from ..layers import BaseTransformerLayer, MultiheadAttention, FFN + + +@TRANSFORMERS.register_module() +class DETREncoder(nn.Module): + def __init__( + self, + embed_dim=256, + num_heads=8, + attn_dropout=0.1, + ffn_dim=2048, + ffn_dropout=0.1, + num_layers=6, + post_norm=True, + batch_first=True, + ): + super().__init__() + + self.embed_dim = embed_dim + self.num_heads = num_heads + self.attn_dropout = attn_dropout + self.ffn_dim = ffn_dim + self.ffn_dropout = ffn_dropout + self.num_layers = num_layers + self.batch_first = batch_first + + self._init_transformer_layers() + + if post_norm: + self.post_norm_layer = nn.LayerNorm(self.embed_dim) + else: + self.post_norm_layer = None + + def _init_transformer_layers(self): + transformer_layers = BaseTransformerLayer( + attn=MultiheadAttention( + embed_dim=self.embed_dim, + num_heads=self.num_heads, + attn_drop=self.attn_dropout, + batch_first=self.batch_first, + ), + ffn=FFN( + embed_dim=self.embed_dim, + ffn_dim=self.ffn_dim, + ffn_drop=self.ffn_dropout, + ), + norm=nn.LayerNorm( + normalized_shape=self.embed_dim, + ), + operation_order=("self_attn", "norm", "ffn", "norm"), + ) + self.layers = nn.ModuleList([copy.deepcopy(transformer_layers) for _ in range(self.num_layers)]) + + def forward( + self, + query, + key, + value, + query_pos=None, + key_pos=None, + attn_masks=None, + query_key_padding_mask=None, + key_padding_mask=None, + **kwargs, + ): + for layer in self.layers: + query = layer( + query, + key, + value, + query_pos=query_pos, + key_pos=key_pos, + attn_masks=attn_masks, + query_key_padding_mask=query_key_padding_mask, + key_padding_mask=key_padding_mask, + **kwargs, + ) + + if self.post_norm_layer is not None: + query = self.post_norm_layer(query) + return query diff --git a/OpenTAD/opentad/models/transformer/layers/__init__.py b/OpenTAD/opentad/models/transformer/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..004b58e211cd371604fc844fc25e305be4e9f65e --- /dev/null +++ b/OpenTAD/opentad/models/transformer/layers/__init__.py @@ -0,0 +1,20 @@ +from .transformer_layer import BaseTransformerLayer +from .attention import MultiheadAttention +from .deformable import MultiScaleDeformableAttention +from .mlp import FFN, MLP +from .position_embedding import PositionEmbeddingSine, PositionEmbeddingLearned, get_sine_pos_embed +from .head import SharedHead +from .utils import inverse_sigmoid + +__all__ = [ + "BaseTransformerLayer", + "MultiheadAttention", + "MultiScaleDeformableAttention", + "FFN", + "MLP", + "PositionEmbeddingSine", + "PositionEmbeddingLearned", + "get_sine_pos_embed", + "SharedHead", + "inverse_sigmoid", +] diff --git a/OpenTAD/opentad/models/transformer/layers/attention.py b/OpenTAD/opentad/models/transformer/layers/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..8fda35c308a5b4e0502896769b3b34d62fbd636a --- /dev/null +++ b/OpenTAD/opentad/models/transformer/layers/attention.py @@ -0,0 +1,111 @@ +import warnings +from typing import Optional +import torch +import torch.nn as nn + + +class MultiheadAttention(nn.Module): + """A wrapper for ``torch.nn.MultiheadAttention`` + Implement MultiheadAttention with identity connection, + and position embedding is also passed as input. + Args: + embed_dim (int): The embedding dimension for attention. + num_heads (int): The number of attention heads. + attn_drop (float): A Dropout layer on attn_output_weights. + Default: 0.0. + proj_drop (float): A Dropout layer after `MultiheadAttention`. + Default: 0.0. + 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, + num_heads: int, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + batch_first: bool = False, + **kwargs, + ): + super(MultiheadAttention, self).__init__() + self.embed_dim = embed_dim + self.num_heads = num_heads + self.batch_first = batch_first + + self.attn = nn.MultiheadAttention( + embed_dim=embed_dim, + num_heads=num_heads, + dropout=attn_drop, + batch_first=batch_first, + **kwargs, + ) + + self.proj_drop = nn.Dropout(proj_drop) + + def forward( + self, + query: torch.Tensor, + key: Optional[torch.Tensor] = None, + value: Optional[torch.Tensor] = None, + identity: Optional[torch.Tensor] = None, + query_pos: Optional[torch.Tensor] = None, + key_pos: Optional[torch.Tensor] = None, + attn_mask: Optional[torch.Tensor] = None, + key_padding_mask: Optional[torch.Tensor] = None, + **kwargs, + ) -> torch.Tensor: + """Forward function for `MultiheadAttention` + **kwargs allow passing a more general data flow when combining + with other operations in `transformerlayer`. + Args: + query (torch.Tensor): Query embeddings with shape + `(num_query, bs, embed_dim)` if self.batch_first is False, + else `(bs, num_query, embed_dim)` + key (torch.Tensor): Key embeddings with shape + `(num_key, bs, embed_dim)` if self.batch_first is False, + else `(bs, num_key, embed_dim)` + value (torch.Tensor): Value embeddings with the same shape as `key`. + Same in `torch.nn.MultiheadAttention.forward`. Default: None. + If None, the `key` will be used. + identity (torch.Tensor): The tensor, with the same shape as x, will + be used for identity addition. Default: None. + If None, `query` will be used. + query_pos (torch.Tensor): The position embedding for query, with the + same shape as `query`. Default: None. + key_pos (torch.Tensor): The position embedding for key. Default: None. + If None, and `query_pos` has the same shape as `key`, then `query_pos` + will be used for `key_pos`. + attn_mask (torch.Tensor): ByteTensor mask with shape `(num_query, num_key)`. + Same as `torch.nn.MultiheadAttention.forward`. Default: None. + key_padding_mask (torch.Tensor): ByteTensor with shape `(bs, num_key)` which + indicates which elements within `key` to be ignored in attention. + Default: None. + """ + if key is None: + key = query + if value is None: + value = key + if identity is None: + identity = query + if key_pos is None: + if query_pos is not None: + # use query_pos if key_pos is not available + if query_pos.shape == key.shape: + key_pos = query_pos + else: + warnings.warn(f"position encoding of key is" f"missing in {self.__class__.__name__}.") + if query_pos is not None: + query = query + query_pos + if key_pos is not None: + key = key + key_pos + + out = self.attn( + query=query, + key=key, + value=value, + attn_mask=attn_mask, + key_padding_mask=key_padding_mask, + )[0] + + return identity + self.proj_drop(out) diff --git a/OpenTAD/opentad/models/transformer/layers/deformable.py b/OpenTAD/opentad/models/transformer/layers/deformable.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb9e59926b8f0eb16d09e9de3766cdfee5d7c3b --- /dev/null +++ b/OpenTAD/opentad/models/transformer/layers/deformable.py @@ -0,0 +1,311 @@ +# coding=utf-8 +# Copyright 2022 The IDEA Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ------------------------------------------------------------------------------------------------ +# Deformable DETR +# Copyright (c) 2020 SenseTime. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------------------------------ +# Modified from: +# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/functions/ms_deform_attn_func.py +# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py +# https://github.com/open-mmlab/mmcv/blob/master/mmcv/ops/multi_scale_deform_attn.py +# ------------------------------------------------------------------------------------------------ + +import math +import warnings +from typing import Optional +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.nn.init import constant_, xavier_uniform_ + + +# helpers +def _is_power_of_2(n): + if (not isinstance(n, int)) or (n < 0): + raise ValueError("invalid input for _is_power_of_2: {} (type: {})".format(n, type(n))) + return (n & (n - 1) == 0) and n != 0 + + +class MultiScaleDeformableAttention(nn.Module): + """Multi-Scale Deformable Attention Module used in Deformable-DETR + + `Deformable DETR: Deformable Transformers for End-to-End Object Detection. + `_. + + Args: + embed_dim (int): The embedding dimension of Attention. Default: 256. + num_heads (int): The number of attention heads. Default: 8. + num_levels (int): The number of feature map used in Attention. Default: 4. + num_points (int): The number of sampling points for each query + in each head. Default: 4. + img2col_steps (int): The step used in image_to_column. Defualt: 64. + dropout (float): Dropout layer used in output. Default: 0.1. + batch_first (bool): if ``True``, then the input and output tensor will be + provided as `(bs, n, embed_dim)`. Default: False. `(n, bs, embed_dim)` + """ + + def __init__( + self, + embed_dim: int = 256, + num_heads: int = 8, + num_levels: int = 4, + num_points: int = 4, + # img2col_step: int = 64, + dropout: float = 0.1, + batch_first: bool = False, + ): + super().__init__() + + assert num_heads % 2 == 0, "num_heads must be divisible by 2" + + 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.dropout = nn.Dropout(dropout) + 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) + 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 init_weights(self): + """ + Default initialization for Parameters of Module. + """ + constant_(self.sampling_offsets.weight.data, 0.0) + + # DeformableDETR's implementation + # Initial offsets: + # (1, 0, -1, 0, -1, 0, 1, 0) + thetas = torch.arange(self.num_heads, dtype=torch.float32) * (4.0 * math.pi / self.num_heads) + grid_init = thetas.cos()[:, None] + + grid_init = grid_init.view(self.num_heads, 1, 1, 1).repeat(1, self.num_levels, self.num_points, 1) + for i in range(self.num_points): + grid_init[:, :, i, :] *= i + 1 + + # heads = 2, my implementation + # grid_init = torch.Tensor([-1.0, 1.0]) + # grid_init = grid_init.view(2, 1, 1).repeat(1, self.num_levels, self.num_points) + # for i in range(self.num_points): + # grid_init[:, :, i] *= (i + 1) * 0.5 + + # heads = any, my implementation + # grid_init = torch.arange(self.num_heads, dtype=torch.float32) + # grid_init = (grid_init // 2 + 1) * (-1) ** grid_init * 0.5 + # grid_init = grid_init.view(self.num_heads, 1, 1).repeat(1, self.num_levels, self.num_points) + # for i in range(self.num_points): + # grid_init[:, :, i] *= i + 1 + + # TadTR implementation + # Initial offsets: (1, 0, -1, 0, -1, 0, 1, 0) + # thetas = torch.arange(self.num_heads, dtype=torch.float32) * (4.0 * math.pi / self.num_heads) + # grid_init = thetas.cos()[:, None] + + # grid_init = grid_init.view(self.num_heads, 1, 1, 1).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 forward( + self, + query: torch.Tensor, + key: Optional[torch.Tensor] = None, + value: Optional[torch.Tensor] = None, + identity: 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 + `(bs, num_query, embed_dim)` + key (torch.Tensor): Key embeddings with shape + `(bs, num_key, embed_dim)` + value (torch.Tensor): Value embeddings with shape + `(bs, num_key, embed_dim)` + identity (torch.Tensor): The tensor used for addition, with the + same shape as `query`. Default: None. If None, `query` will be + used. + 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, 1)`, + all elements is range in [0, 1], top-left (0, 0), + bottom-right (1, 1), including padding are. + or `(N, Length_{query}, num_levels, 2)`, add additional + dimensions `(width)` to form reference boxes. + spatial_shapes (torch.Tensor): Spatial shape of features in different levels. + With shape `(num_levels)`, each element represents length. + level_start_index (torch.Tensor): The start index of each level. A tensor with + shape `(num_levels, )`. + + Returns: + torch.Tensor: forward results with shape `(num_query, bs, embed_dim)` + """ + + if value is None: + value = query + + if identity is None: + identity = query + if query_pos is not None: + query = query + query_pos + + if not self.batch_first: + # change to (bs, num_query ,embed_dims) + query = query.permute(1, 0, 2) + value = value.permute(1, 0, 2) + + bs, num_query, _ = query.shape + bs, num_value, _ = value.shape + + assert spatial_shapes.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, + ) + 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).view( + bs, + num_query, + self.num_heads, + self.num_levels, + self.num_points, + ) + + # bs, num_query, num_heads, num_levels, num_points, 2 + + # reference points + if reference_points.dim() == 4 and reference_points.shape[-1] == 1: + reference_points = reference_points.squeeze(-1) + + if reference_points.dim() == 3: # encoder, [bs, num_query, num_levels] + offset_normalizer = spatial_shapes + sampling_locations = ( + reference_points[:, :, None, :, None] + sampling_offsets / offset_normalizer[None, None, None, :, None] + ) + elif reference_points.dim() == 4: # decoder, [bs, num_query, num_levels, 2] + sampling_locations = ( + reference_points[:, :, None, :, None, 0] + + sampling_offsets / self.num_points * reference_points[:, :, None, :, None, 1] * 0.5 + ) + else: + raise ValueError( + "Last dim of reference_points must be 2 or 4, but get {} instead.".format(reference_points.shape[-1]) + ) + + # the original impl for fp32 training + if False: # torch.cuda.is_available() and value.is_cuda: + output = MultiScaleDeformableAttnFunction.apply( + value.to(torch.float32) if value.dtype == torch.float16 else value, + spatial_shapes, + level_start_index, + sampling_locations, + attention_weights, + self.im2col_step, + ) + else: + output = multi_scale_deformable_attn_pytorch(value, spatial_shapes, sampling_locations, attention_weights) + + if value.dtype == torch.float16: + output = output.to(torch.float16) + + output = self.output_proj(output) + + if not self.batch_first: + output = output.permute(1, 0, 2) + + return self.dropout(output) + identity + + +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(value_spatial_shapes.tolist(), dim=1) + sampling_grids = 2 * sampling_locations - 1 + sampling_value_list = [] + for level, T_ in enumerate(value_spatial_shapes): + # bs, T_, num_heads, embed_dims -> bs*num_heads, embed_dims, T_ + value_l_ = value_list[level].flatten(2).transpose(1, 2).reshape(bs * num_heads, embed_dims, T_) + # bs, num_queries, num_heads, num_points -> bs*num_heads, num_queries, num_points + sampling_grid_l_ = sampling_grids[:, :, :, level].transpose(1, 2).flatten(0, 1) + sampling_grid_l_ = torch.stack([-torch.ones_like(sampling_grid_l_), sampling_grid_l_], dim=-1) + # bs*num_heads, embed_dims, num_queries, num_points + sampling_value_l_ = F.grid_sample( + value_l_.unsqueeze(-1), + 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, 1, num_queries, num_levels*num_points) + attention_weights = attention_weights.transpose(1, 2) + attention_weights = attention_weights.reshape(bs * num_heads, 1, num_queries, num_levels * num_points) + output = torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights + output = output.sum(-1).view(bs, num_heads * embed_dims, num_queries) + return output.transpose(1, 2).contiguous() diff --git a/OpenTAD/opentad/models/transformer/layers/head.py b/OpenTAD/opentad/models/transformer/layers/head.py new file mode 100644 index 0000000000000000000000000000000000000000..a126eedef0f0cb33c2125c4d04da2e254cdbee25 --- /dev/null +++ b/OpenTAD/opentad/models/transformer/layers/head.py @@ -0,0 +1,22 @@ +import math +import torch +import torch.nn as nn +from .mlp import MLP +from ...builder import TRANSFORMERS + + +@TRANSFORMERS.register_module() +class SharedHead(nn.Module): + def __init__(self, embed_dim, num_classes, num_layers=3): + super().__init__() + + # define classification head and box head + self.class_embed = nn.Linear( + embed_dim, num_classes + ) # here we do not use +1, since we are using sigmoid focal loss + self.bbox_embed = MLP(input_dim=embed_dim, hidden_dim=embed_dim, output_dim=2, num_layers=num_layers) + + def forward(self, hidden_states): + outputs_class = self.class_embed(hidden_states) + outputs_coord = self.bbox_embed(hidden_states).sigmoid() + return outputs_class, outputs_coord diff --git a/OpenTAD/opentad/models/transformer/layers/mlp.py b/OpenTAD/opentad/models/transformer/layers/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..dd74e03bf2abccb989e9025ec355ba6a6909e81a --- /dev/null +++ b/OpenTAD/opentad/models/transformer/layers/mlp.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# Copyright 2022 The IDEA Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class MLP(nn.Module): + """The implementation of simple multi-layer perceptron layer + without dropout and identity connection. + The feature process order follows `Linear -> ReLU -> Linear -> ReLU -> ...`. + Args: + input_dim (int): The input feature dimension. + hidden_dim (int): The hidden dimension of MLPs. + output_dim (int): the output feature dimension of MLPs. + num_layer (int): The number of FC layer used in MLPs. + """ + + def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int) -> torch.Tensor: + 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): + """Forward function of `MLP`. + Args: + x (torch.Tensor): the input tensor used in `MLP` layers. + Returns: + torch.Tensor: the forward results of `MLP` layer + """ + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + return x + + +class FFN(nn.Module): + """The implementation of feed-forward networks (FFNs) + with identity connection. + Args: + embed_dim (int): The feature dimension. Same as + `MultiheadAttention`. Defaults: 256. + ffn_dim (int): The hidden dimension of FFNs. + Defaults: 1024. + output_dim (int): The output feature dimension of FFNs. + Default: None. If None, the `embed_dim` will be used. + num_fcs (int, optional): The number of fully-connected layers in + FFNs. Default: 2. + activation (nn.Module): The activation layer used in FFNs. + Default: nn.ReLU(inplace=True). + ffn_drop (float, optional): Probability of an element to be + zeroed in FFN. Default 0.0. + add_identity (bool, optional): Whether to add the + identity connection. Default: `True`. + """ + + def __init__( + self, + embed_dim=256, + ffn_dim=1024, + output_dim=None, + num_fcs=2, + activation=nn.ReLU(inplace=True), + ffn_drop=0.0, + fc_bias=True, + add_identity=True, + ): + super(FFN, self).__init__() + assert num_fcs >= 2, "num_fcs should be no less " f"than 2. got {num_fcs}." + self.embed_dim = embed_dim + self.ffn_dim = ffn_dim + self.num_fcs = num_fcs + self.activation = activation + + output_dim = embed_dim if output_dim is None else output_dim + + layers = [] + in_channels = embed_dim + for _ in range(num_fcs - 1): + layers.append( + nn.Sequential( + nn.Linear(in_channels, ffn_dim, bias=fc_bias), + self.activation, + nn.Dropout(ffn_drop), + ) + ) + in_channels = ffn_dim + layers.append(nn.Linear(ffn_dim, output_dim, bias=fc_bias)) + layers.append(nn.Dropout(ffn_drop)) + self.layers = nn.Sequential(*layers) + self.add_identity = add_identity + + def forward(self, x, identity=None) -> torch.Tensor: + """Forward function of `FFN`. + Args: + x (torch.Tensor): the input tensor used in `FFN` layers. + identity (torch.Tensor): the tensor with the same shape as `x`, + which will be used for identity addition. Default: None. + if None, `x` will be used. + Returns: + torch.Tensor: the forward results of `FFN` layer + """ + out = self.layers(x) + if not self.add_identity: + return out + if identity is None: + identity = x + return identity + out diff --git a/OpenTAD/opentad/models/transformer/layers/position_embedding.py b/OpenTAD/opentad/models/transformer/layers/position_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..ac8d8f34076f88dbba62a76e2e52801ed8236a7d --- /dev/null +++ b/OpenTAD/opentad/models/transformer/layers/position_embedding.py @@ -0,0 +1,176 @@ +# coding=utf-8 +# Copyright 2022 The IDEA Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ------------------------------------------------------------------------------------------------ +# Various positional encodings for the transformer. +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +# Copyright (c) OpenMMLab. All rights reserved. +# ------------------------------------------------------------------------------------------------ +# Modified from: +# https://github.com/facebookresearch/detr/blob/main/models/position_encoding.py +# https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/utils/positional_encoding.py +# ------------------------------------------------------------------------------------------------ + +import math +import torch +import torch.nn as nn +from ...builder import TRANSFORMERS + + +@TRANSFORMERS.register_module() +class PositionEmbeddingSine(nn.Module): + """Sinusoidal position embedding used in DETR model. + + Please see `End-to-End Object Detection with Transformers + `_ for more details. + + Args: + num_pos_feats (int): The feature dimension for each position along + x-axis or y-axis. The final returned dimension for each position + is 2 times of the input value. + temperature (int, optional): The temperature used for scaling + the position embedding. Default: 10000. + scale (float, optional): A scale factor that scales the position + embedding. The scale will be used only when `normalize` is True. + Default: 2*pi. + eps (float, optional): A value added to the denominator for numerical + stability. Default: 1e-6. + offset (float): An offset added to embed when doing normalization. + normalize (bool, optional): Whether to normalize the position embedding. + Default: False. + """ + + def __init__( + self, + num_pos_feats: int = 64, + temperature: int = 10000, + scale: float = 2 * math.pi, + eps: float = 1e-6, + offset: float = 0.0, + normalize: bool = False, + ): + super().__init__() + if normalize: + assert isinstance(scale, (float, int)), ( + "when normalize is set," "scale should be provided and in float or int type, " f"found {type(scale)}" + ) + self.num_pos_feats = num_pos_feats + self.temperature = temperature + self.normalize = normalize + self.scale = scale + self.eps = eps + self.offset = offset + + def forward(self, mask: torch.Tensor, **kwargs) -> torch.Tensor: + """Forward function for `PositionEmbeddingSine`. + + Args: + mask (torch.Tensor): ByteTensor mask. Non-zero values representing + ignored positions, while zero values means valid positions + for the input tensor. Shape as `(bs, t)`. + + Returns: + torch.Tensor: Returned position embedding with + shape `(bs, num_pos_feats * 2, t)` + """ + assert mask is not None + not_mask = ~mask + embed = not_mask.cumsum(1, dtype=torch.float32) + if self.normalize: + embed = (embed + self.offset) / (embed[:, -1:] + self.eps) * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=mask.device) + dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / self.num_pos_feats) + + pos = embed[:, :, None] / dim_t + pos = torch.stack((pos[:, :, 0::2].sin(), pos[:, :, 1::2].cos()), dim=3).flatten(2) + return pos # [bs,t,c] + + def __repr__(self): + rep_str = self.__class__.__name__ + "(" + rep_str += f"num_pos_feats={str(self.num_pos_feats)}, " + rep_str += f"temperature={str(self.temperature)}, " + rep_str += f"normalize={str(self.normalize)}, " + rep_str += f"offset={str(self.offset)})" + return rep_str + + +@TRANSFORMERS.register_module() +class PositionEmbeddingLearned(nn.Module): + """ + Position embedding with learnable embedding weights. + + Args: + num_pos_feats (int): The feature dimension for each position along + x-axis or y-axis. The final returned dimension for each position + is 2 times of the input value. + row_num_embed (int, optional): The dictionary size of row embeddings. + Default: 50. + col_num_embed (int, optional): The dictionary size of column embeddings. + Default: 50. + """ + + def __init__(self, num_pos_feats: int = 256, num_embed: int = 100): + super().__init__() + self.num_embed = num_embed + self.num_pos_feats = num_pos_feats + self.embed = nn.Embedding(num_embed, num_pos_feats) + + self.reset_parameters() + + def reset_parameters(self): + nn.init.uniform_(self.embed.weight) + + def forward(self, mask): + """Forward function for `PositionEmbeddingLearned`. + + Args: + mask (torch.Tensor): ByteTensor mask. Non-zero values representing + ignored positions, while zero values means valid positions + for the input tensor. Shape as `(bs, t)`. + + Returns: + torch.Tensor: Returned position embedding with + shape `(bs, num_pos_feats * 2, t)` + """ + bs, t = mask.shape + emb = self.embed(torch.arange(t, device=mask.device)) + pos = emb.unsqueeze(0).repeat(bs, 1, 1) + return pos + + +def get_sine_pos_embed(pos_tensor: torch.Tensor, num_pos_feats: int = 128, temperature: int = 10000): + """generate sine position embedding from a position tensor + + Args: + pos_tensor (torch.Tensor): Shape as `(None, n)`. + num_pos_feats (int): projected shape for each float in the tensor. Default: 128 + temperature (int): The temperature used for scaling + the position embedding. Default: 10000. + Returns: + torch.Tensor: Returned position embedding # noqa + with shape `(None, 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)] + pos_res = torch.cat(pos_res, dim=2) + return pos_res diff --git a/OpenTAD/opentad/models/transformer/layers/transformer_layer.py b/OpenTAD/opentad/models/transformer/layers/transformer_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..be488694beafd7d177b94477323e5e9319295d50 --- /dev/null +++ b/OpenTAD/opentad/models/transformer/layers/transformer_layer.py @@ -0,0 +1,166 @@ +import copy +import warnings +from typing import List +import torch +import torch.nn as nn + + +class BaseTransformerLayer(nn.Module): + """The implementation of Base `TransformerLayer` used in Transformer. Modified + from `mmcv `_. + It can be built by directly passing the `Attentions`, `FFNs`, `Norms` + module, which support more flexible customization combined with + `LazyConfig` system. The `BaseTransformerLayer` also supports `prenorm` + when you specifying the `norm` as the first element of `operation_order`. + More details about the `prenorm`: `On Layer Normalization in the + Transformer Architecture `_ . + Args: + attn (list[nn.Module] | nn.Module): nn.Module or a list + contains the attention module used in TransformerLayer. + ffn (nn.Module): FFN module used in TransformerLayer. + norm (nn.Module): Normalization layer used in TransformerLayer. + operation_order (tuple[str]): The execution order of operation in + transformer. Such as ('self_attn', 'norm', 'ffn', 'norm'). + Support `prenorm` when you specifying the first element as `norm`. + Default = None. + """ + + def __init__( + self, + attn: List[nn.Module], + ffn: nn.Module, + norm: nn.Module, + operation_order: tuple = None, + ): + super(BaseTransformerLayer, self).__init__() + assert set(operation_order).issubset({"self_attn", "norm", "cross_attn", "ffn"}) + + # count attention nums + num_attn = operation_order.count("self_attn") + operation_order.count("cross_attn") + + if isinstance(attn, nn.Module): + attn = [copy.deepcopy(attn) for _ in range(num_attn)] + else: + assert len(attn) == num_attn, ( + f"The length of attn (nn.Module or List[nn.Module]) {num_attn}" + f"is not consistent with the number of attention in " + f"operation_order {operation_order}" + ) + + self.num_attn = num_attn + self.operation_order = operation_order + self.pre_norm = operation_order[0] == "norm" + self.attentions = nn.ModuleList() + index = 0 + for operation_name in operation_order: + if operation_name in ["self_attn", "cross_attn"]: + self.attentions.append(attn[index]) + index += 1 + + self.embed_dim = self.attentions[0].embed_dim + + # count ffn nums + self.ffns = nn.ModuleList() + num_ffns = operation_order.count("ffn") + for _ in range(num_ffns): + self.ffns.append(copy.deepcopy(ffn)) + + # count norm nums + self.norms = nn.ModuleList() + num_norms = operation_order.count("norm") + for _ in range(num_norms): + self.norms.append(copy.deepcopy(norm)) + + def forward( + self, + query: torch.Tensor, + key: torch.Tensor = None, + value: torch.Tensor = None, + query_pos: torch.Tensor = None, + key_pos: torch.Tensor = None, + attn_masks: List[torch.Tensor] = None, + query_key_padding_mask: torch.Tensor = None, + key_padding_mask: torch.Tensor = None, + **kwargs, + ): + """Forward function for `BaseTransformerLayer`. + **kwargs contains the specific arguments of attentions. + Args: + query (torch.Tensor): Query embeddings with shape + `(num_query, bs, embed_dim)` or `(bs, num_query, embed_dim)` + which should be specified follows the attention module used in + `BaseTransformerLayer`. + key (torch.Tensor): Key embeddings used in `Attention`. + value (torch.Tensor): Value embeddings with the same shape as `key`. + query_pos (torch.Tensor): The position embedding for `query`. + Default: None. + key_pos (torch.Tensor): The position embedding for `key`. + Default: None. + attn_masks (List[Tensor] | None): A list of 2D ByteTensor used + in calculation the corresponding attention. The length of + `attn_masks` should be equal to the number of `attention` in + `operation_order`. Default: None. + query_key_padding_mask (torch.Tensor): ByteTensor for `query`, with + shape `(bs, num_query)`. Only used in `self_attn` layer. + Defaults to None. + key_padding_mask (torch.Tensor): ByteTensor for `key`, with + shape `(bs, num_key)`. Default: None. + """ + norm_index = 0 + attn_index = 0 + ffn_index = 0 + identity = query + if attn_masks is None: + attn_masks = [None for _ in range(self.num_attn)] + elif isinstance(attn_masks, torch.Tensor): + attn_masks = [copy.deepcopy(attn_masks) for _ in range(self.num_attn)] + warnings.warn(f"Use same attn_mask in all attentions in " f"{self.__class__.__name__} ") + else: + assert len(attn_masks) == self.num_attn, ( + f"The length of " + f"attn_masks {len(attn_masks)} must be equal " + f"to the number of attention in " + f"operation_order {self.num_attn}" + ) + + for layer in self.operation_order: + if layer == "self_attn": + temp_key = temp_value = query + query = self.attentions[attn_index]( + query, + temp_key, + temp_value, + identity if self.pre_norm else None, + query_pos=query_pos, + key_pos=query_pos, + attn_mask=attn_masks[attn_index], + key_padding_mask=query_key_padding_mask, + **kwargs, + ) + attn_index += 1 + identity = query + + elif layer == "norm": + query = self.norms[norm_index](query) + norm_index += 1 + + elif layer == "cross_attn": + query = self.attentions[attn_index]( + query, + key, + value, + identity if self.pre_norm else None, + query_pos=query_pos, + key_pos=key_pos, + attn_mask=attn_masks[attn_index], + key_padding_mask=key_padding_mask, + **kwargs, + ) + attn_index += 1 + identity = query + + elif layer == "ffn": + query = self.ffns[ffn_index](query, identity if self.pre_norm else None) + ffn_index += 1 + + return query diff --git a/OpenTAD/opentad/models/transformer/layers/utils.py b/OpenTAD/opentad/models/transformer/layers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..94b9d1a6f90c01f49c4e1c902830c65ee7d8a86f --- /dev/null +++ b/OpenTAD/opentad/models/transformer/layers/utils.py @@ -0,0 +1,8 @@ +import torch + + +def inverse_sigmoid(x, eps=1e-5): + x = x.clamp(min=0, max=1) + x1 = x.clamp(min=eps) + x2 = (1 - x).clamp(min=eps) + return torch.log(x1 / x2) diff --git a/OpenTAD/opentad/models/transformer/matcher/hungarian_matcher.py b/OpenTAD/opentad/models/transformer/matcher/hungarian_matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..8b83b5ecaabfc2d80b0da0a0893be306d50b869a --- /dev/null +++ b/OpenTAD/opentad/models/transformer/matcher/hungarian_matcher.py @@ -0,0 +1,132 @@ +import torch +import torch.nn as nn +from scipy.optimize import linear_sum_assignment + +from ...utils.iou_tools import compute_giou_torch, compute_iou_torch +from ...utils.bbox_tools import proposal_cw_to_se +from ...builder import MATCHERS + + +@MATCHERS.register_module() +class HungarianMatcher(nn.Module): + """HungarianMatcher which computes an assignment between targets and predictions. + For efficiency reasons, the targets don't include the no_object. Because of this, in general, + there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, + while the others are un-matched (and thus treated as non-objects). + Args: + cost_class (float): The relative weight of the classification error + in the matching cost. Default: 1. + cost_bbox (float): The relative weight of the L1 error of the bounding box + coordinates in the matching cost. Default: 1. + cost_giou (float): This is the relative weight of the giou loss of + the bounding box in the matching cost. Default: 1. + cost_class_type (str): How the classification error is calculated. + Choose from ``["ce_cost", "focal_loss_cost"]``. Default: "focal_loss_cost". + alpha (float): Weighting factor in range (0, 1) to balance positive vs + negative examples in focal loss. Default: 0.25. + gamma (float): Exponent of modulating factor (1 - p_t) to balance easy vs + hard examples in focal loss. Default: 2. + """ + + def __init__( + self, + cost_class: float = 1, + cost_bbox: float = 1, + cost_giou: float = 1, + cost_class_type: str = "focal_loss_cost", # or "ce_cost" + alpha: float = 0.25, + gamma: float = 2.0, + iou_type: str = "giou", # or "iou" + use_multi_class: bool = True, + ): + super().__init__() + self.cost_class = cost_class + self.cost_bbox = cost_bbox + self.cost_giou = cost_giou + self.cost_class_type = cost_class_type + self.alpha = alpha + self.gamma = gamma + self.iou_type = iou_type + self.use_multi_class = use_multi_class + assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, "all costs cant be 0" + assert cost_class_type in { + "ce_cost", + "focal_loss_cost", + }, "only support ce loss or focal loss for computing class cost" + + @torch.no_grad() + def forward(self, outputs, gt_segments, gt_labels): + """Forward function for `HungarianMatcher` which performs the matching. + Args: + outputs (Dict[str, torch.Tensor]): This is a dict that contains at least these entries: + - ``"pred_logits"``: Tensor of shape (bs, num_queries, num_classes) with the classification logits. + - ``"pred_boxes"``: Tensor of shape (bs, num_queries, 4) with the predicted box coordinates. + targets (List[Dict[str, torch.Tensor]]): This is a list of targets (len(targets) = batch_size), + where each target is a dict containing: + - ``"labels"``: Tensor of shape (num_target_boxes, ) (where num_target_boxes is the number of ground-truth objects in the target) containing the class labels. # noqa + - ``"boxes"``: Tensor of shape (num_target_boxes, 4) containing the target box coordinates. + Returns: + list[torch.Tensor]: A list of size batch_size, containing tuples of `(index_i, index_j)` where: + - ``index_i`` is the indices of the selected predictions (in order) + - ``index_j`` is the indices of the corresponding selected targets (in order) + For each batch element, it holds: `len(index_i) = len(index_j) = min(num_queries, num_target_boxes)` + """ + bs, num_queries = outputs["pred_logits"].shape[:2] + + # We flatten to compute the cost matrices in a batch + if self.cost_class_type == "ce_cost": + out_prob = outputs["pred_logits"].flatten(0, 1).softmax(-1) # [batch_size * num_queries, num_classes] + elif self.cost_class_type == "focal_loss_cost": + out_prob = outputs["pred_logits"].flatten(0, 1).sigmoid() # [batch_size * num_queries, num_classes] + + out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 2] + + # Also concat the target labels and boxes + tgt_ids = torch.cat(gt_labels) # [num_gt, num_classes] + tgt_segment = torch.cat(gt_segments) # num_gt + + # Compute the classification cost. + if self.cost_class_type == "ce_cost": + # Compute the classification cost. Contrary to the loss, we don't use the NLL, + # but approximate it in 1 - prob[target class]. + # The 1 is a constant that doesn't change the matching, it can be omitted. + cost_class = -out_prob[:, tgt_ids] + elif self.cost_class_type == "focal_loss_cost": + alpha = self.alpha + gamma = self.gamma + neg_cost_class = (1 - alpha) * (out_prob**gamma) * (-(1 - out_prob + 1e-8).log()) + pos_cost_class = alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log()) + if self.use_multi_class: + cost_class = ( + pos_cost_class - neg_cost_class + ) @ tgt_ids.T.float() # [batch_size * num_queries, num_gts] + else: + cost_class = pos_cost_class[:, tgt_ids] - neg_cost_class[:, tgt_ids] + + # Compute the L1 cost between boxes + cost_bbox = torch.cdist(out_bbox, tgt_segment, p=1) + + # Compute the giou cost between boxes + if self.iou_type == "giou": + cost_giou = -compute_giou_torch(proposal_cw_to_se(tgt_segment), proposal_cw_to_se(out_bbox)) + elif self.iou_type == "iou": + cost_giou = -compute_iou_torch(proposal_cw_to_se(tgt_segment), proposal_cw_to_se(out_bbox)) + else: + raise NotImplementedError(f"iou_type {self.iou_type} not implemented") + + # Final cost matrix + C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou + C = C.view(bs, num_queries, -1).cpu() + + sizes = [v.shape[0] for v in gt_segments] + indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))] + return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices] + + def __repr__(self): + rep_str = self.__class__.__name__ + "(" + rep_str += f"cost_class={str(self.cost_class)}, " + rep_str += f"cost_bbox={str(self.cost_bbox)}, " + rep_str += f"cost_giou={str(self.cost_giou)}, " + rep_str += f"alpha={str(self.alpha)}, " + rep_str += f"gamma={str(self.gamma)})" + return rep_str diff --git a/OpenTAD/opentad/models/transformer/tadtr_transformer.py b/OpenTAD/opentad/models/transformer/tadtr_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..46d52be92c51d345e9a9f822ecd0173d6d8f00bc --- /dev/null +++ b/OpenTAD/opentad/models/transformer/tadtr_transformer.py @@ -0,0 +1,163 @@ +import torch +import torch.nn as nn +from .layers import MLP, inverse_sigmoid +from ..builder import TRANSFORMERS +from .deformable_detr_transformer import DeformableDETRTransformer +from ..utils.bbox_tools import proposal_se_to_cw +from ..roi_heads.roi_extractors.align1d.align import Align1DLayer + + +@TRANSFORMERS.register_module() +class TadTRTransformer(DeformableDETRTransformer): + def __init__( + self, + num_proposals, + num_classes, + position_embedding=None, + encoder=None, + decoder=None, + aux_loss=True, + loss=None, + with_act_reg=True, + roi_size=16, + roi_extend_ratio=0.25, + ): + super(TadTRTransformer, self).__init__( + two_stage_num_proposals=num_proposals, + num_classes=num_classes, + position_embedding=position_embedding, + encoder=encoder, + decoder=decoder, + aux_loss=aux_loss, + loss=loss, + with_box_refine=True, + as_two_stage=False, + ) + + self.with_act_reg = with_act_reg + if self.with_act_reg: # RoI alignment + hidden_dim = self.encoder.embed_dim + self.roi_extend_ratio = roi_extend_ratio + self.roi_extractor = Align1DLayer(roi_size) + self.actionness_pred = nn.Sequential( + nn.Linear(roi_size * hidden_dim, hidden_dim), + nn.ReLU(inplace=True), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(inplace=True), + nn.Linear(hidden_dim, 1), + nn.Sigmoid(), + ) + + @staticmethod + def _to_roi_align_format(rois, T, roi_extend_ratio=1): + """Convert RoIs to RoIAlign format. + Params: + RoIs: normalized segments coordinates, shape (batch_size, num_segments, 4) + T: length of the video feature sequence + """ + # transform to absolute axis + B, N = rois.shape[:2] + rois_center = rois[:, :, 0:1] + rois_size = rois[:, :, 1:2] * (roi_extend_ratio * 2 + 1) + rois_abs = torch.cat((rois_center - rois_size / 2, rois_center + rois_size / 2), dim=2) * T + # expand the RoIs + rois_abs = torch.clamp(rois_abs, min=0, max=T) # (N, T, 2) + # add batch index + batch_ind = torch.arange(0, B).view((B, 1, 1)).to(rois_abs.device) + batch_ind = batch_ind.repeat(1, N, 1) + rois_abs = torch.cat((batch_ind.float(), rois_abs), dim=2) + # NOTE: stop gradient here to stabilize training + return rois_abs.view((B * N, 3)).detach() + + def forward_train(self, x, masks, gt_segments=None, gt_labels=None, is_training=True, **kwargs): + # The input of TadTR's transformer is single scale feature + # x: [bs, c, t], masks: [bs, t], padding is 1. + + # Here we set masks to be all False + masks = torch.zeros_like(masks, dtype=torch.bool) + + feat = x.permute(0, 2, 1) # [bs, c, t] -> [bs, t, c] + pos_embed = self.position_embedding(masks) + self.level_embeds[0].view(1, 1, -1) # [bs, t, c] + + lengths = torch.as_tensor([feat.shape[1]], dtype=torch.long, device=feat.device) + level_start_index = lengths.new_zeros((1,)) + + valid_ratios = self.get_valid_ratio(masks)[:, None] # [bs, 1] + reference_points = self.get_reference_points(lengths, valid_ratios, device=feat.device) # [bs, t, 1] + + memory = self.encoder( + query=feat, + key=None, + value=None, + query_pos=pos_embed, + query_key_padding_mask=masks, + spatial_shapes=lengths, + reference_points=reference_points, + level_start_index=level_start_index, + valid_ratios=valid_ratios, + **kwargs, + ) + + bs, _, c = memory.shape + query_pos, query = torch.split(self.query_embedding.weight, c, dim=1) + query_pos = query_pos.unsqueeze(0).expand(bs, -1, -1) + query = query.unsqueeze(0).expand(bs, -1, -1) + reference_points = self.reference_points(query_pos).sigmoid() # override the reference points + + # decoder + inter_states, inter_references_out = self.decoder( + query=query, # bs, num_queries, embed_dims + key=memory, # bs, num_tokens, embed_dims + value=memory, # bs, num_tokens, embed_dims + query_pos=query_pos, + key_padding_mask=masks, # bs, num_tokens + reference_points=reference_points, # num_queries, 1 + spatial_shapes=lengths, # nlvl + level_start_index=level_start_index, # nlvl + valid_ratios=valid_ratios, + **kwargs, + ) + + # Calculate output coordinates and classes. + outputs_classes = [] + outputs_coords = [] + for lvl in range(inter_states.shape[0]): + reference = reference_points if lvl == 0 else inter_references_out[lvl - 1] + reference = inverse_sigmoid(reference) + outputs_class = self.class_embed[lvl](inter_states[lvl]) + tmp = self.bbox_embed[lvl](inter_states[lvl]) + if reference.shape[-1] == 2: + tmp += reference + else: + assert reference.shape[-1] == 1 + tmp[..., 0] += reference.squeeze(-1) + outputs_coord = tmp.sigmoid() + outputs_classes.append(outputs_class) + outputs_coords.append(outputs_coord) + outputs_class = torch.stack(outputs_classes) # tensor shape: [num_decoder_layers, bs, num_query, num_class] + outputs_coord = torch.stack(outputs_coords) # tensor shape: [num_decoder_layers, bs, num_query, 2] + + output = {"pred_logits": outputs_class[-1], "pred_boxes": outputs_coord[-1]} + + if self.with_act_reg: + # perform RoIAlign + B, N = outputs_coord[-1].shape[:2] + rois = self._to_roi_align_format(outputs_coord[-1], memory.shape[1], roi_extend_ratio=self.roi_extend_ratio) + roi_features = self.roi_extractor(memory.permute(0, 2, 1), rois).view((B, N, -1)) + pred_actionness = self.actionness_pred(roi_features) + output["pred_actionness"] = pred_actionness + + if is_training: + if self.aux_loss: + output["aux_outputs"] = [ + {"pred_logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1]) + ] + return self.losses(output, masks, gt_segments, gt_labels) + else: + return output + + @torch.no_grad() + def prepare_targets(self, masks, gt_segments, gt_labels): + gt_segments = [proposal_se_to_cw(bboxes / masks.shape[-1]) for bboxes in gt_segments] # normalize gt_segments + gt_labels = [labels.long() for labels in gt_labels] + return gt_segments, gt_labels diff --git a/OpenTAD/opentad/models/utils/__init__.py b/OpenTAD/opentad/models/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a47c21e17ea7b5f8ed53fe9478232c2340532a91 --- /dev/null +++ b/OpenTAD/opentad/models/utils/__init__.py @@ -0,0 +1 @@ +from .post_processing import * diff --git a/OpenTAD/opentad/models/utils/bbox_tools.py b/OpenTAD/opentad/models/utils/bbox_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..e7718997776536bb9f2d5af8ce53c38b72502f36 --- /dev/null +++ b/OpenTAD/opentad/models/utils/bbox_tools.py @@ -0,0 +1,58 @@ +import torch +import math + + +def compute_delta(bboxes_init, gt_segments, wc=2.0, wl=2.0): + assert bboxes_init.size(0) == gt_segments.size(0) + assert bboxes_init.size(-1) == gt_segments.size(-1) == 2 + + # wc, wl = (10.0, 5.0) + # wc, wl = (1.0, 1.0) + + init_c = (bboxes_init[..., 0] + bboxes_init[..., 1]) * 0.5 + init_w = bboxes_init[..., 1] - bboxes_init[..., 0] + + gt_c = (gt_segments[..., 0] + gt_segments[..., 1]) * 0.5 + gt_w = gt_segments[..., 1] - gt_segments[..., 0] + + dc = (gt_c - init_c) / init_w * wc + dw = torch.log(gt_w / init_w) * wl + + deltas = torch.stack([dc, dw], dim=-1) + return deltas + + +def delta_to_pred(bboxes_init, pred_delta, wc=2.0, wl=2.0): + assert pred_delta.shape[-2] == bboxes_init.shape[-2] + + # wc, wl = (10.0, 5.0) + # wc, wl = (1.0, 1.0) + + dc = pred_delta[..., 0] / wc + # Prevent sending too large values into torch.exp() + dw = torch.clamp(pred_delta[..., 1] / wl, max=math.log(1000.0 / 16)) + + init_c = (bboxes_init[..., 0] + bboxes_init[..., 1]) * 0.5 + init_w = bboxes_init[..., 1] - bboxes_init[..., 0] + + pred_c = dc * init_w + init_c + pred_w = torch.exp(dw) * init_w + + pred_bboxes = torch.stack([pred_c - 0.5 * pred_w, pred_c + 0.5 * pred_w], dim=-1) + + pred_bboxes = pred_bboxes.clamp(min=0) + return pred_bboxes + + +def proposal_cw_to_se(x): + c, w = x.unbind(-1) + s = c - 0.5 * w + e = c + 0.5 * w + return torch.stack([s, e], dim=-1) + + +def proposal_se_to_cw(x): + s, e = x.unbind(-1) + c = (s + e) * 0.5 + w = e - s + return torch.stack([c, w], dim=-1) diff --git a/OpenTAD/opentad/models/utils/iou_tools.py b/OpenTAD/opentad/models/utils/iou_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..e699e75d9d2456c08f7627d15370d112e6800dd1 --- /dev/null +++ b/OpenTAD/opentad/models/utils/iou_tools.py @@ -0,0 +1,150 @@ +import torch + + +def compute_iou_torch(gt_boxes, anchors): + """Compute IoU between gt_boxes and anchors. + gt_boxes: shape [N, 2] + anchors: shape [M, 2] + """ + + N = gt_boxes.shape[0] + M = anchors.shape[0] + + gt_areas = (gt_boxes[:, 1] - gt_boxes[:, 0]).view(1, N) + anchors_areas = (anchors[:, 1] - anchors[:, 0]).view(M, 1) + + boxes = anchors.view(M, 1, 2).repeat(1, N, 1) + query_boxes = gt_boxes.view(1, N, 2).repeat(M, 1, 1) + + inter_max = torch.min(boxes[..., 1], query_boxes[..., 1]) + inter_min = torch.max(boxes[..., 0], query_boxes[..., 0]) + inter = (inter_max - inter_min).clamp(min=0) + + scores = inter / (anchors_areas + gt_areas - inter).clamp(min=1e-6) # shape [M, N] + return scores.to(anchors.dtype) + + +def compute_ioa_torch(gt_boxes, anchors): + """Compute Intersection between gt_boxes and anchors. + gt_boxes: np.array shape [N, 2] + anchors: np.array shape [M, 2] + """ + + N = gt_boxes.shape[0] + M = anchors.shape[0] + + anchors_areas = (anchors[:, 1] - anchors[:, 0]).view(M, 1) + + boxes = anchors.view(M, 1, 2).repeat(1, N, 1) + query_boxes = gt_boxes.view(1, N, 2).repeat(M, 1, 1) + + inter_max = torch.min(boxes[..., 1], query_boxes[..., 1]) + inter_min = torch.max(boxes[..., 0], query_boxes[..., 0]) + inter = (inter_max - inter_min).clamp(min=0) + + scores = inter / anchors_areas.clamp(min=1e-6) # shape [M, N] + return scores.to(anchors.dtype) + + +def compute_batched_iou_torch(gt_boxes, anchors): + """Compute IoU between gt_boxes and anchors. + gt_boxes: shape [B, N, 2] + anchors: shape [B, N, 2] + gt_boxes has been aligned with anchors + """ + bs = gt_boxes.shape[0] + N = gt_boxes.shape[1] + + gt_areas = (gt_boxes[..., 1] - gt_boxes[..., 0]).view(bs, N) + anchors_areas = (anchors[..., 1] - anchors[..., 0]).view(bs, N) + + inter_max = torch.min(anchors[..., 1], gt_boxes[..., 1]) + inter_min = torch.max(anchors[..., 0], gt_boxes[..., 0]) + inter = (inter_max - inter_min).clamp(min=0) + + scores = inter / (anchors_areas + gt_areas - inter).clamp(min=1e-6) # [B,N] + return scores.to(anchors.dtype) + + +def compute_giou_torch(gt_boxes, anchors): + """Compute GIoU between gt_boxes and anchors. + gt_boxes: shape [N, 2] + anchors: shape [M, 2] + """ + + N = gt_boxes.shape[0] + M = anchors.shape[0] + + gt_areas = (gt_boxes[:, 1] - gt_boxes[:, 0]).view(1, N) + anchors_areas = (anchors[:, 1] - anchors[:, 0]).view(M, 1) + + boxes = anchors.view(M, 1, 2).repeat(1, N, 1) + query_boxes = gt_boxes.view(1, N, 2).repeat(M, 1, 1) + + inter_max = torch.min(boxes[..., 1], query_boxes[..., 1]) + inter_min = torch.max(boxes[..., 0], query_boxes[..., 0]) + inter = (inter_max - inter_min).clamp(min=0) + + union = anchors_areas + gt_areas - inter + + iou = inter / union.clamp(min=1e-6) # shape [M, N] + + x1_enclosing = torch.min(boxes[..., 0], query_boxes[..., 0]) + x2_enclosing = torch.max(boxes[..., 1], query_boxes[..., 1]) + area = (x2_enclosing - x1_enclosing).clamp(min=1e-7) + + # GIOU + giou = iou - (area - union) / (area + 1e-6) + return giou.to(anchors.dtype) # [M,N] + + +def compute_diou_torch(gt_boxes, anchors, eps=1e-7): + """ + Compute DIoU (Distance Intersection over Union) between pairs of 1D boxes. + + Encourages maximizing the overlap and minimizing the distance between the centers of the boxes. + + Tensor broadcasting and repeating are used to efficiently compute overlaps and distances + between all pairs of boxes. + + Args: + gt_boxes (torch.Tensor): Ground truth boxes, shape (N, 2) + anchors (torch.Tensor): Anchor boxes, shape (M, 2) + eps (float, optional): A small number to prevent division by zero. + Returns: + torch.Tensor: The DIoU between each pair of boxes, shape (M, N) + """ + + N = gt_boxes.shape[0] + M = anchors.shape[0] + + gt_areas = (gt_boxes[:, 1] - gt_boxes[:, 0]).view(1, N) + anchors_areas = (anchors[:, 1] - anchors[:, 0]).view(M, 1) + + boxes = anchors.view(M, 1, 2).repeat(1, N, 1) + query_boxes = gt_boxes.view(1, N, 2).repeat(M, 1, 1) + + # overlap + inter_max = torch.min(boxes[..., 1], query_boxes[..., 1]) + inter_min = torch.max(boxes[..., 0], query_boxes[..., 0]) + inter = (inter_max - inter_min).clamp(min=0) + + # union + union = anchors_areas + gt_areas - inter + + # IoU + iou = inter / union.clamp(min=eps) # shape [M, N] + + # enclose area + x1_enclosing = torch.min(boxes[..., 0], query_boxes[..., 0]) + x2_enclosing = torch.max(boxes[..., 1], query_boxes[..., 1]) + area = x2_enclosing - x1_enclosing + + # center distance + c1 = (boxes[..., 0] + boxes[..., 1]) / 2 + c2 = (query_boxes[..., 0] + query_boxes[..., 1]) / 2 + c_dist = (c2 - c1).abs() + + # DIoU + diou = iou - c_dist * c_dist / (area * area).clamp(min=eps) + return diou.to(anchors.dtype) # [M,N] diff --git a/OpenTAD/opentad/models/utils/misc.py b/OpenTAD/opentad/models/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..6dbd5446643b76d95e75c0c53207c5e1a37890d7 --- /dev/null +++ b/OpenTAD/opentad/models/utils/misc.py @@ -0,0 +1,25 @@ +import torch + + +def convert_gt_to_one_hot(gt_segments, gt_labels, num_classes): + """convert the gt from class index to one hot encoding. this is for multi class case.""" + + gt_segments_unique, gt_labels_onehot = [], [] + for gt_segment, gt_label in zip(gt_segments, gt_labels): + if len(gt_segment) > 0: + bbox_unique, inverse_indices = torch.unique(gt_segment, dim=0, return_inverse=True) + label_unique = [] + for i in range(bbox_unique.shape[0]): + label = torch.nn.functional.one_hot( + gt_label[inverse_indices == i].long(), + num_classes=num_classes, + ) + label_unique.append(label.sum(dim=0).to(gt_label.device)) + label_unique = torch.stack(label_unique) + else: + bbox_unique, label_unique = [], [] + gt_segments_unique.append(bbox_unique) # [K] + gt_labels_onehot.append(label_unique) # [K,num_classes] + # gt_segments is the unique gt_segments + # gt_labels is the one hot encoding for multi class + return gt_segments_unique, gt_labels_onehot diff --git a/OpenTAD/opentad/models/utils/post_processing/__init__.py b/OpenTAD/opentad/models/utils/post_processing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bd321ea15e56b1f2e7efac98d4c2f6cf5f56e257 --- /dev/null +++ b/OpenTAD/opentad/models/utils/post_processing/__init__.py @@ -0,0 +1,12 @@ +from .nms.nms import batched_nms +from .utils import boundary_choose, save_predictions, load_predictions, convert_to_seconds +from .classifier import build_classifier + +__all__ = [ + "boundary_choose", + "batched_nms", + "save_predictions", + "load_predictions", + "convert_to_seconds", + "build_classifier", +] diff --git a/OpenTAD/opentad/models/utils/post_processing/classifier.py b/OpenTAD/opentad/models/utils/post_processing/classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..147acf511f40997bb654c4692598fd9f97ba40ed --- /dev/null +++ b/OpenTAD/opentad/models/utils/post_processing/classifier.py @@ -0,0 +1,185 @@ +import json +import numpy as np +import torch +from mmengine.registry import Registry + +CLASSIFIERS = Registry("models") + + +def build_classifier(cfg): + """Build external classifier.""" + return CLASSIFIERS.build(cfg) + + +@CLASSIFIERS.register_module() +class CUHKANETClassifier: + def __init__(self, path, topk=1): + super().__init__() + with open(path, "r") as f: + cuhk_data = json.load(f) + self.cuhk_data_score = cuhk_data["results"] + self.cuhk_data_action = np.array(cuhk_data["class"]) + self.topk = topk + + def __call__(self, video_id, segments, scores): + assert len(segments) == len(scores) + # sort video classification + cuhk_score = np.array(self.cuhk_data_score[video_id]) + cuhk_classes = self.cuhk_data_action[np.argsort(-cuhk_score)] + cuhk_score = cuhk_score[np.argsort(-cuhk_score)] + + new_segments = [] + new_labels = [] + new_scores = [] + # for segment, score in zip(segments, scores): + for k in range(self.topk): + new_segments.append(segments) + new_labels.extend([cuhk_classes[k]] * len(segments)) + new_scores.append(scores * cuhk_score[k]) + + new_segments = torch.cat(new_segments) + new_scores = torch.cat(new_scores) + return new_segments, new_labels, new_scores + + +@CLASSIFIERS.register_module() +class UntrimmedNetTHUMOSClassifier: + def __init__(self, path, topk=1): + super().__init__() + + self.thumos_class = { + 7: "BaseballPitch", + 9: "BasketballDunk", + 12: "Billiards", + 21: "CleanAndJerk", + 22: "CliffDiving", + 23: "CricketBowling", + 24: "CricketShot", + 26: "Diving", + 31: "FrisbeeCatch", + 33: "GolfSwing", + 36: "HammerThrow", + 40: "HighJump", + 45: "JavelinThrow", + 51: "LongJump", + 68: "PoleVault", + 79: "Shotput", + 85: "SoccerPenalty", + 92: "TennisSwing", + 93: "ThrowDiscus", + 97: "VolleyballSpiking", + } + + self.cls_data = np.load(path) + self.thu_label_id = np.array(list(self.thumos_class.keys())) - 1 # get thumos class id + self.topk = topk + + def __call__(self, video_id, segments, scores): + assert len(segments) == len(scores) + + # sort video classification + video_cls = self.cls_data[int(video_id[-4:]) - 1][self.thu_label_id] # order by video list, output 20 + video_cls_rank = sorted((e, i) for i, e in enumerate(video_cls)) + unet_classes = [self.thu_label_id[video_cls_rank[-k - 1][1]] + 1 for k in range(self.topk)] + unet_scores = [video_cls_rank[-k - 1][0] for k in range(self.topk)] + + new_segments = [] + new_labels = [] + new_scores = [] + # for segment, score in zip(segments, scores): + for k in range(self.topk): + new_segments.append(segments) + new_labels.extend([self.thumos_class[int(unet_classes[k])]] * len(segments)) + new_scores.append(scores * unet_scores[k]) + + new_segments = torch.cat(new_segments) + new_scores = torch.cat(new_scores) + return new_segments, new_labels, new_scores + + +@CLASSIFIERS.register_module() +class TCANetHACSClassifier: + def __init__(self, path, topk=1): + super().__init__() + + with open(path, "r") as f: + cls_data = json.load(f) + self.cls_data_score = cls_data["results"] + self.cls_data_action = cls_data["class"] + self.topk = topk + + def __call__(self, video_id, segments, scores): + assert len(segments) == len(scores) + + # sort video classification + cls_score = np.array(self.cls_data_score[video_id][0]) + cls_score = np.exp(cls_score) / np.sum(np.exp(cls_score)) * 2.0 + cls_data_action = np.array(self.cls_data_action) + cls_classes = cls_data_action[np.argsort(-cls_score)] + cls_score = cls_score[np.argsort(-cls_score)] + + new_segments = [] + new_labels = [] + new_scores = [] + + for k in range(self.topk): + new_segments.append(segments) + new_labels.extend([cls_classes[k]] * len(segments)) + new_scores.append(scores * cls_score[k]) + + new_segments = torch.cat(new_segments) + new_scores = torch.cat(new_scores) + return new_segments, new_labels, new_scores + + +@CLASSIFIERS.register_module() +class StandardClassifier: + def __init__(self, path, topk=1, apply_softmax=False): + super().__init__() + + with open(path, "r") as f: + cls_data = json.load(f) + self.cls_data_score = cls_data["results"] + self.cls_data_label = np.array(cls_data["class"]) if "class" in cls_data else np.array(cls_data["classes"]) + self.apply_softmax = apply_softmax + self.topk = topk + + def __call__(self, video_id, segments, scores): + assert len(segments) == len(scores) + cls_score = np.array(self.cls_data_score[video_id]) + + if self.apply_softmax: # do softmax + cls_score = np.exp(cls_score) / np.sum(np.exp(cls_score)) + + # sort video classification scores + topk_cls_idx = np.argsort(cls_score)[::-1][: self.topk] + topk_cls_score = cls_score[topk_cls_idx] + topk_cls_label = self.cls_data_label[topk_cls_idx] + + new_segments = [] + new_labels = [] + new_scores = [] + + for k in range(self.topk): + new_segments.append(segments) + new_labels.extend([topk_cls_label[k]] * len(segments)) + new_scores.append(np.sqrt(scores * topk_cls_score[k])) # default is sqrt + + new_segments = torch.cat(new_segments) + new_scores = torch.cat(new_scores) + return new_segments, new_labels, new_scores + + +@CLASSIFIERS.register_module() +class PseudoClassifier: + def __init__(self, pseudo_label=""): + super().__init__() + + self.pseudo_label = pseudo_label + + def __call__(self, video_id, segments, scores): + assert len(segments) == len(scores) + + labels = [self.pseudo_label for _ in range(len(segments))] + + return segments, labels, scores diff --git a/OpenTAD/opentad/models/utils/post_processing/nms/nms.py b/OpenTAD/opentad/models/utils/post_processing/nms/nms.py new file mode 100644 index 0000000000000000000000000000000000000000..c506ff35a49a4fbd82ef887834e4a3ae55075940 --- /dev/null +++ b/OpenTAD/opentad/models/utils/post_processing/nms/nms.py @@ -0,0 +1,208 @@ +# Functions for 1D NMS, modified from: +# https://github.com/open-mmlab/mmcv/blob/master/mmcv/ops/nms.py +import torch + +import nms_1d_cpu + + +class NMSop(torch.autograd.Function): + @staticmethod + def forward(ctx, segs, scores, cls_idxs, iou_threshold, min_score, max_num): + # vanilla nms will not change the score, so we can filter segs first + is_filtering_by_score = min_score > 0 + if is_filtering_by_score: + valid_mask = scores > min_score + segs, scores = segs[valid_mask], scores[valid_mask] + cls_idxs = cls_idxs[valid_mask] + valid_inds = torch.nonzero(valid_mask, as_tuple=False).squeeze(dim=1) + + # nms op; return inds that is sorted by descending order + inds = nms_1d_cpu.nms( + segs.contiguous().cpu(), + scores.contiguous().cpu(), + iou_threshold=float(iou_threshold), + ) + # cap by max number + if max_num > 0: + inds = inds[: min(max_num, len(inds))] + # return the sorted segs / scores + sorted_segs = segs[inds] + sorted_scores = scores[inds] + sorted_cls_idxs = cls_idxs[inds] + return sorted_segs.clone(), sorted_scores.clone(), sorted_cls_idxs.clone() + + +class SoftNMSop(torch.autograd.Function): + @staticmethod + def forward(ctx, segs, scores, cls_idxs, iou_threshold, sigma, min_score, method, max_num, t1, t2): + # pre allocate memory for sorted results + dets = segs.new_empty((segs.size(0), 3), device="cpu") + # softnms op, return dets that stores the sorted segs / scores + inds = nms_1d_cpu.softnms( + segs.cpu(), + scores.cpu(), + dets.cpu(), + iou_threshold=float(iou_threshold), + sigma=float(sigma), + min_score=float(min_score), + method=int(method), + t1=float(t1), + t2=float(t2), + ) + # cap by max number + if max_num > 0: + n_segs = min(len(inds), max_num) + else: + n_segs = len(inds) + sorted_segs = dets[:n_segs, :2] + sorted_scores = dets[:n_segs, 2] + sorted_cls_idxs = cls_idxs[inds] + sorted_cls_idxs = sorted_cls_idxs[:n_segs] + return sorted_segs.clone(), sorted_scores.clone(), sorted_cls_idxs.clone() + + +def seg_voting(nms_segs, all_segs, all_scores, iou_threshold, score_offset=1.5): + """ + blur localization results by incorporating side segs. + this is known as bounding box voting in object detection literature. + slightly boost the performance around iou_threshold + """ + + # *_segs : N_i x 2, all_scores: N, + # apply offset + offset_scores = all_scores + score_offset + + # computer overlap between nms and all segs + # construct the distance matrix of # N_nms x # N_all + num_nms_segs, num_all_segs = nms_segs.shape[0], all_segs.shape[0] + ex_nms_segs = nms_segs[:, None].expand(num_nms_segs, num_all_segs, 2) + ex_all_segs = all_segs[None, :].expand(num_nms_segs, num_all_segs, 2) + + # compute intersection + left = torch.maximum(ex_nms_segs[:, :, 0], ex_all_segs[:, :, 0]) + right = torch.minimum(ex_nms_segs[:, :, 1], ex_all_segs[:, :, 1]) + inter = (right - left).clamp(min=0) + + # lens of all segments + nms_seg_lens = ex_nms_segs[:, :, 1] - ex_nms_segs[:, :, 0] + all_seg_lens = ex_all_segs[:, :, 1] - ex_all_segs[:, :, 0] + + # iou + iou = inter / (nms_seg_lens + all_seg_lens - inter) + + # get neighbors (# N_nms x # N_all) / weights + seg_weights = (iou >= iou_threshold).to(all_scores.dtype) * all_scores[None, :] + seg_weights /= torch.sum(seg_weights, dim=1, keepdim=True) + refined_segs = seg_weights @ all_segs + + return refined_segs + + +def batched_nms( + segs, + scores, + cls_idxs, + iou_threshold=0.0, # does not matter when use soft nms + min_score=0.0, + max_seg_num=100, + use_soft_nms=True, + multiclass=True, + sigma=0.5, + voting_thresh=0.0, # set 0 to disable + method=2, # 0: vanilla nms, 1: linear, 2: gaussian, 3: improved gaussian + t1=0, # only used in improved gaussian for better recall + t2=0, # only used in improved gaussian for better recall +): + # method 2 means we use gaussian soft-nms, so iou_threshold does not matter + + # make sure the inputs are float + segs = segs.float() + scores = scores.float() + + # Based on Detectron2 implementation, + num_segs = segs.shape[0] + # corner case, no prediction outputs + if num_segs == 0: + return ( + torch.zeros([0, 2]), + torch.zeros([0]), + torch.zeros([0], dtype=cls_idxs.dtype), + ) + + if multiclass: + # multiclass nms: apply nms on each class independently + new_segs, new_scores, new_cls_idxs = [], [], [] + for class_id in torch.unique(cls_idxs): + curr_indices = torch.where(cls_idxs == class_id)[0] + # soft_nms vs nms + if use_soft_nms: + sorted_segs, sorted_scores, sorted_cls_idxs = SoftNMSop.apply( + segs[curr_indices], + scores[curr_indices], + cls_idxs[curr_indices], + iou_threshold, + sigma, + min_score, + method, + max_seg_num, + t1, + t2, + ) + else: + sorted_segs, sorted_scores, sorted_cls_idxs = NMSop.apply( + segs[curr_indices], + scores[curr_indices], + cls_idxs[curr_indices], + iou_threshold, + min_score, + max_seg_num, + ) + # disable seg voting for multiclass nms, no sufficient segs + + # fill in the class index + new_segs.append(sorted_segs) + new_scores.append(sorted_scores) + new_cls_idxs.append(sorted_cls_idxs) + + # cat the results + new_segs = torch.cat(new_segs) + new_scores = torch.cat(new_scores) + new_cls_idxs = torch.cat(new_cls_idxs) + + else: + # class agnostic + if use_soft_nms: + new_segs, new_scores, new_cls_idxs = SoftNMSop.apply( + segs, + scores, + cls_idxs, + iou_threshold, + sigma, + min_score, + method, + max_seg_num, + t1, + t2, + ) + else: + new_segs, new_scores, new_cls_idxs = NMSop.apply( + segs, + scores, + cls_idxs, + iou_threshold, + min_score, + max_seg_num, + ) + # seg voting + if voting_thresh > 0: + new_segs = seg_voting(new_segs, segs, scores, voting_thresh) + + # sort based on scores and return + # truncate the results based on max_seg_num + _, idxs = new_scores.sort(descending=True) + max_seg_num = min(max_seg_num, new_segs.shape[0]) + # needed for multiclass NMS + new_segs = new_segs[idxs[:max_seg_num]] + new_scores = new_scores[idxs[:max_seg_num]] + new_cls_idxs = new_cls_idxs[idxs[:max_seg_num]] + return new_segs, new_scores, new_cls_idxs diff --git a/OpenTAD/opentad/models/utils/post_processing/nms/nms_cpu.cpp b/OpenTAD/opentad/models/utils/post_processing/nms/nms_cpu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e02703352aac560adb8a02c702f89a7055909b16 --- /dev/null +++ b/OpenTAD/opentad/models/utils/post_processing/nms/nms_cpu.cpp @@ -0,0 +1,185 @@ +#include +#include +#include +#include + +// 1D NMS (CPU) helper functions, ported from +// https://github.com/open-mmlab/mmcv/blob/master/mmcv/ops/csrc/pytorch/nms.cpp + +using namespace at; + +#define CHECK_CPU(x) \ + TORCH_CHECK(!x.device().is_cuda(), #x " must be a CPU tensor") +#define CHECK_CONTIGUOUS(x) \ + TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") +#define CHECK_CPU_INPUT(x) \ + CHECK_CPU(x); \ + CHECK_CONTIGUOUS(x) + +Tensor nms_1d_cpu(Tensor segs, Tensor scores, float iou_threshold) { + if (segs.numel() == 0) { + return at::empty({0}, segs.options().dtype(at::kLong)); + } + auto x1_t = segs.select(1, 0).contiguous(); + auto x2_t = segs.select(1, 1).contiguous(); + + Tensor areas_t = x2_t - x1_t + 1e-6; + + auto order_t = std::get<1>(scores.sort(0, /* descending=*/true)); + + auto nsegs = segs.size(0); + Tensor select_t = at::ones({nsegs}, segs.options().dtype(at::kBool)); + + auto select = select_t.data_ptr(); + auto order = order_t.data_ptr(); + auto x1 = x1_t.data_ptr(); + auto x2 = x2_t.data_ptr(); + auto areas = areas_t.data_ptr(); + + for (int64_t _i = 0; _i < nsegs; _i++) { + if (select[_i] == false) continue; + auto i = order[_i]; + auto ix1 = x1[i]; + auto ix2 = x2[i]; + auto iarea = areas[i]; + + for (int64_t _j = _i + 1; _j < nsegs; _j++) { + if (select[_j] == false) continue; + auto j = order[_j]; + auto xx1 = std::max(ix1, x1[j]); + auto xx2 = std::min(ix2, x2[j]); + + auto inter = std::max(0.f, xx2 - xx1); + auto ovr = inter / (iarea + areas[j] - inter); + if (ovr >= iou_threshold) select[_j] = false; + } + } + return order_t.masked_select(select_t); +} + +Tensor nms_1d(Tensor segs, Tensor scores, float iou_threshold) { + CHECK_CPU_INPUT(segs); + CHECK_CPU_INPUT(scores); + return nms_1d_cpu(segs, scores, iou_threshold); + +} + +Tensor softnms_1d_cpu(Tensor segs, Tensor scores, Tensor dets, float iou_threshold, + float sigma, float min_score, int method, float t1, float t2) { + if (segs.numel() == 0) { + return at::empty({0}, segs.options().dtype(at::kLong)); + } + + auto x1_t = segs.select(1, 0).contiguous(); + auto x2_t = segs.select(1, 1).contiguous(); + auto scores_t = scores.clone(); + + Tensor areas_t = x2_t - x1_t + 1e-6; + + auto nsegs = segs.size(0); + auto x1 = x1_t.data_ptr(); + auto x2 = x2_t.data_ptr(); + auto sc = scores_t.data_ptr(); + auto areas = areas_t.data_ptr(); + auto de = dets.data_ptr(); + + int64_t pos = 0; + Tensor inds_t = at::arange(nsegs, segs.options().dtype(at::kLong)); + auto inds = inds_t.data_ptr(); + + for (int64_t i = 0; i < nsegs; i++) { + auto max_score = sc[i]; + auto max_pos = i; + + // get seg with max score + pos = i + 1; + while (pos < nsegs) { + if (max_score < sc[pos]) { + max_score = sc[pos]; + max_pos = pos; + } + pos = pos + 1; + } + // swap the current seg (i) and the seg with max score (max_pos) + auto ix1 = de[i * 3 + 0] = x1[max_pos]; + auto ix2 = de[i * 3 + 1] = x2[max_pos]; + auto iscore = de[i * 3 + 2] = sc[max_pos]; + auto iarea = areas[max_pos]; + auto iind = inds[max_pos]; + + x1[max_pos] = x1[i]; + x2[max_pos] = x2[i]; + sc[max_pos] = sc[i]; + areas[max_pos] = areas[i]; + inds[max_pos] = inds[i]; + + x1[i] = ix1; + x2[i] = ix2; + sc[i] = iscore; + areas[i] = iarea; + inds[i] = iind; + + // reset pos + pos = i + 1; + while (pos < nsegs) { + auto xx1 = std::max(ix1, x1[pos]); + auto xx2 = std::min(ix2, x2[pos]); + + auto inter = std::max(0.f, xx2 - xx1); + auto ovr = inter / (iarea + areas[pos] - inter); + + float weight = 1.; + if (method == 0) { + // vanilla nms + if (ovr >= iou_threshold) weight = 0; + } else if (method == 1) { + // linear + if (ovr >= iou_threshold) weight = 1 - ovr; + } else if (method == 2) { + // gaussian + weight = std::exp(-(ovr * ovr) / sigma); + } else if (method == 3) { + // improved gaussian, proposed in BMN, helpful for recall + if (ovr >= (t1 + t2 * iarea)) weight = std::exp(-(ovr * ovr) / sigma); + } + sc[pos] *= weight; + + // if the score falls below threshold, discard the segment by + // swapping with last seg update N + if (sc[pos] < min_score) { + x1[pos] = x1[nsegs - 1]; + x2[pos] = x2[nsegs - 1]; + sc[pos] = sc[nsegs - 1]; + areas[pos] = areas[nsegs - 1]; + inds[pos] = inds[nsegs - 1]; + nsegs = nsegs - 1; + pos = pos - 1; + } + + pos = pos + 1; + } + } + return inds_t.slice(0, 0, nsegs); +} + +Tensor softnms_1d(Tensor segs, Tensor scores, Tensor dets, float iou_threshold, + float sigma, float min_score, int method, float t1, float t2) { + // softnms is not implemented on GPU + CHECK_CPU_INPUT(segs) + CHECK_CPU_INPUT(scores) + CHECK_CPU_INPUT(dets) + return softnms_1d_cpu(segs, scores, dets, iou_threshold, sigma, min_score, method, t1, t2); +} + +// bind to torch interface +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def( + "nms", &nms_1d, "nms (CPU) ", + py::arg("segs"), py::arg("scores"), py::arg("iou_threshold") + ); + m.def( + "softnms", &softnms_1d, "softnms (CPU) ", + py::arg("segs"), py::arg("scores"), py::arg("dets"), py::arg("iou_threshold"), + py::arg("sigma"), py::arg("min_score"), py::arg("method"), py::arg("t1"), py::arg("t2") + ); +} diff --git a/OpenTAD/opentad/models/utils/post_processing/nms/setup.py b/OpenTAD/opentad/models/utils/post_processing/nms/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..be8b9938a2574fcd9f9c2e19841140039522c3cd --- /dev/null +++ b/OpenTAD/opentad/models/utils/post_processing/nms/setup.py @@ -0,0 +1,10 @@ +from setuptools import setup +from torch.utils.cpp_extension import BuildExtension, CppExtension + + +setup( + name="nms_1d_cpu", + version="0.0.1", + ext_modules=[CppExtension(name="nms_1d_cpu", sources=["./nms_cpu.cpp"], extra_compile_args=["-fopenmp"])], + cmdclass={"build_ext": BuildExtension}, +) diff --git a/OpenTAD/opentad/models/utils/post_processing/utils.py b/OpenTAD/opentad/models/utils/post_processing/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..07978ff89630fe01dca4a5451b835e9e68249355 --- /dev/null +++ b/OpenTAD/opentad/models/utils/post_processing/utils.py @@ -0,0 +1,65 @@ +import os +import pickle +import torch +import torch.nn.functional as F + + +def boundary_choose(score): + mask_high = score > score.max(dim=1, keepdim=True)[0] * 0.5 + mask_peak = score == F.max_pool1d(score, kernel_size=3, stride=1, padding=1) + mask = mask_peak | mask_high + return mask + + +def save_predictions(predictions, metas, folder): + for idx in range(len(metas)): + video_name = metas[idx]["video_name"] + + file_path = os.path.join(folder, f"{video_name}.pkl") + prediction = [data[idx] for data in predictions] + with open(file_path, "wb") as outfile: + pickle.dump(prediction, outfile, pickle.HIGHEST_PROTOCOL) + + +def load_single_prediction(metas, folder): + """Should not be used for sliding window. Since we saved the files with video name, and sliding window will have multiple files with the same name.""" + predictions = [] + for idx in range(len(metas)): + video_name = metas[idx]["video_name"] + file_path = os.path.join(folder, f"{video_name}.pkl") + with open(file_path, "rb") as infile: + prediction = pickle.load(infile) + predictions.append(prediction) + + batched_predictions = [] + for i in range(len(predictions[0])): + data = torch.stack([prediction[i] for prediction in predictions]) + batched_predictions.append(data) + return batched_predictions + + +def load_predictions(metas, infer_cfg): + if "fuse_list" in infer_cfg.keys(): + predictions = [] + predictions_list = [load_single_prediction(metas, folder) for folder in infer_cfg.fuse_list] + for i in range(len(predictions_list[0])): + predictions.append(torch.stack([pred[i] for pred in predictions_list]).mean(dim=0)) + return predictions + else: + return load_single_prediction(metas, infer_cfg.folder) + + +def convert_to_seconds(segments, meta): + if meta["fps"] == -1: # resize setting, like in anet / hacs + segments = segments / meta["resize_length"] * meta["duration"] + else: # sliding window / padding setting, like in thumos / ego4d + snippet_stride = meta["snippet_stride"] + offset_frames = meta["offset_frames"] + window_start_frame = meta["window_start_frame"] if "window_start_frame" in meta.keys() else 0 + segments = (segments * snippet_stride + window_start_frame + offset_frames) / meta["fps"] + + # truncate all boundaries within [0, duration] + if segments.shape[0] > 0: + segments[segments <= 0.0] *= 0.0 + segments[segments >= meta["duration"]] = segments[segments >= meta["duration"]] * 0.0 + meta["duration"] + return segments diff --git a/OpenTAD/opentad/utils/__init__.py b/OpenTAD/opentad/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..65bac604522f260e3fef06874c440ba612c890ea --- /dev/null +++ b/OpenTAD/opentad/utils/__init__.py @@ -0,0 +1,16 @@ +from .misc import set_seed, update_workdir, create_folder, save_config, AverageMeter +from .logger import setup_logger +from .ema import ModelEma +from .checkpoint import save_checkpoint, save_best_checkpoint + +__all__ = [ + "set_seed", + "update_workdir", + "create_folder", + "save_config", + "setup_logger", + "AverageMeter", + "ModelEma", + "save_checkpoint", + "save_best_checkpoint", +] diff --git a/OpenTAD/opentad/utils/checkpoint.py b/OpenTAD/opentad/utils/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..2dd270ced33636477a9328c67e5413cf309c0b03 --- /dev/null +++ b/OpenTAD/opentad/utils/checkpoint.py @@ -0,0 +1,37 @@ +import os +import torch + + +def save_checkpoint(model, model_ema, optimizer, scheduler, epoch, work_dir=None): + save_dir = os.path.join(work_dir, "checkpoint") + + save_states = { + "epoch": epoch, + "state_dict": model.state_dict(), + "optimizer": optimizer.state_dict(), + "scheduler": scheduler.state_dict(), + } + + if model_ema != None: + save_states.update({"state_dict_ema": model_ema.module.state_dict()}) + + if not os.path.exists(save_dir): + os.mkdir(save_dir) + + checkpoint_path = os.path.join(save_dir, f"epoch_{epoch}.pth") + torch.save(save_states, checkpoint_path) + + +def save_best_checkpoint(model, model_ema, epoch, work_dir=None): + save_dir = os.path.join(work_dir, "checkpoint") + + save_states = {"epoch": epoch, "state_dict": model.state_dict()} + + if model_ema != None: + save_states.update({"state_dict_ema": model_ema.module.state_dict()}) + + if not os.path.exists(save_dir): + os.mkdir(save_dir) + + checkpoint_path = os.path.join(save_dir, f"best.pth") + torch.save(save_states, checkpoint_path) diff --git a/OpenTAD/opentad/utils/ema.py b/OpenTAD/opentad/utils/ema.py new file mode 100644 index 0000000000000000000000000000000000000000..83387143081ce0f3297c66c244c0ea4e95a0fbaf --- /dev/null +++ b/OpenTAD/opentad/utils/ema.py @@ -0,0 +1,27 @@ +import torch +from copy import deepcopy + + +class ModelEma(torch.nn.Module): + def __init__(self, model, decay=0.999, device=None): + super().__init__() + # make a copy of the model for accumulating moving average of weights + self.module = deepcopy(model) + self.module.eval() + self.decay = decay + self.device = device # perform ema on different device from model if set + if self.device is not None: + self.module.to(device=device) + + def _update(self, model, update_fn): + with torch.no_grad(): + for ema_v, model_v in zip(self.module.state_dict().values(), model.state_dict().values()): + if self.device is not None: + model_v = model_v.to(device=self.device) + ema_v.copy_(update_fn(ema_v, model_v)) + + def update(self, model): + self._update(model, update_fn=lambda e, m: self.decay * e + (1.0 - self.decay) * m) + + def set(self, model): + self._update(model, update_fn=lambda e, m: m) diff --git a/OpenTAD/opentad/utils/logger.py b/OpenTAD/opentad/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5a77d394f54abdc1bb6c51bdb51ae26cc2fcd7bd --- /dev/null +++ b/OpenTAD/opentad/utils/logger.py @@ -0,0 +1,24 @@ +import logging +import os +import sys + + +def setup_logger(name, save_dir, distributed_rank=0, filename="log.json"): + logger = logging.getLogger(name) + logger.setLevel(logging.DEBUG) + # don't log results for the non-master process + if distributed_rank > 0: + return logger + ch = logging.StreamHandler(stream=sys.stdout) + ch.setLevel(logging.DEBUG) + formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s: %(message)s", "%Y-%m-%d %H:%M:%S") + ch.setFormatter(formatter) + logger.addHandler(ch) + + if save_dir: + fh = logging.FileHandler(os.path.join(save_dir, filename)) + fh.setLevel(logging.DEBUG) + fh.setFormatter(formatter) + logger.addHandler(fh) + + return logger diff --git a/OpenTAD/opentad/utils/misc.py b/OpenTAD/opentad/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..41117b3980e43c6437d63dd80fe1eaaa3999bbeb --- /dev/null +++ b/OpenTAD/opentad/utils/misc.py @@ -0,0 +1,78 @@ +import os +import numpy as np +import random +import shutil +import torch +import torch.distributed as dist + + +def set_seed(seed, disable_deterministic=False): + """Set randon seed for pytorch and numpy""" + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + + if disable_deterministic: + torch.backends.cudnn.deterministic = False + torch.backends.cudnn.benchmark = True + else: + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" + torch.use_deterministic_algorithms(True, warn_only=True) + + +def update_workdir(cfg, exp_id, gpu_num): + cfg.work_dir = os.path.join(cfg.work_dir, f"gpu{gpu_num}_id{exp_id}/") + return cfg + + +def create_folder(folder_path): + dir_name = os.path.expanduser(folder_path) + if not os.path.exists(dir_name): + os.makedirs(dir_name, mode=0o777, exist_ok=True) + + +def save_config(cfg, folder_path): + shutil.copy2(cfg, folder_path) + + +def reduce_loss(loss_dict): + # reduce loss when distributed training, only for logging + for loss_name, loss_value in loss_dict.items(): + loss_value = loss_value.data.clone() + dist.all_reduce(loss_value.div_(dist.get_world_size())) + loss_dict[loss_name] = loss_value + return loss_dict + + +class AverageMeter(object): + """Computes and stores the average and current value. + Used to compute dataset stats from mini-batches + """ + + def __init__(self): + self.initialized = False + self.val = None + self.avg = None + self.sum = None + self.count = 0.0 + + def initialize(self, val, n): + self.val = val + self.avg = val + self.sum = val * n + self.count = n + self.initialized = True + + def update(self, val, n=1): + if not self.initialized: + self.initialize(val, n) + else: + self.add(val, n) + + def add(self, val, n): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count diff --git a/OpenTAD/requirements.txt b/OpenTAD/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..56c3407c1d77809492f3a48f81342a60c8458468 --- /dev/null +++ b/OpenTAD/requirements.txt @@ -0,0 +1,19 @@ +###### Requirements without Version Specifiers ###### +mmengine +wandb +scipy +einops +pandas +tqdm +ninja +imgaug +pytorchvideo + +###### Requirements with Version Specifiers ###### +numpy==1.23.5 +gdown==5.1.0 + +###### Custom Package Requirements ###### +opentad/models/utils/post_processing/nms +opentad/models/roi_heads/roi_extractors/align1d +opentad/models/roi_heads/roi_extractors/boundary_pooling \ No newline at end of file diff --git a/OpenTAD/run.sh b/OpenTAD/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..6bbb3d3b8f85271eb9b4131a65987d7ecafc1098 --- /dev/null +++ b/OpenTAD/run.sh @@ -0,0 +1,23 @@ +''' +# Training feature-based ActionFormer on 1 GPU. +torchrun \ + --nnodes=1 \ + --nproc_per_node=1 \ + --rdzv_backend=c10d \ + --rdzv_endpoint=localhost:0 \ + tools/train.py configs/actionformer/anet_tsp.py +''' + + +# 1. Change 'configs/_base_/datasets/activitynet-1.3/features_tsp_resize_trunc.py' Line 50 to 'subset_name="testing"' +# 2. Add --not_eval +# 3. ε°† configs/actionformer/anet_tsp.py ι‡Œ post_processing δΈ­ηš„ external_cls ιƒ¨εˆ†ζ³¨ι‡ŠζŽ‰ +torchrun \ + --nnodes=1 \ + --nproc_per_node=1 \ + --rdzv_backend=c10d \ + --rdzv_endpoint=localhost:0 \ + tools/test.py \ + configs/actionformer/anet_tsp.py \ + --checkpoint exps/anet/actionformer_tsp/gpu1_id0/checkpoint/best.pth \ + --not_eval \ No newline at end of file diff --git a/OpenTAD/tools/model_converters/publish_model.py b/OpenTAD/tools/model_converters/publish_model.py new file mode 100644 index 0000000000000000000000000000000000000000..0afece32e07a3bdc5366157ebe3f01359ace8bc8 --- /dev/null +++ b/OpenTAD/tools/model_converters/publish_model.py @@ -0,0 +1,42 @@ +import argparse +import subprocess + +import torch + + +def process_checkpoint(in_file, out_file): + checkpoint = torch.load(in_file, map_location="cpu") + + # only keep `epoch` and `state_dict`/`state_dict_ema`` for smaller file size + ckpt_keys = list(checkpoint.keys()) + save_keys = ["meta", "epoch"] + if "state_dict_ema" in ckpt_keys: + save_keys.append("state_dict_ema") + else: + save_keys.append("state_dict") + + for k in ckpt_keys: + if k not in save_keys: + print(f"Key `{k}` will be removed because it is not in save_keys.") + checkpoint.pop(k, None) + + # if it is necessary to remove some sensitive data in checkpoint['meta'], + # add the code here. + torch.save(checkpoint, out_file) + sha = subprocess.check_output(["sha256sum", out_file]).decode() + if out_file.endswith(".pth"): + out_file_name = out_file[:-4] + else: + out_file_name = out_file + final_file = out_file_name + f"_{sha[:8]}.pth" + subprocess.Popen(["mv", out_file, final_file]) + print(f"The published model is saved at {final_file}.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Process a checkpoint to be published") + parser.add_argument("in_file", help="input checkpoint filename") + parser.add_argument("out_file", help="output checkpoint filename") + args = parser.parse_args() + + process_checkpoint(args.in_file, args.out_file) diff --git a/OpenTAD/tools/prepare_data/activitynet/README.md b/OpenTAD/tools/prepare_data/activitynet/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f924097058d8b17590e8826b8e8f3139ff9cdc5d --- /dev/null +++ b/OpenTAD/tools/prepare_data/activitynet/README.md @@ -0,0 +1,48 @@ +# Data Preparation for ActivityNet-1.3 + +## Download Annotations + +You can download the annotation by +```bash +bash download_annotation.sh +``` +The annotation should be in `data/activitynet-1.3/annotations/`. + +- Since some videos in the validation set are no longer exiting in YouTube, therefore BMN/AFSD/RTD-Action/TALLFormer and other following works choose to ignore these videos during evaluation and report the performance. We follow this evaluation protocol in this codebase for fair comparison. The blocked videos are recorded in the `blocked.json`, and there are total 4,728 videos left in validation subset. Therefore, the performance of ActionFormer/VideoMambaSuite could be slightly higher than their paper reported. + +## Download Pre-extracted Features + +Please put the downloaded feature under the path: `data/activitynet-1.3/features/`. + + +We provide the following pre-extracted features for ActivityNet: + +| Feature | Url | Backbone | Feature Extraction Setting | +| :-------------: | :--------------------------------------------------------------------------------------------------------------------------------: | :-------------------: | :----------------------------------------------------------: | +| tsp_unresize | [Google Drive](https://drive.google.com/file/d/1INw4tKjSoPL6_9uiB_RCOQ-fyOrA3uOi/view?usp=sharing) | TSP (r2plus1d-34) | 15 fps, snippet_stride=16, clip_length=16, frame_interval=1 | +| tsn_unresize | [Google Drive](https://drive.google.com/file/d/137GfkCoH4Uro_i5kz0d35J1YOx8ftsm6/view?usp=sharing) | TSN (two stream) | | +| slowfast_r50 | [Google Drive](https://drive.google.com/file/d/1zwxW8R-EZceEWOQyPOMoJSI-Aaz8cR4r/view?usp=sharing) | SlowFast-R50-8x8x1 | snippet_stride=8, clip_length=32, frame_interval=1 | +| slowfast_r101 | [Google Drive](https://drive.google.com/file/d/1U--V_eGi_MYeRp0HdNQG0CJDpKWLyFzT/view?usp=sharing) | SlowFast-R101-8x8x1 | snippet_stride=8, clip_length=32, frame_interval=1 | +| videomae_b | [Google Drive](https://drive.google.com/file/d/1rsnZXUi4EVuDXYWJy9p11crPGt3Ex18W/view?usp=sharing) | VideoMAE-Base-16x4x1 | snippet_stride=8, clip_length=16, frame_interval=4 | +| videomae_l | [Google Drive](https://drive.google.com/file/d/1lwb7jy3nHNelmTfRAeztKVZoVzwj5BXx/view?usp=sharing) | VideoMAE-Large-16x4x1 | snippet_stride=8, clip_length=16, frame_interval=4 | +| internvideo2_6b | [Official Repo](https://github.com/OpenGVLab/video-mamba-suite/blob/main/video-mamba-suite/temporal-action-localization/README.md) | InternVideo2-6B | snippet_stride=8, clip_length=16, frame_interval=1 | + +## Download Raw Videos + +Please put the downloaded video under the path: `data/activitynet-1.3/raw_data/`. + +You can download the raw video from [official website](https://docs.google.com/forms/d/e/1FAIpQLSeKaFq9ZfcmZ7W0B0PbEhfbTHY41GeEgwsa7WobJgGUhn4DTQ/viewform), which provides 7-day access for downloading. + +**[Update]** We have recently added a processed version of the ActivityNet-v1.3 videos to the folders above, named `Anet_videos_15fps_short256.zip`. The video has been converted by ffmpeg to 15 fps, and the shorter side of the video is resized to 256 pixels. In this codebase, all end-to-end ActivityNet experiments are based on this data. + +## Citation + +```BibTeX +@article{Heilbron2015ActivityNetAL, + title={ActivityNet: A large-scale video benchmark for human activity understanding}, + author={Fabian Caba Heilbron and Victor Escorcia and Bernard Ghanem and Juan Carlos Niebles}, + journal={2015 IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, + year={2015}, + pages={961-970} +} +``` \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/activitynet/download_annotation.sh b/OpenTAD/tools/prepare_data/activitynet/download_annotation.sh new file mode 100644 index 0000000000000000000000000000000000000000..917b7b3a79c590a8a2ddc9cb1e60025a744492ac --- /dev/null +++ b/OpenTAD/tools/prepare_data/activitynet/download_annotation.sh @@ -0,0 +1,9 @@ +DATA_DIR="../../../data/" + +if [[ ! -d "${DATA_DIR}" ]]; then + echo "${DATA_DIR} does not exist. Creating" + mkdir -p ${DATA_DIR} +fi + +# download annotations for ActivityNet-1.3 +gdown https://drive.google.com/drive/folders/1HwLFaUdrTLkTcx0oKm_z9WPyQiD2moJU -O $DATA_DIR --folder diff --git a/OpenTAD/tools/prepare_data/charades/README.md b/OpenTAD/tools/prepare_data/charades/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dcc781751637bdb019ae296c9d10df6e1b60a51b --- /dev/null +++ b/OpenTAD/tools/prepare_data/charades/README.md @@ -0,0 +1,43 @@ +# Data Preparation for Charades + +## Download Annotations + +You can download the annotation by +```bash +bash download_annotation.sh +``` +The annotation should be in `data/charades/annotations/`. + + +## Download Pre-extracted Features + +Please put the downloaded feature under the path: `data/charades/features/`. + + +We provide the following pre-extracted features for Charades: + +| Feature | Url | Backbone | Feature Extraction Setting | +| :------: | :------------------------------------------------------------------------------------------------: | :------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| vgg-rgb | [Google Drive](https://drive.google.com/file/d/1aiRPzZHVIwGKnpxp_lMK6TOHFC93061X/view?usp=sharing) | VGG-16 | 24fps, snippet_stride=4, converted from [official website](https://prior.allenai.org/projects/charades) | +| vgg-flow | [Google Drive](https://drive.google.com/file/d/1n6KU5yYj_2btKJcr0e8bu7GrKUw2uNqE/view?usp=sharing) | VGG-16 | 24fps, snippet_stride=4, converted from [official website](https://prior.allenai.org/projects/charades) | +| i3d-rgb | [Google Drive](https://drive.google.com/file/d/1kmABW7c0wFRoYvxkYXO26iFtLU-VBf3l/view?usp=sharing) | I3D | 24fps, snippet_stride=8, converted from [here](https://github.com/Xun-Yang/Causal_Video_Moment_Retrieval/blob/main/DATASET.md) | + + +## Download Raw Videos + +Please put the downloaded video under the path: `data/charades/raw_data/`. + +You can download the raw video from [official website](https://prior.allenai.org/projects/charades). + +## Citation + +```BibTeX +@inproceedings{sigurdsson2016hollywood, + title={Hollywood in homes: Crowdsourcing data collection for activity understanding}, + author={Sigurdsson, Gunnar A and Varol, G{\"u}l and Wang, Xiaolong and Farhadi, Ali and Laptev, Ivan and Gupta, Abhinav}, + booktitle={Computer Vision--ECCV 2016: 14th European Conference, Amsterdam, The Netherlands, October 11--14, 2016, Proceedings, Part I 14}, + pages={510--526}, + year={2016}, + organization={Springer} +} +``` \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/charades/download_annotation.sh b/OpenTAD/tools/prepare_data/charades/download_annotation.sh new file mode 100644 index 0000000000000000000000000000000000000000..d444d0377a96151caa31b90a810255bb2093a3a2 --- /dev/null +++ b/OpenTAD/tools/prepare_data/charades/download_annotation.sh @@ -0,0 +1,9 @@ +DATA_DIR="../../../data/" + +if [[ ! -d "${DATA_DIR}" ]]; then + echo "${DATA_DIR} does not exist. Creating" + mkdir -p ${DATA_DIR} +fi + +# download annotations for THUMOS-14 +gdown --folder https://drive.google.com/drive/folders/1oON5K5hSa5jexnB4IGdsW6qDB3w1I_QG -O $DATA_DIR --folder \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/epic/README.md b/OpenTAD/tools/prepare_data/epic/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4b5b23a6c6ec99ab0a15b1ce1b8645105600b6c1 --- /dev/null +++ b/OpenTAD/tools/prepare_data/epic/README.md @@ -0,0 +1,45 @@ +# Data Preparation for EPIC-KITCHENS-100 + +## Download Annotations + +You can download the annotation by +```bash +bash download_annotation.sh +``` +The annotation should be in `data/epic_kitchens-100/annotations/`. + +- You can also download original csv annotations from [official website](https://github.com/epic-kitchens/epic-kitchens-100-annotations), and use `convert_epic_kitchens_anno.py` to generate the annotations that suitable for the codebase. + +## Download Pre-extracted Features + +Please put the downloaded feature under the path: `data/epic_kitchens-100/features/`. + + +We provide the following pre-extracted features for EPIC-KITCHENS-100: + +| Feature | Url | Backbone | Feature Extraction Setting | +| :--------: | :------------------------------------------------------------------------------------------------: | :--------------------------------: | :--------------------------------------------------------: | +| slowfast | [Google Drive](https://drive.google.com/file/d/12cDSUkJJ-id2LqKYm5fxTNDg9NOnhAAZ/view?usp=sharing) | SlowFast (Epic Finetuned) | 30fps, snippet_stride=16, clip_length=32, frame_interval=1 | +| videomae-l | Coming soon | VideoMAE-L-16x4x1 (Epic Finetuned) | 30fps, snippet_stride=16, clip_length=16, frame_interval=1 | + +## Download Raw Videos + +Please put the downloaded video under the path: `data/epic_kitchens-100/raw_data/`. + +You can download the raw video from [official website](https://github.com/epic-kitchens/epic-kitchens-download-scripts). + +## Citation + +```BibTeX +@ARTICLE{Damen2022RESCALING, + title={Rescaling Egocentric Vision: Collection, Pipeline and Challenges for EPIC-KITCHENS-100}, + author={Damen, Dima and Doughty, Hazel and Farinella, Giovanni Maria and Furnari, Antonino + and Ma, Jian and Kazakos, Evangelos and Moltisanti, Davide and Munro, Jonathan + and Perrett, Toby and Price, Will and Wray, Michael}, + journal = {International Journal of Computer Vision (IJCV)}, + year = {2022}, + volume = {130}, + pages = {33–55}, + Url = {https://doi.org/10.1007/s11263-021-01531-2} +} +``` \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/epic/convert_epic_kitchens_anno.py b/OpenTAD/tools/prepare_data/epic/convert_epic_kitchens_anno.py new file mode 100644 index 0000000000000000000000000000000000000000..7c63876b271fb6cdba1896ac83f03c3a1f784e14 --- /dev/null +++ b/OpenTAD/tools/prepare_data/epic/convert_epic_kitchens_anno.py @@ -0,0 +1,121 @@ +import argparse +import os +import pandas as pd +import json +import tqdm + + +def parse_annotation(args): + if os.path.exists(args.save_path) is False: + os.makedirs(args.save_path) + + train_path = os.path.join(args.csv_dir, "EPIC_100_train.csv") + val_path = os.path.join(args.csv_dir, "EPIC_100_validation.csv") + test_path = os.path.join(args.csv_dir, "EPIC_100_test_timestamps.csv") + duration_path = os.path.join(args.csv_dir, "EPIC_100_video_info.csv") + + train_anno = pd.read_csv(train_path) + val_anno = pd.read_csv(val_path) + test_anno = pd.read_csv(test_path) + duration_anno = pd.read_csv(duration_path) + + def _parse_subset(anno, video_info, subset, save_path): + print(f"Processing {subset} subset...") + database = {} + all_video_id = anno["video_id"].unique() + + for video_id in tqdm.tqdm(all_video_id): + video_duration = video_info[video_info["video_id"] == video_id]["duration"].values[0] + filter_anno = anno[anno["video_id"] == video_id] + + if subset == "test": + database[video_id] = dict( + subset=subset, + duration=video_duration, + ) + else: + annotations = [] + for _, row in filter_anno.iterrows(): + # convert timestamp to seconds + def _convert_timestamp_to_seconds(timestamp): + timestamp = timestamp.split(":") + timestamp = [float(t) for t in timestamp] + return timestamp[0] * 3600 + timestamp[1] * 60 + timestamp[2] + + start_time = _convert_timestamp_to_seconds(row["start_timestamp"]) + end_time = _convert_timestamp_to_seconds(row["stop_timestamp"]) + + annotations.append( + dict( + segment=[round(start_time, 2), round(end_time, 2)], + verb_label=f"id_{row['verb_class']:03d}", + verb_label_name=row["verb"], + noun_label=f"id_{row['noun_class']:03d}", + noun_label_name=row["noun"], + ) + ) + + database[video_id] = dict( + subset=subset, + duration=video_duration, + annotations=annotations, + ) + return database + + database = {} + database.update(_parse_subset(train_anno, duration_anno, "train", args.save_path)) + database.update(_parse_subset(val_anno, duration_anno, "val", args.save_path)) + database.update(_parse_subset(test_anno, duration_anno, "test", args.save_path)) + + out = dict(version="epic-kitchens-100", database=database) + json_path = os.path.join(args.save_path, "epic_kitchens_full.json") + with open(json_path, "w") as f: + json.dump(out, f) + print(f"The full annotation is saved at {json_path}") + + # parse only verb and noun annotations + def save_subset(database, subset_name): + sub_database = {} + for video_id in database.keys(): + annotation_verb = [] + if database[video_id]["subset"] != "test": + for anno in database[video_id]["annotations"]: + annotation_verb.append( + dict( + segment=anno["segment"], + label=anno[subset_name + "_label"], + label_name=anno[subset_name + "_label_name"], + ) + ) + + sub_database[video_id] = dict( + subset=database[video_id]["subset"], + duration=database[video_id]["duration"], + annotations=annotation_verb, + ) + else: + sub_database[video_id] = dict( + subset=database[video_id]["subset"], + duration=database[video_id]["duration"], + ) + + out = dict(version=f"epic-kitchens-100-{subset_name}", database=sub_database) + json_path = os.path.join(args.save_path, f"epic_kitchens_{subset_name}.json") + with open(json_path, "w") as f: + json.dump(out, f) + + print(f"The {subset_name} annotation is saved at {json_path}") + + save_subset(database, "verb") + save_subset(database, "noun") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="") + parser.add_argument("csv_dir", metavar="FILE", type=str, help="path to original annotation") + parser.add_argument("save_path", metavar="FILE", type=str, help="path to save") + args = parser.parse_args() + + parse_annotation(args) + + # python tools/prepare_data/convert_epic_kitchens_anno.py data/epic_kitchens-100/annotation data/epic_kitchens-100/annotations diff --git a/OpenTAD/tools/prepare_data/epic/download_annotation.sh b/OpenTAD/tools/prepare_data/epic/download_annotation.sh new file mode 100644 index 0000000000000000000000000000000000000000..322023eab01b6248b83070e7f09eb9b2ae49b464 --- /dev/null +++ b/OpenTAD/tools/prepare_data/epic/download_annotation.sh @@ -0,0 +1,9 @@ +DATA_DIR="../../../data/" + +if [[ ! -d "${DATA_DIR}" ]]; then + echo "${DATA_DIR} does not exist. Creating" + mkdir -p ${DATA_DIR} +fi + +# download annotations for Epic-Kitchens-100 +gdown --folder https://drive.google.com/drive/folders/1l04vJnpZP8NE8B8yho0uAkWL0_0fdqE0 -O $DATA_DIR --folder \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/fineaction/README.md b/OpenTAD/tools/prepare_data/fineaction/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1d6d993bfb5935a634c1915a497338bc1dbb04ca --- /dev/null +++ b/OpenTAD/tools/prepare_data/fineaction/README.md @@ -0,0 +1,41 @@ +# Data Preparation for FineAction-1.3 + +## Download Annotations + +You can download the annotation by +```bash +bash download_annotation.sh +``` +The annotation should be in `data/fineaction/annotations/`. + + +## Download Pre-extracted Features + +Please put the downloaded feature under the path: `data/fineaction/features/`. + + +We provide the following pre-extracted features: + +| Feature | Url | Backbone | Feature Extraction Setting | +| :-------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------: | :-------------------------------------------------: | +| videomae_h | [InternVideo Repo](https://github.com/OpenGVLab/InternVideo/tree/main/Downstream/Temporal-Action-Localization#to-reproduce-our-results-of-internvideo) | VideoMAE-H-K700-16x4x1 | snippet_stride=16, clip_length=16, frame_interval=1 | +| videomaev2_g | [VideoMAEv2 Repo](https://github.com/OpenGVLab/VideoMAEv2/blob/master/docs/TAD.md) | VideoMAEv2-g-K710-16x4x1 | snippet_stride=16, clip_length=16, frame_interval=1 | +| internvideo2_1b | [Official Repo](https://github.com/OpenGVLab/video-mamba-suite/blob/main/video-mamba-suite/temporal-action-localization/README.md) | InternVideo2-6B | snippet_stride=4, clip_length=16, frame_interval=1 | + +## Download Raw Videos + +Please put the downloaded video under the path: `data/fineaction/raw_data/`. + +You can download the raw video from [official website](https://github.com/Richard-61/FineAction). + +## Citation + +```BibTeX +@article{liu2022fineaction, + title={Fineaction: A fine-grained video dataset for temporal action localization}, + author={Liu, Yi and Wang, Limin and Wang, Yali and Ma, Xiao and Qiao, Yu}, + journal={IEEE Transactions on Image Processing}, + year={2022}, + publisher={IEEE} +} +``` \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/fineaction/download_annotation.sh b/OpenTAD/tools/prepare_data/fineaction/download_annotation.sh new file mode 100644 index 0000000000000000000000000000000000000000..c1521f4c932af630d9dacafcfab74848c632af8c --- /dev/null +++ b/OpenTAD/tools/prepare_data/fineaction/download_annotation.sh @@ -0,0 +1,9 @@ +DATA_DIR="../../../data/" + +if [[ ! -d "${DATA_DIR}" ]]; then + echo "${DATA_DIR} does not exist. Creating" + mkdir -p ${DATA_DIR} +fi + +# download annotations for FineAction-1.3 +gdown --folder https://drive.google.com/drive/folders/1R2ji2InJONWzBfLaEmp2CiT3FHHiZSJI -O $DATA_DIR --folder \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/generate_missing_list.py b/OpenTAD/tools/prepare_data/generate_missing_list.py new file mode 100644 index 0000000000000000000000000000000000000000..10505a4ff56cc9097619886d931ed5627277fe10 --- /dev/null +++ b/OpenTAD/tools/prepare_data/generate_missing_list.py @@ -0,0 +1,37 @@ +import argparse +import json +import os +import tqdm + + +def main(args): + missing_list = [] + + anno_database = json.load(open(args.anno_file))["database"] + for video_name in tqdm.tqdm(list(anno_database.keys())): + file_path = os.path.join(args.data_dir, f"{args.prefix}{video_name}{args.suffix}.{args.ext}") + + if not os.path.exists(file_path): + missing_list.append(video_name) + + saved_path = os.path.join(f"{args.data_dir}", "missing_files.txt") + with open(saved_path, "w") as f: + f.write("\n".join(missing_list)) + + print( + f"Total {len(anno_database.keys())} videos/features in dataset, " + f"missing {len(missing_list)} videos/features." + ) + print(f"Missing file has been saved in {saved_path}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Train a Temporal Action Detector") + parser.add_argument("anno_file", metavar="FILE", type=str, help="path to annotation") + parser.add_argument("data_dir", metavar="FILE", type=str, help="path to data folder") + parser.add_argument("--prefix", type=str, default="") + parser.add_argument("--suffix", type=str, default="") + parser.add_argument("--ext", type=str, default="npy") + args = parser.parse_args() + + main(args) diff --git a/OpenTAD/tools/prepare_data/hacs/README.md b/OpenTAD/tools/prepare_data/hacs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..aa56903077d60c51e2f28c88c47271ff7dfc856e --- /dev/null +++ b/OpenTAD/tools/prepare_data/hacs/README.md @@ -0,0 +1,40 @@ +# Data Preparation for HACS + +## Download Annotations + +You can download the annotation by +```bash +bash download_annotation.sh +``` +The annotation should be in `data/hacs-1.1.1/annotations/`. + + +## Download Pre-extracted Features + +Please put the downloaded feature under the path: `data/hacs-1.1.1/features/`. + + +We provide the following pre-extracted features for HACS: + +| Feature | Url | Backbone | Feature Extraction Setting | +| :-------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------------: | :----------------------------------------------------------------------------: | +| slowfast | [Google Drive](https://drive.google.com/file/d/1eTNay6xFFNp6qWSzlXRAkpPpLBukeRAW/view?usp=sharing) | SlowFast-R101 (HACS Finetuned) | 15fps, snippet_stride=8, clip_length=32, frame_interval=1, extracted by TCANet | +| videomae | [InternVideo Repo](https://github.com/OpenGVLab/InternVideo/tree/main/Downstream/Temporal-Action-Localization#to-reproduce-our-results-of-internvideo) | VideoMAE-L-K700 | snippet_stride=16, clip_length=16, frame_interval=1 | +| internvideo2_6b | [Official Repo](https://github.com/OpenGVLab/video-mamba-suite/blob/main/video-mamba-suite/temporal-action-localization/README.md) | InternVideo2-6B | snippet_stride=8, clip_length=16, frame_interval=1 | + +## Download Raw Videos + +Please put the downloaded video under the path: `data/hacs/raw_data/`. + +You can download the raw video from [official website](https://github.com/hangzhaomit/HACS-dataset). + +## Citation + +```BibTeX +@article{zhao2019hacs, + title={HACS: Human Action Clips and Segments Dataset for Recognition and Temporal Localization}, + author={Zhao, Hang and Yan, Zhicheng and Torresani, Lorenzo and Torralba, Antonio}, + journal={arXiv preprint arXiv:1712.09374}, + year={2019} +} +``` \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/hacs/download_annotation.sh b/OpenTAD/tools/prepare_data/hacs/download_annotation.sh new file mode 100644 index 0000000000000000000000000000000000000000..f396157db6c661efd715526a5231a95c77fd6d7b --- /dev/null +++ b/OpenTAD/tools/prepare_data/hacs/download_annotation.sh @@ -0,0 +1,9 @@ +DATA_DIR="../../../data/" + +if [[ ! -d "${DATA_DIR}" ]]; then + echo "${DATA_DIR} does not exist. Creating" + mkdir -p ${DATA_DIR} +fi + +# download annotations for HACS-1.1 +gdown --folder https://drive.google.com/drive/folders/1K5tPK-HYkKHYFsvkOydAGCnM9R5Nrrqx -O $DATA_DIR --folder \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/multi-thumos/README.md b/OpenTAD/tools/prepare_data/multi-thumos/README.md new file mode 100644 index 0000000000000000000000000000000000000000..609d065399fa83e01b42a6ef1ed04f351792e7c4 --- /dev/null +++ b/OpenTAD/tools/prepare_data/multi-thumos/README.md @@ -0,0 +1,27 @@ +# Data Preparation for Multi-THUMOS14 + +## Download Annotations + +You can download the annotation by +```bash +bash download_annotation.sh +``` +The annotation should be in `data/multithumos/annotations/`. + +## Download Pre-extracted Features and Raw Videos + +Note that the MultiTHUMOS dataset contains dense, multilabel, frame-level action annotations for 30 hours across 413 videos in the THUMOS'14 action detection dataset. Therefore, they share the same raw videos and pre-extracted features. Please refer to [THUMOS14 page](/tools/prepare_data/thumos/README.md) for more details. + +## Citation + +```BibTeX +@article{yeung2018every, + title={Every moment counts: Dense detailed labeling of actions in complex videos}, + author={Yeung, Serena and Russakovsky, Olga and Jin, Ning and Andriluka, Mykhaylo and Mori, Greg and Fei-Fei, Li}, + journal={International Journal of Computer Vision}, + volume={126}, + pages={375--389}, + year={2018}, + publisher={Springer} +} +``` \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/multi-thumos/download_annotation.sh b/OpenTAD/tools/prepare_data/multi-thumos/download_annotation.sh new file mode 100644 index 0000000000000000000000000000000000000000..984d9c638f27aa67a956c05cb194aec7deb331f4 --- /dev/null +++ b/OpenTAD/tools/prepare_data/multi-thumos/download_annotation.sh @@ -0,0 +1,9 @@ +DATA_DIR="../../../data/" + +if [[ ! -d "${DATA_DIR}" ]]; then + echo "${DATA_DIR} does not exist. Creating" + mkdir -p ${DATA_DIR} +fi + +# download annotations for Multi-THUMOS +gdown --folder https://drive.google.com/drive/folders/1benWupqjUEqxsup514hopBX1mHU2nrmd -O $DATA_DIR --folder \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/thumos/README.md b/OpenTAD/tools/prepare_data/thumos/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c089d3ba7caa2269c815588b2a668c846a74cc92 --- /dev/null +++ b/OpenTAD/tools/prepare_data/thumos/README.md @@ -0,0 +1,50 @@ +# Data Preparation for THUMOS14 + +## Download Annotations + +You can download the annotation by +```bash +bash download_annotation.sh +``` +The annotation should be in `data/thumos-14/annotations/`. + +- Following previous work such as G-TAD/VSGN, two videos are removed from the THUMOS14 validation set. (`video_test_0000270` due to wrong annotations, `video_test_0001292` due to empty annotations). Therefore, there are total 211 videos left in test subset. In this codebase, we use this annotation file to conduct all THUMOS-related experiments for a fair comparison. + + +## Download Pre-extracted Features + +Please put the downloaded feature under the path: `data/thumos-14/features/`. + + +We provide the following pre-extracted features for THUMOS14: + +| Feature | Url | Backbone | Feature Extraction Setting | +| :-------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------: | :------------------------------------------------: | +| i3d | [Google Drive](https://drive.google.com/file/d/1bxpfdFRQNCFlQ39aIocLjSt0C6_M6t6N/view?usp=sharing) | I3D (two stream) | snippet_stride=4, extracted by ActionFormer | +| tsn | [Google Drive](https://drive.google.com/file/d/1z5s8WTwZCXkGFRCT0jhyJhcJEGcGGcTx/view?usp=sharing) | TSN (two stream) | snippet_stride=1, extracted by G-TAD | +| slowfast_r50 | [Google Drive](https://drive.google.com/file/d/1ORcNmUcPXezDtOfCPawuTf6UkiQ--PQv/view?usp=sharing) | SlowFast-R50-8x8x1 | snippet_stride=4, clip_length=32, frame_interval=1 | +| slowfast_r101 | [Google Drive](https://drive.google.com/file/d/1L5WT2Qo-ZZ2sBtgv4uYXUHE8w5CGy5dy/view?usp=sharing) | SlowFast-R101-8x8x1 | snippet_stride=4, clip_length=32, frame_interval=1 | +| videomae_b | [Google Drive](https://drive.google.com/file/d/1qI20zPzjJ5rHz1G9QyJEksfw-QW9oSVu/view?usp=sharing) | VideoMAE-B-16x4x1 | snippet_stride=4, clip_length=16, frame_interval=1 | +| videomae_l | [Google Drive](https://drive.google.com/file/d/1-qHD6s8w21TCeExp9DPtAGX409OjwW18/view?usp=sharing) | VideoMAE-L-16x4x1 | snippet_stride=4, clip_length=16, frame_interval=1 | +| videomae_h | [InternVideo Repo](https://github.com/OpenGVLab/InternVideo/tree/main/Downstream/Temporal-Action-Localization#to-reproduce-our-results-of-internvideo) | VideoMAE-H-K700-16x4x1 | snippet_stride=4, clip_length=16, frame_interval=1 | +| videomaev2_g | [Google Drive](https://drive.google.com/file/d/1FRoCz_ZS13faRLN6ocfwghsmIsENLz7_/view?usp=sharing) | VideoMAEv2-g-K710-16x4x1 | snippet_stride=4, clip_length=16, frame_interval=1 | +| internvideo2_6b | [Official Repo](https://github.com/OpenGVLab/video-mamba-suite/blob/main/video-mamba-suite/temporal-action-localization/README.md) | InternVideo2-6B | snippet_stride=4, clip_length=16, frame_interval=1 | + +## Download Raw Videos + +Please put the downloaded video under the path: `data/thumos-14/raw_data/`. + +You can download the raw video from [official website](https://www.crcv.ucf.edu/THUMOS14/download.html), or download from this [Google Drive](https://drive.google.com/file/d/1cbwDvIk4DsM5uSZJpGDfjGu4ZeZhftgK/view?usp=sharing). + +## Citation + +```BibTeX +@misc{THUMOS14, + author = {Jiang, Y.-G. and Liu, J. and Roshan Zamir, A. and Toderici, G. and Laptev, + I. and Shah, M. and Sukthankar, R.}, + title = {{THUMOS} Challenge: Action Recognition with a Large + Number of Classes}, + howpublished = "\url{http://crcv.ucf.edu/THUMOS14/}", + Year = {2014} +} +``` \ No newline at end of file diff --git a/OpenTAD/tools/prepare_data/thumos/download_annotation.sh b/OpenTAD/tools/prepare_data/thumos/download_annotation.sh new file mode 100644 index 0000000000000000000000000000000000000000..65e3891dfc0c89d0b8c37d9b76032198de92dc22 --- /dev/null +++ b/OpenTAD/tools/prepare_data/thumos/download_annotation.sh @@ -0,0 +1,9 @@ +DATA_DIR="../../../data/" + +if [[ ! -d "${DATA_DIR}" ]]; then + echo "${DATA_DIR} does not exist. Creating" + mkdir -p ${DATA_DIR} +fi + +# download annotations for THUMOS-14 +gdown --folder https://drive.google.com/drive/folders/1sGTFuJ-G08sOZi9SHCBR7W3Q8IIryHKN -O $DATA_DIR --folder \ No newline at end of file diff --git a/OpenTAD/tools/test.py b/OpenTAD/tools/test.py new file mode 100644 index 0000000000000000000000000000000000000000..89f1ad7d7a0de01cd9f8a816be057e8dda20adee --- /dev/null +++ b/OpenTAD/tools/test.py @@ -0,0 +1,115 @@ +import os +import sys + +sys.dont_write_bytecode = True +path = os.path.join(os.path.dirname(__file__), "..") +if path not in sys.path: + sys.path.insert(0, path) + +import argparse +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel +from mmengine.config import Config +from opentad.models import build_detector +from opentad.datasets import build_dataset, build_dataloader +from opentad.cores import eval_one_epoch +from opentad.utils import update_workdir, set_seed, create_folder, setup_logger + + +def parse_args(): + parser = argparse.ArgumentParser(description="Test a Temporal Action Detector") + parser.add_argument("config", metavar="FILE", type=str, help="path to config file") + parser.add_argument("--checkpoint", type=str, default="none", help="the checkpoint path") + parser.add_argument("--seed", type=int, default=42, help="random seed") + parser.add_argument("--id", type=int, default=0, help="repeat experiment id") + parser.add_argument("--not_eval", action="store_true", help="whether to not to eval, only do inference") + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + + # load config + cfg = Config.fromfile(args.config) + + # DDP init + args.local_rank = int(os.environ["LOCAL_RANK"]) + args.world_size = int(os.environ["WORLD_SIZE"]) + args.rank = int(os.environ["RANK"]) + print(f"Distributed init (rank {args.rank}/{args.world_size}, local rank {args.local_rank})") + dist.init_process_group("nccl", rank=args.rank, world_size=args.world_size) + torch.cuda.set_device(args.local_rank) + + # set random seed, create work_dir + set_seed(args.seed) + cfg = update_workdir(cfg, args.id, torch.cuda.device_count()) + if args.rank == 0: + create_folder(cfg.work_dir) + + # setup logger + logger = setup_logger("Test", save_dir=cfg.work_dir, distributed_rank=args.rank) + logger.info(f"Using torch version: {torch.__version__}, CUDA version: {torch.version.cuda}") + logger.info(f"Config: \n{cfg.pretty_text}") + + # build dataset + test_dataset = build_dataset(cfg.dataset.test, default_args=dict(logger=logger)) + test_loader = build_dataloader( + test_dataset, + rank=args.rank, + world_size=args.world_size, + shuffle=False, + drop_last=False, + **cfg.solver.test, + ) + # build model + model = build_detector(cfg.model) + + # DDP + model = model.to(args.local_rank) + model = DistributedDataParallel(model, device_ids=[args.local_rank]) + logger.info(f"Using DDP with {torch.cuda.device_count()} GPUS...") + + # load checkpoint: args -> config -> best + if args.checkpoint != "none": + checkpoint_path = args.checkpoint + elif "test_epoch" in cfg.inference.keys(): + checkpoint_path = os.path.join(cfg.work_dir, f"checkpoint/epoch_{cfg.inference.test_epoch}.pth") + else: + checkpoint_path = os.path.join(cfg.work_dir, "checkpoint/best.pth") + logger.info("Loading checkpoint from: {}".format(checkpoint_path)) + device = f"cuda:{args.rank % torch.cuda.device_count()}" + checkpoint = torch.load(checkpoint_path, map_location=device) + logger.info("Checkpoint is epoch {}.".format(checkpoint["epoch"])) + + # Model EMA + use_ema = getattr(cfg.solver, "ema", False) + if use_ema: + model.load_state_dict(checkpoint["state_dict_ema"]) + logger.info("Using Model EMA...") + else: + model.load_state_dict(checkpoint["state_dict"]) + + # AMP: automatic mixed precision + use_amp = getattr(cfg.solver, "amp", False) + if use_amp: + logger.info("Using Automatic Mixed Precision...") + + # test the detector + logger.info("Testing Starts...\n") + eval_one_epoch( + test_loader, + model, + cfg, + logger, + args.rank, + model_ema=None, # since we have load the ema in the model + use_amp=use_amp, + world_size=args.world_size, + not_eval=args.not_eval, + ) + + +if __name__ == "__main__": + main() diff --git a/OpenTAD/tools/train.py b/OpenTAD/tools/train.py new file mode 100644 index 0000000000000000000000000000000000000000..68c639c55eb112a25e451178ec08242bceb47feb --- /dev/null +++ b/OpenTAD/tools/train.py @@ -0,0 +1,228 @@ +import os +import sys + +sys.dont_write_bytecode = True +path = os.path.join(os.path.dirname(__file__), "..") +if path not in sys.path: + sys.path.insert(0, path) + +import argparse +import torch +import torch.distributed as dist +from torch.distributed.algorithms.ddp_comm_hooks import default as comm_hooks +from torch.nn.parallel import DistributedDataParallel +from torch.cuda.amp import GradScaler +from mmengine.config import Config, DictAction +from opentad.models import build_detector +from opentad.datasets import build_dataset, build_dataloader +from opentad.cores import train_one_epoch, val_one_epoch, eval_one_epoch, build_optimizer, build_scheduler +from opentad.utils import ( + set_seed, + update_workdir, + create_folder, + save_config, + setup_logger, + ModelEma, + save_checkpoint, + save_best_checkpoint, +) + + +def parse_args(): + parser = argparse.ArgumentParser(description="Train a Temporal Action Detector") + parser.add_argument("config", metavar="FILE", type=str, help="path to config file") + parser.add_argument("--seed", type=int, default=42, help="random seed") + parser.add_argument("--id", type=int, default=0, help="repeat experiment id") + parser.add_argument("--resume", type=str, default=None, help="resume from a checkpoint") + parser.add_argument("--not_eval", action="store_true", help="whether not to eval, only do inference") + parser.add_argument("--disable_deterministic", action="store_true", help="disable deterministic for faster speed") + parser.add_argument("--cfg-options", nargs="+", action=DictAction, help="override settings") + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + + # load config + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # DDP init + args.local_rank = int(os.environ["LOCAL_RANK"]) + args.world_size = int(os.environ["WORLD_SIZE"]) + args.rank = int(os.environ["RANK"]) + print(f"Distributed init (rank {args.rank}/{args.world_size}, local rank {args.local_rank})") + dist.init_process_group("nccl", rank=args.rank, world_size=args.world_size) + torch.cuda.set_device(args.local_rank) + + # set random seed, create work_dir, and save config + set_seed(args.seed, args.disable_deterministic) + cfg = update_workdir(cfg, args.id, args.world_size) + if args.rank == 0: + create_folder(cfg.work_dir) + save_config(args.config, cfg.work_dir) + + # setup logger + logger = setup_logger("Train", save_dir=cfg.work_dir, distributed_rank=args.rank) + logger.info(f"Using torch version: {torch.__version__}, CUDA version: {torch.version.cuda}") + logger.info(f"Config: \n{cfg.pretty_text}") + + # build dataset + train_dataset = build_dataset(cfg.dataset.train, default_args=dict(logger=logger)) + train_loader = build_dataloader( + train_dataset, + rank=args.rank, + world_size=args.world_size, + shuffle=True, + drop_last=True, + **cfg.solver.train, + ) + + val_dataset = build_dataset(cfg.dataset.val, default_args=dict(logger=logger)) + val_loader = build_dataloader( + val_dataset, + rank=args.rank, + world_size=args.world_size, + shuffle=False, + drop_last=False, + **cfg.solver.val, + ) + + test_dataset = build_dataset(cfg.dataset.test, default_args=dict(logger=logger)) + test_loader = build_dataloader( + test_dataset, + rank=args.rank, + world_size=args.world_size, + shuffle=False, + drop_last=False, + **cfg.solver.test, + ) + + # build model + model = build_detector(cfg.model) + + # DDP + use_static_graph = getattr(cfg.solver, "static_graph", False) + model = model.to(args.local_rank) + model = DistributedDataParallel( + model, + device_ids=[args.local_rank], + output_device=args.local_rank, + find_unused_parameters=False if use_static_graph else True, + static_graph=use_static_graph, # default is False, should be true when use activation checkpointing in E2E + ) + logger.info(f"Using DDP with total {args.world_size} GPUS...") + + # FP16 compression + use_fp16_compress = getattr(cfg.solver, "fp16_compress", False) + if use_fp16_compress: + logger.info("Using FP16 compression ...") + model.register_comm_hook(state=None, hook=comm_hooks.fp16_compress_hook) + + # Model EMA + use_ema = getattr(cfg.solver, "ema", False) + if use_ema: + logger.info("Using Model EMA...") + model_ema = ModelEma(model) + else: + model_ema = None + + # AMP: automatic mixed precision + use_amp = getattr(cfg.solver, "amp", False) + if use_amp: + logger.info("Using Automatic Mixed Precision...") + scaler = GradScaler() + else: + scaler = None + + # build optimizer and scheduler + optimizer = build_optimizer(cfg.optimizer, model, logger) + scheduler, max_epoch = build_scheduler(cfg.scheduler, optimizer, len(train_loader)) + + # override the max_epoch + max_epoch = cfg.workflow.get("end_epoch", max_epoch) + + # resume: reset epoch, load checkpoint / best rmse + if args.resume != None: + logger.info("Resume training from: {}".format(args.resume)) + device = f"cuda:{args.local_rank}" + checkpoint = torch.load(args.resume, map_location=device) + resume_epoch = checkpoint["epoch"] + logger.info("Resume epoch is {}".format(resume_epoch)) + model.load_state_dict(checkpoint["state_dict"]) + optimizer.load_state_dict(checkpoint["optimizer"]) + scheduler.load_state_dict(checkpoint["scheduler"]) + if model_ema != None: + model_ema.module.load_state_dict(checkpoint["state_dict_ema"]) + + del checkpoint # save memory if the model is very large such as ViT-g + else: + resume_epoch = -1 + + # train the detector + logger.info("Training Starts...\n") + val_loss_best = 1e6 + val_start_epoch = cfg.workflow.get("val_start_epoch", 0) + for epoch in range(resume_epoch + 1, max_epoch): + train_loader.sampler.set_epoch(epoch) + + # train for one epoch + train_one_epoch( + train_loader, + model, + optimizer, + scheduler, + epoch, + logger, + model_ema=model_ema, + clip_grad_l2norm=cfg.solver.clip_grad_norm, + logging_interval=cfg.workflow.logging_interval, + scaler=scaler, + ) + + # save checkpoint + if (epoch == max_epoch - 1) or ((epoch + 1) % cfg.workflow.checkpoint_interval == 0): + if args.rank == 0: + save_checkpoint(model, model_ema, optimizer, scheduler, epoch, work_dir=cfg.work_dir) + + # val for one epoch + if epoch >= val_start_epoch: + if (cfg.workflow.val_loss_interval > 0) and ((epoch + 1) % cfg.workflow.val_loss_interval == 0): + val_loss = val_one_epoch( + val_loader, + model, + logger, + args.rank, + epoch, + model_ema=model_ema, + use_amp=use_amp, + ) + + # save the best checkpoint + if val_loss < val_loss_best: + logger.info(f"New best epoch {epoch}") + val_loss_best = val_loss + if args.rank == 0: + save_best_checkpoint(model, model_ema, epoch, work_dir=cfg.work_dir) + + # eval for one epoch + if epoch >= val_start_epoch: + if (cfg.workflow.val_eval_interval > 0) and ((epoch + 1) % cfg.workflow.val_eval_interval == 0): + eval_one_epoch( + test_loader, + model, + cfg, + logger, + args.rank, + model_ema=model_ema, + use_amp=use_amp, + world_size=args.world_size, + not_eval=args.not_eval, + ) + logger.info("Training Over...\n") + + +if __name__ == "__main__": + main()