├── .gitignore ├── LICENSE ├── README.md ├── config.py ├── configs ├── dat_base.yaml ├── dat_base_384.yaml ├── dat_p.yaml ├── dat_small.yaml └── dat_tiny.yaml ├── data ├── __init__.py ├── build.py └── samplers.py ├── evaluate.sh ├── figures ├── datt.png ├── motivation.png └── vis.png ├── logger.py ├── lr_scheduler.py ├── main.py ├── map_22kto1k.pth ├── models ├── __init__.py ├── build.py ├── dat.py ├── dat_blocks.py ├── nat.py ├── qna.py └── slide.py ├── optimizer.py ├── slurm_main.py ├── train.sh ├── train_slurm.sh └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # other 104 | .vscode 105 | # data/ 106 | output/ 107 | 108 | clean_ckp.py 109 | 110 | 111 | # DDETR something 112 | deformable_detr_ops 113 | d_detr.py 114 | ddetr_b1.yaml 115 | ddetr_b2.yaml 116 | ddetr_b3.yaml 117 | 118 | # misc 119 | stat_mem.py 120 | stat_model.py -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vision Transformer with Deformable Attention 2 | 3 | This repository contains the code for the paper Vision Transformer with Deformable Attention (CVPR2022, **Best Paper Finalists**) \[[arXiv](https://arxiv.org/abs/2201.00520)\]\[[video](https://cloud.tsinghua.edu.cn/f/17476d769ced48eaa278/)]\[[poster](https://cloud.tsinghua.edu.cn/f/9afe817efb504d32951b/)\]\[[CVPR page](https://openaccess.thecvf.com/content/CVPR2022/html/Xia_Vision_Transformer_With_Deformable_Attention_CVPR_2022_paper.html)\], and DAT++: Spatially Dynamic Vision Transformerwith Deformable Attention (extended version)\[[arXiv](https://arxiv.org/abs/2309.01430)]. 4 | 5 | This repository mainly includes the implementation for image classification experiments. For object detection and instance segmentation, please refer to [DAT-Detection](https://github.com/LeapLabTHU/DAT-Detection); for semantic segmentation, please see [DAT-Segmentation](https://github.com/LeapLabTHU/DAT-Segmentation) for more details. 6 | 7 | ## Introduction 8 | 9 | ### Motivation 10 | 11 | ![Motivation](figures/motivation.png) 12 | 13 | **(a) Vision Transformer(ViT)** has proved its superiority over many tasks thanks to its large or even global receptive field. However, this global attention leads to excessive computational costs. **(b) Swin Transformer** proposes shifted window attention, which is a more efficient sparse attention mechanism with linear computation complexity. Nevertheless, this hand-crafted attention pattern is likely to drop important features outside one window, and shifting windows impedes the growth of the receptive field, limiting modeling the long-range dependencies. **(c) DCN** expands the receptive fields of the standard convolutions with the learned offsets for each different query. Howbeit, directly applying this technique to the Vision Transformer is non-trivial for the quadratic space complexity and the training difficulties. **(d) Deformable Attention (DAT)** is proposed to model the relations among tokens effectively under the guidance of the important regions in the feature maps. This flexible scheme enables the self-attention module to focus on relevant regions and capture more informative features. 14 | 15 | 16 | ### Method 17 | 18 | ![Deform_Attn](figures/datt.png) 19 | 20 | By learning several groups of offsets for the grid reference points, the deformed keys and values are sampled from these shifted locations. This deformable attention can capture the most informative regions in the image. On this basis, we present **Deformable Attention Transformer (DAT)** and **DAT++**, a general backbone model with deformable attention for both image classification and other dense prediction tasks. 21 | 22 | ### Visualizations 23 | 24 | ![Visualizations](figures/vis.png) 25 | 26 | Visualizations show the most important keys denotes in orange circles, where larger circles indicates higher attention scores in the 3rd column. The 4-th and 5-th columns display the important keys (orange circles) to some queries (red starts). The important keys cover the main parts of the objects, which demonstrates the effectiveness of DAT and DAT++. 27 | 28 | ## Dependencies 29 | 30 | - NVIDIA GPU + CUDA 11.3 31 | - Python 3.9 32 | - PyTorch == 1.11.0 33 | - torchvision == 0.12.0 34 | - numpy == 1.20.3 35 | - timm == 0.5.4 36 | - einops == 0.6.1 37 | - natten == 0.14.6 38 | - PyYAML 39 | - yacs 40 | - termcolor 41 | 42 | ## Evaluate Pretrained Models on ImageNet-1K Classification 43 | 44 | We provide the pretrained models in the tiny, small, and base versions of DAT++, as listed below. 45 | 46 | | model | resolution | acc@1 | config | pretrained weights | 47 | | :---: | :---: | :---: | :---: | :---: | 48 | | DAT-T++ | 224x224 | 83.9 | [config](configs/dat_tiny.yaml) | [OneDrive](https://1drv.ms/u/s!ApI0vb6wPqmtgrl-pI8MPFoll-ueNQ?e=bpdieu) / [TsinghuaCloud](https://cloud.tsinghua.edu.cn/f/14c5ddae10b642e68089/) | 49 | | DAT-S++ | 224x224 | 84.6 | [config](configs/dat_small.yaml) | [OneDrive](https://1drv.ms/u/s!ApI0vb6wPqmtgroB0ESeknbTsksWAg?e=Jbh0BS) / [TsinghuaCloud](https://cloud.tsinghua.edu.cn/f/4c2a76360c964fbd81d5/) | 50 | | DAT-B++ | 224x224 | 84.9 | [config](configs/dat_base.yaml) | [OneDrive](https://1drv.ms/u/s!ApI0vb6wPqmtgrl_P46QOehhgA0-wg?e=DJRAfw) / [TsinghuaCloud](https://cloud.tsinghua.edu.cn/f/8e30492404d348d89f25/) | 51 | | DAT-B++ | 384x384 | 85.9 | [config](configs/dat_base_384.yaml) | [OneDrive](https://1drv.ms/u/s!ApI0vb6wPqmtgroAI7cLAoj17khZNw?e=7yzxAg) / [TsinghuaCloud](https://cloud.tsinghua.edu.cn/f/032dc804cdf44bf18bb5/) | 52 | 53 | To evaluate one model, please download the pretrained weights to your local machine and run the script `evaluate.sh` as follow. 54 | 55 | **Please notice: Before training or evaluation, please set the `--data-path` argument in `train.sh` or `evaluate.sh` to the path where ImageNet-1K data stores.** 56 | 57 | ``` 58 | bash evaluate.sh 59 | ``` 60 | 61 | E.g., suppose evaluating the DAT-Tiny model (`dat_pp_tiny_in1k_224.pth`) with 8 GPUs, the command should be: 62 | 63 | ``` 64 | bash evaluate.sh 8 configs/dat_tiny.yaml dat_pp_tiny_in1k_224.pth 65 | ``` 66 | 67 | And the evaluation result should give: 68 | 69 | ``` 70 | [2023-09-04 17:18:15 dat_plus_plus] (main.py 301): INFO * Acc@1 83.864 Acc@5 96.734 71 | [2023-09-04 17:18:15 dat_plus_plus] (main.py 179): INFO Accuracy of the network on the 50000 test images: 83.9% 72 | ``` 73 | 74 | 75 | ## Train Models from Scratch 76 | 77 | To train a model from scratch, we provide a simple script `train.sh`. E.g, to train a model with 8 GPUs on a single node, you can use this command: 78 | 79 | ``` 80 | bash train.sh 8 81 | ``` 82 | 83 | We also provide a training script `train_slurm.sh` for training models on multiple machines with a larger batch-size like 4096. 84 | 85 | ``` 86 | bash train_slurm.sh 32 87 | ``` 88 | 89 | **Remember to change the \ in the script files to your own ImageNet directory.** 90 | 91 | ## Future Updates 92 | 93 | - [x] Classification pretrained models. 94 | - [x] Object Detection codebase & models. 95 | - [x] Semantic Segmentation codebase & models. 96 | - [ ] ImageNet-22K pretraining for DAT-B++ and DAT-L++. 97 | - [ ] DINO / Mask2Former for system level DET/SEG. 98 | - [ ] CUDA / CUTLASS acceleration (maybe). 99 | 100 | ## Acknowledgements 101 | 102 | This code is developed on the top of [Swin Transformer](https://github.com/microsoft/Swin-Transformer), we thank to their efficient and neat codebase. The computational resources supporting this work are provided by [Hangzhou 103 | High-Flyer AI Fundamental Research Co.,Ltd](https://www.high-flyer.cn/). 104 | 105 | ## Citation 106 | 107 | If you find our work is useful in your research, please consider citing: 108 | 109 | ``` 110 | @article{xia2023dat, 111 | title={DAT++: Spatially Dynamic Vision Transformer with Deformable Attention}, 112 | author={Zhuofan Xia and Xuran Pan and Shiji Song and Li Erran Li and Gao Huang}, 113 | year={2023}, 114 | journal={arXiv preprint arXiv:2309.01430}, 115 | } 116 | 117 | @InProceedings{Xia_2022_CVPR, 118 | author = {Xia, Zhuofan and Pan, Xuran and Song, Shiji and Li, Li Erran and Huang, Gao}, 119 | title = {Vision Transformer With Deformable Attention}, 120 | booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, 121 | month = {June}, 122 | year = {2022}, 123 | pages = {4794-4803} 124 | } 125 | ``` 126 | 127 | ## Contact 128 | 129 | If you have any questions or concerns, please send email to [xzf23@mails.tsinghua.edu.cn](mailto:xzf23@mails.tsinghua.edu.cn). 130 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import os 12 | import yaml 13 | from yacs.config import CfgNode as CN 14 | 15 | _C = CN() 16 | 17 | # Base config files 18 | _C.BASE = [''] 19 | 20 | # ----------------------------------------------------------------------------- 21 | # Data settings 22 | # ----------------------------------------------------------------------------- 23 | _C.DATA = CN() 24 | # Batch size for a single GPU, could be overwritten by command line argument 25 | _C.DATA.BATCH_SIZE = 128 26 | # Path to dataset, could be overwritten by command line argument 27 | _C.DATA.DATA_PATH = '' 28 | # Dataset name 29 | _C.DATA.DATASET = 'imagenet' 30 | # Input image size 31 | _C.DATA.IMG_SIZE = 224 32 | # Interpolation to resize image (random, bilinear, bicubic) 33 | _C.DATA.INTERPOLATION = 'bicubic' 34 | # Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU. 35 | _C.DATA.PIN_MEMORY = True 36 | # Number of data loading threads 37 | _C.DATA.NUM_WORKERS = 8 38 | 39 | # ----------------------------------------------------------------------------- 40 | # Model settings 41 | # ----------------------------------------------------------------------------- 42 | _C.MODEL = CN() 43 | # Model type 44 | _C.MODEL.TYPE = 'dat' 45 | # Model name 46 | _C.MODEL.NAME = 'dat_tiny' 47 | # Checkpoint to resume, could be overwritten by command line argument 48 | _C.MODEL.RESUME = '' 49 | # Number of classes, overwritten in data preparation 50 | _C.MODEL.NUM_CLASSES = 1000 51 | # Dropout rate 52 | _C.MODEL.DROP_RATE = 0.0 53 | # Drop path rate 54 | _C.MODEL.DROP_PATH_RATE = 0.1 55 | # Label Smoothing 56 | _C.MODEL.LABEL_SMOOTHING = 0.1 57 | 58 | _C.MODEL.PRETRAINED = None 59 | 60 | _C.MODEL.DAT = CN(new_allowed=True) 61 | # ----------------------------------------------------------------------------- 62 | # Training settings 63 | # ----------------------------------------------------------------------------- 64 | _C.TRAIN = CN() 65 | _C.TRAIN.START_EPOCH = 0 66 | _C.TRAIN.EPOCHS = 300 67 | _C.TRAIN.WARMUP_EPOCHS = 20 68 | _C.TRAIN.WEIGHT_DECAY = 0.05 69 | _C.TRAIN.BASE_LR = 5e-4 70 | _C.TRAIN.WARMUP_LR = 5e-7 71 | _C.TRAIN.MIN_LR = 5e-6 72 | # Clip gradient norm 73 | _C.TRAIN.CLIP_GRAD = 5.0 74 | # Auto resume from latest checkpoint 75 | _C.TRAIN.AUTO_RESUME = True 76 | # Whether to use gradient checkpointing to save memory 77 | # could be overwritten by command line argument 78 | _C.TRAIN.USE_CHECKPOINT = False 79 | 80 | # LR scheduler 81 | _C.TRAIN.LR_SCHEDULER = CN() 82 | _C.TRAIN.LR_SCHEDULER.NAME = 'cosine' 83 | # Epoch interval to decay LR, used in StepLRScheduler 84 | _C.TRAIN.LR_SCHEDULER.DECAY_EPOCHS = 30 85 | # LR decay rate, used in StepLRScheduler 86 | _C.TRAIN.LR_SCHEDULER.DECAY_RATE = 0.1 87 | 88 | # Optimizer 89 | _C.TRAIN.OPTIMIZER = CN() 90 | _C.TRAIN.OPTIMIZER.NAME = 'adamw' 91 | # Optimizer Epsilon 92 | _C.TRAIN.OPTIMIZER.EPS = 1e-8 93 | # Optimizer Betas 94 | _C.TRAIN.OPTIMIZER.BETAS = (0.9, 0.999) 95 | # SGD momentum 96 | _C.TRAIN.OPTIMIZER.MOMENTUM = 0.9 97 | 98 | # ----------------------------------------------------------------------------- 99 | # Augmentation settings 100 | # ----------------------------------------------------------------------------- 101 | _C.AUG = CN() 102 | # Color jitter factor 103 | _C.AUG.COLOR_JITTER = 0.4 104 | # Use AutoAugment policy. "v0" or "original" 105 | _C.AUG.AUTO_AUGMENT = 'rand-m9-mstd0.5-inc1' 106 | # Random erase prob 107 | _C.AUG.REPROB = 0.25 108 | # Random erase mode 109 | _C.AUG.REMODE = 'pixel' 110 | # Random erase count 111 | _C.AUG.RECOUNT = 1 112 | # Mixup alpha, mixup enabled if > 0 113 | _C.AUG.MIXUP = 0.8 114 | # Cutmix alpha, cutmix enabled if > 0 115 | _C.AUG.CUTMIX = 1.0 116 | # Cutmix min/max ratio, overrides alpha and enables cutmix if set 117 | _C.AUG.CUTMIX_MINMAX = None 118 | # Probability of performing mixup or cutmix when either/both is enabled 119 | _C.AUG.MIXUP_PROB = 1.0 120 | # Probability of switching to cutmix when both mixup and cutmix enabled 121 | _C.AUG.MIXUP_SWITCH_PROB = 0.5 122 | # How to apply mixup/cutmix params. Per "batch", "pair", or "elem" 123 | _C.AUG.MIXUP_MODE = 'batch' 124 | 125 | # ----------------------------------------------------------------------------- 126 | # Testing settings 127 | # ----------------------------------------------------------------------------- 128 | _C.TEST = CN() 129 | # Whether to use center crop when testing 130 | _C.TEST.CROP = True 131 | 132 | # ----------------------------------------------------------------------------- 133 | # Misc 134 | # ----------------------------------------------------------------------------- 135 | 136 | # overwritten by command line argument 137 | _C.AMP = False 138 | # Path to output folder, overwritten by command line argument 139 | _C.OUTPUT = '' 140 | # Tag of experiment, overwritten by command line argument 141 | _C.TAG = 'default' 142 | # Frequency to save checkpoint 143 | _C.SAVE_FREQ = 1 144 | # Frequency to logging info 145 | _C.PRINT_FREQ = 100 146 | # Fixed random seed 147 | _C.SEED = 0 148 | # Perform evaluation only, overwritten by command line argument 149 | _C.EVAL_MODE = False 150 | # Test throughput only, overwritten by command line argument 151 | _C.THROUGHPUT_MODE = False 152 | # local rank for DistributedDataParallel, given by command line argument 153 | _C.LOCAL_RANK = 0 154 | 155 | 156 | def _update_config_from_file(config, cfg_file): 157 | config.defrost() 158 | with open(cfg_file, 'r') as f: 159 | yaml_cfg = yaml.load(f, Loader=yaml.FullLoader) 160 | 161 | for cfg in yaml_cfg.setdefault('BASE', ['']): 162 | if cfg: 163 | _update_config_from_file( 164 | config, os.path.join(os.path.dirname(cfg_file), cfg) 165 | ) 166 | print('=> merge config from {}'.format(cfg_file)) 167 | config.merge_from_file(cfg_file) 168 | config.freeze() 169 | 170 | 171 | def update_config(config, args): 172 | _update_config_from_file(config, args.cfg) 173 | 174 | config.defrost() 175 | if args.opts: 176 | config.merge_from_list(args.opts) 177 | 178 | # merge from specific arguments 179 | if args.batch_size: 180 | config.DATA.BATCH_SIZE = args.batch_size 181 | if args.data_path: 182 | config.DATA.DATA_PATH = args.data_path 183 | if args.resume: 184 | config.MODEL.RESUME = args.resume 185 | if args.amp: 186 | config.AMP = args.amp 187 | if args.print_freq: 188 | config.PRINT_FREQ = args.print_freq 189 | if args.output: 190 | config.OUTPUT = args.output 191 | if args.tag: 192 | config.TAG = args.tag 193 | if args.eval: 194 | config.EVAL_MODE = True 195 | if args.throughput: 196 | config.THROUGHPUT_MODE = True 197 | 198 | # output folder 199 | config.OUTPUT = os.path.join(config.OUTPUT, config.MODEL.NAME, config.TAG) 200 | 201 | config.freeze() 202 | 203 | 204 | def get_config(args): 205 | """Get a yacs CfgNode object with default values.""" 206 | # Return a clone so that the defaults will not be altered 207 | # This is for the "local variable" use pattern 208 | config = _C.clone() 209 | update_config(config, args) 210 | 211 | return config 212 | -------------------------------------------------------------------------------- /configs/dat_base.yaml: -------------------------------------------------------------------------------- 1 | MODEL: 2 | TYPE: dat 3 | NAME: dat_plus_plus 4 | DAT: 5 | img_size: 224 6 | patch_size: 4 7 | num_classes: 1000 8 | expansion: 4 9 | dim_stem: 128 10 | dims: [128, 256, 512, 1024] 11 | depths: [2, 4, 18, 2] 12 | stage_spec: [[N, D], [N, D, N, D], [N, D, N, D, N, D, N, D, N, D, N, D, N, D, N, D, N, D], [D, D]] 13 | heads: [4, 8, 16, 32] 14 | window_sizes: [7, 7, 7, 7] 15 | groups: [2, 4, 8, 16] 16 | use_pes: [True, True, True, True] 17 | dwc_pes: [False, False, False, False] 18 | strides: [8, 4, 2, 1] 19 | offset_range_factor: [-1, -1, -1, -1] 20 | no_offs: [False, False, False, False] 21 | fixed_pes: [False, False, False, False] 22 | use_dwc_mlps: [True, True, True, True] 23 | use_lpus: [True, True, True, True] 24 | use_conv_patches: True 25 | ksizes: [9, 7, 5, 3] 26 | nat_ksizes: [7, 7, 7, 7] 27 | drop_rate: 0.0 28 | attn_drop_rate: 0.0 29 | drop_path_rate: 0.7 30 | 31 | TRAIN: 32 | EPOCHS: 300 33 | WARMUP_EPOCHS: 20 34 | 35 | DATA: 36 | BATCH_SIZE: 64 37 | 38 | SAVE_FREQ: 1 -------------------------------------------------------------------------------- /configs/dat_base_384.yaml: -------------------------------------------------------------------------------- 1 | MODEL: 2 | TYPE: dat 3 | NAME: dat_plus_plus 4 | PRETRAINED: "" 5 | DAT: 6 | img_size: 224 7 | patch_size: 4 8 | num_classes: 1000 9 | expansion: 4 10 | dim_stem: 128 11 | dims: [128, 256, 512, 1024] 12 | depths: [2, 4, 18, 2] 13 | stage_spec: [[N, D], [N, D, N, D], [N, D, N, D, N, D, N, D, N, D, N, D, N, D, N, D, N, D], [D, D]] 14 | heads: [4, 8, 16, 32] 15 | window_sizes: [7, 7, 7, 7] 16 | groups: [2, 4, 8, 16] 17 | use_pes: [True, True, True, True] 18 | dwc_pes: [False, False, False, False] 19 | strides: [8, 4, 2, 1] 20 | offset_range_factor: [-1, -1, -1, -1] 21 | no_offs: [False, False, False, False] 22 | fixed_pes: [False, False, False, False] 23 | use_dwc_mlps: [True, True, True, True] 24 | use_lpus: [True, True, True, True] 25 | use_conv_patches: True 26 | ksizes: [9, 7, 5, 3] 27 | nat_ksizes: [7, 7, 7, 7] 28 | drop_rate: 0.0 29 | attn_drop_rate: 0.0 30 | drop_path_rate: 0.6 31 | 32 | TRAIN: 33 | EPOCHS: 30 34 | WARMUP_EPOCHS: 0 35 | WEIGHT_DECAY: 1.0e-8 36 | BASE_LR: 2e-05 37 | WARMUP_LR: 2e-08 38 | MIN_LR: 2e-07 39 | 40 | TEST: 41 | CROP: False 42 | 43 | DATA: 44 | BATCH_SIZE: 24 45 | IMG_SIZE: 384 46 | 47 | SAVE_FREQ: 1 48 | 49 | -------------------------------------------------------------------------------- /configs/dat_p.yaml: -------------------------------------------------------------------------------- 1 | MODEL: 2 | TYPE: dat 3 | NAME: dat_plus 4 | DAT: 5 | img_size: 224 6 | patch_size: 4 7 | num_classes: 1000 8 | expansion: 4 9 | dim_stem: 64 10 | dims: [64, 128, 256, 512] 11 | depths: [2, 4, 18, 2] 12 | stage_spec: [[N, D], [N, D, N, D], [N, D, N, D, N, D, N, D, N, D, N, D, N, D, N, D, N, D], [D, D]] 13 | heads: [2, 4, 8, 16] 14 | window_sizes: [7, 7, 7, 7] 15 | groups: [1, 2, 4, 8] 16 | use_pes: [True, True, True, True] 17 | dwc_pes: [False, False, False, False] 18 | strides: [8, 4, 2, 1] 19 | offset_range_factor: [-1, -1, -1, -1] 20 | no_offs: [False, False, False, False] 21 | fixed_pes: [False, False, False, False] 22 | use_dwc_mlps: [False, False, False, False] 23 | use_lpus: [False, False, False, False] 24 | use_conv_patches: False 25 | ksizes: [9, 7, 5, 3] 26 | nat_ksizes: [7, 7, 7, 7] 27 | drop_rate: 0.0 28 | attn_drop_rate: 0.0 29 | drop_path_rate: 0.2 30 | 31 | TRAIN: 32 | EPOCHS: 300 33 | WARMUP_EPOCHS: 20 34 | 35 | DATA: 36 | BATCH_SIZE: 128 37 | 38 | SAVE_FREQ: 1 -------------------------------------------------------------------------------- /configs/dat_small.yaml: -------------------------------------------------------------------------------- 1 | MODEL: 2 | TYPE: dat 3 | NAME: dat_plus_plus 4 | DAT: 5 | img_size: 224 6 | patch_size: 4 7 | num_classes: 1000 8 | expansion: 4 9 | dim_stem: 96 10 | dims: [96, 192, 384, 768] 11 | depths: [2, 4, 18, 2] 12 | stage_spec: [[N, D], [N, D, N, D], [N, D, N, D, N, D, N, D, N, D, N, D, N, D, N, D, N, D], [D, D]] 13 | heads: [3, 6, 12, 24] 14 | window_sizes: [7, 7, 7, 7] 15 | groups: [1, 2, 3, 6] 16 | use_pes: [True, True, True, True] 17 | dwc_pes: [False, False, False, False] 18 | strides: [8, 4, 2, 1] 19 | offset_range_factor: [-1, -1, -1, -1] 20 | no_offs: [False, False, False, False] 21 | fixed_pes: [False, False, False, False] 22 | use_dwc_mlps: [True, True, True, True] 23 | use_lpus: [True, True, True, True] 24 | use_conv_patches: True 25 | ksizes: [9, 7, 5, 3] 26 | nat_ksizes: [7, 7, 7, 7] 27 | drop_rate: 0.0 28 | attn_drop_rate: 0.0 29 | drop_path_rate: 0.4 30 | 31 | TRAIN: 32 | EPOCHS: 300 33 | WARMUP_EPOCHS: 20 34 | 35 | DATA: 36 | BATCH_SIZE: 128 37 | 38 | SAVE_FREQ: 1 -------------------------------------------------------------------------------- /configs/dat_tiny.yaml: -------------------------------------------------------------------------------- 1 | MODEL: 2 | TYPE: dat 3 | NAME: dat_plus_plus 4 | DAT: 5 | img_size: 224 6 | patch_size: 4 7 | num_classes: 1000 8 | expansion: 4 9 | dim_stem: 64 10 | dims: [64, 128, 256, 512] 11 | depths: [2, 4, 18, 2] 12 | stage_spec: [[N, D], [N, D, N, D], [N, D, N, D, N, D, N, D, N, D, N, D, N, D, N, D, N, D], [D, D]] 13 | heads: [2, 4, 8, 16] 14 | window_sizes: [7, 7, 7, 7] 15 | groups: [1, 2, 4, 8] 16 | use_pes: [True, True, True, True] 17 | dwc_pes: [False, False, False, False] 18 | strides: [8, 4, 2, 1] 19 | offset_range_factor: [-1, -1, -1, -1] 20 | no_offs: [False, False, False, False] 21 | fixed_pes: [False, False, False, False] 22 | use_dwc_mlps: [True, True, True, True] 23 | use_lpus: [True, True, True, True] 24 | use_conv_patches: True 25 | ksizes: [9, 7, 5, 3] 26 | nat_ksizes: [7, 7, 7, 7] 27 | drop_rate: 0.0 28 | attn_drop_rate: 0.0 29 | drop_path_rate: 0.2 30 | 31 | TRAIN: 32 | EPOCHS: 300 33 | WARMUP_EPOCHS: 20 34 | 35 | DATA: 36 | BATCH_SIZE: 128 37 | 38 | SAVE_FREQ: 1 -------------------------------------------------------------------------------- /data/__init__.py: -------------------------------------------------------------------------------- 1 | from .build import build_loader -------------------------------------------------------------------------------- /data/build.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import os 12 | import torch 13 | import numpy as np 14 | import torch.distributed as dist 15 | from torchvision import datasets, transforms 16 | from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD 17 | from timm.data import Mixup 18 | from timm.data import create_transform 19 | from .samplers import SubsetRandomSampler 20 | from torch.utils.data import DataLoader 21 | def build_loader(config): 22 | 23 | config.defrost() 24 | dataset_train, config.MODEL.NUM_CLASSES = build_dataset(is_train=True, config=config) 25 | config.freeze() 26 | 27 | dataset_val, _ = build_dataset(is_train=False, config=config) 28 | 29 | num_tasks = dist.get_world_size() 30 | global_rank = dist.get_rank() 31 | sampler_train = torch.utils.data.DistributedSampler( 32 | dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True 33 | ) 34 | indices = np.arange(dist.get_rank(), len(dataset_val), dist.get_world_size()) 35 | sampler_val = SubsetRandomSampler(indices) 36 | 37 | data_loader_train = DataLoader( 38 | dataset_train, sampler=sampler_train, 39 | batch_size=config.DATA.BATCH_SIZE, 40 | num_workers=config.DATA.NUM_WORKERS, 41 | pin_memory=config.DATA.PIN_MEMORY, 42 | drop_last=True 43 | ) 44 | 45 | data_loader_val = DataLoader( 46 | dataset_val, sampler=sampler_val, 47 | batch_size=config.DATA.BATCH_SIZE, 48 | shuffle=False, 49 | num_workers=config.DATA.NUM_WORKERS, 50 | pin_memory=config.DATA.PIN_MEMORY, 51 | drop_last=False 52 | ) 53 | 54 | # setup mixup / cutmix 55 | mixup_fn = None 56 | mixup_active = config.AUG.MIXUP > 0 or config.AUG.CUTMIX > 0. or config.AUG.CUTMIX_MINMAX is not None 57 | if mixup_active: 58 | mixup_fn = Mixup( 59 | mixup_alpha=config.AUG.MIXUP, cutmix_alpha=config.AUG.CUTMIX, cutmix_minmax=config.AUG.CUTMIX_MINMAX, 60 | prob=config.AUG.MIXUP_PROB, switch_prob=config.AUG.MIXUP_SWITCH_PROB, mode=config.AUG.MIXUP_MODE, 61 | label_smoothing=config.MODEL.LABEL_SMOOTHING, num_classes=config.MODEL.NUM_CLASSES) 62 | 63 | return dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn 64 | 65 | 66 | def build_dataset(is_train, config): 67 | transform = build_transform(is_train, config) 68 | if config.DATA.DATASET == 'imagenet': 69 | prefix = 'train' if is_train else 'val' 70 | root = os.path.join(config.DATA.DATA_PATH, prefix) 71 | dataset = datasets.ImageFolder(root, transform=transform) 72 | nb_classes = 1000 73 | else: 74 | raise NotImplementedError("We only support ImageNet Now.") 75 | 76 | return dataset, nb_classes 77 | 78 | 79 | def build_transform(is_train, config): 80 | resize_im = config.DATA.IMG_SIZE > 32 81 | if is_train: 82 | 83 | transform = create_transform( 84 | input_size=config.DATA.IMG_SIZE, 85 | is_training=True, 86 | color_jitter=config.AUG.COLOR_JITTER if config.AUG.COLOR_JITTER > 0 else None, 87 | auto_augment=config.AUG.AUTO_AUGMENT if config.AUG.AUTO_AUGMENT != 'none' else None, 88 | re_prob=config.AUG.REPROB, 89 | re_mode=config.AUG.REMODE, 90 | re_count=config.AUG.RECOUNT, 91 | interpolation=config.DATA.INTERPOLATION, 92 | ) 93 | if not resize_im: 94 | # replace RandomResizedCropAndInterpolation with 95 | # RandomCrop 96 | transform.transforms[0] = transforms.RandomCrop(config.DATA.IMG_SIZE, padding=4) 97 | return transform 98 | 99 | t = [] 100 | if resize_im: 101 | if config.TEST.CROP: 102 | size = int((256 / 224) * config.DATA.IMG_SIZE) 103 | t.append( 104 | transforms.Resize((size, size), interpolation=transforms.InterpolationMode.BICUBIC), 105 | # to maintain same ratio w.r.t. 224 images 106 | ) 107 | t.append(transforms.CenterCrop(config.DATA.IMG_SIZE)) 108 | else: 109 | t.append( 110 | transforms.Resize((config.DATA.IMG_SIZE, config.DATA.IMG_SIZE), 111 | interpolation=transforms.InterpolationMode.BICUBIC) 112 | ) 113 | 114 | t.append(transforms.ToTensor()) 115 | t.append(transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD)) 116 | return transforms.Compose(t) 117 | -------------------------------------------------------------------------------- /data/samplers.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import torch 12 | 13 | class SubsetRandomSampler(torch.utils.data.Sampler): 14 | r"""Samples elements randomly from a given list of indices, without replacement. 15 | 16 | Arguments: 17 | indices (sequence): a sequence of indices 18 | """ 19 | 20 | def __init__(self, indices): 21 | self.epoch = 0 22 | self.indices = indices 23 | 24 | def __iter__(self): 25 | return (self.indices[i] for i in torch.randperm(len(self.indices))) 26 | 27 | def __len__(self): 28 | return len(self.indices) 29 | 30 | def set_epoch(self, epoch): 31 | self.epoch = epoch 32 | -------------------------------------------------------------------------------- /evaluate.sh: -------------------------------------------------------------------------------- 1 | PORT=30001 2 | GPU=$1 3 | CFG=$2 4 | CKPT=$3 5 | 6 | torchrun --nproc_per_node $GPU --master_port $PORT main.py --cfg $CFG --data-path --eval --resume $CKPT -------------------------------------------------------------------------------- /figures/datt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeapLabTHU/DAT/32173fcf10d71abe73267f4e99829cd8624b7ab6/figures/datt.png -------------------------------------------------------------------------------- /figures/motivation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeapLabTHU/DAT/32173fcf10d71abe73267f4e99829cd8624b7ab6/figures/motivation.png -------------------------------------------------------------------------------- /figures/vis.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeapLabTHU/DAT/32173fcf10d71abe73267f4e99829cd8624b7ab6/figures/vis.png -------------------------------------------------------------------------------- /logger.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import os 12 | import sys 13 | import logging 14 | import functools 15 | from termcolor import colored 16 | 17 | @functools.lru_cache() 18 | def create_logger(output_dir, dist_rank=0, name=''): 19 | # create logger 20 | logger = logging.getLogger(name) 21 | logger.setLevel(logging.DEBUG) 22 | logger.propagate = False 23 | 24 | # create formatter 25 | fmt = '[%(asctime)s %(name)s] (%(filename)s %(lineno)d): %(levelname)s %(message)s' 26 | color_fmt = colored('[%(asctime)s %(name)s]', 'green') + \ 27 | colored('(%(filename)s %(lineno)d)', 'yellow') + ': %(levelname)s %(message)s' 28 | 29 | # create console handlers for master process 30 | if dist_rank == 0: 31 | console_handler = logging.StreamHandler(sys.stdout) 32 | console_handler.setLevel(logging.DEBUG) 33 | console_handler.setFormatter( 34 | logging.Formatter(fmt=color_fmt, datefmt='%Y-%m-%d %H:%M:%S')) 35 | logger.addHandler(console_handler) 36 | file_handler = logging.FileHandler(os.path.join(output_dir, f'log_rank{dist_rank}.txt'), mode='a') 37 | file_handler.setLevel(logging.DEBUG) 38 | file_handler.setFormatter(logging.Formatter(fmt=fmt, datefmt='%Y-%m-%d %H:%M:%S')) 39 | logger.addHandler(file_handler) 40 | 41 | return logger 42 | -------------------------------------------------------------------------------- /lr_scheduler.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import torch 12 | from timm.scheduler.cosine_lr import CosineLRScheduler 13 | from timm.scheduler.step_lr import StepLRScheduler 14 | from timm.scheduler.scheduler import Scheduler 15 | 16 | 17 | def build_scheduler(config, optimizer, n_iter_per_epoch): 18 | num_steps = int(config.TRAIN.EPOCHS * n_iter_per_epoch) 19 | warmup_steps = int(config.TRAIN.WARMUP_EPOCHS * n_iter_per_epoch) 20 | decay_steps = int(config.TRAIN.LR_SCHEDULER.DECAY_EPOCHS * n_iter_per_epoch) 21 | 22 | lr_scheduler = None 23 | if config.TRAIN.LR_SCHEDULER.NAME == 'cosine': 24 | lr_scheduler = CosineLRScheduler( 25 | optimizer, 26 | t_initial=num_steps, 27 | lr_min=config.TRAIN.MIN_LR, 28 | warmup_lr_init=config.TRAIN.WARMUP_LR, 29 | warmup_t=warmup_steps, 30 | cycle_limit=1, 31 | t_in_epochs=False, 32 | ) 33 | elif config.TRAIN.LR_SCHEDULER.NAME == 'linear': 34 | lr_scheduler = LinearLRScheduler( 35 | optimizer, 36 | t_initial=num_steps, 37 | lr_min_rate=0.01, 38 | warmup_lr_init=config.TRAIN.WARMUP_LR, 39 | warmup_t=warmup_steps, 40 | t_in_epochs=False, 41 | ) 42 | elif config.TRAIN.LR_SCHEDULER.NAME == 'step': 43 | lr_scheduler = StepLRScheduler( 44 | optimizer, 45 | decay_t=decay_steps, 46 | decay_rate=config.TRAIN.LR_SCHEDULER.DECAY_RATE, 47 | warmup_lr_init=config.TRAIN.WARMUP_LR, 48 | warmup_t=warmup_steps, 49 | t_in_epochs=False, 50 | ) 51 | 52 | return lr_scheduler 53 | 54 | 55 | class LinearLRScheduler(Scheduler): 56 | def __init__(self, 57 | optimizer: torch.optim.Optimizer, 58 | t_initial: int, 59 | lr_min_rate: float, 60 | warmup_t=0, 61 | warmup_lr_init=0., 62 | t_in_epochs=True, 63 | noise_range_t=None, 64 | noise_pct=0.67, 65 | noise_std=1.0, 66 | noise_seed=42, 67 | initialize=True, 68 | ) -> None: 69 | super().__init__( 70 | optimizer, param_group_field="lr", 71 | noise_range_t=noise_range_t, noise_pct=noise_pct, noise_std=noise_std, noise_seed=noise_seed, 72 | initialize=initialize) 73 | 74 | self.t_initial = t_initial 75 | self.lr_min_rate = lr_min_rate 76 | self.warmup_t = warmup_t 77 | self.warmup_lr_init = warmup_lr_init 78 | self.t_in_epochs = t_in_epochs 79 | if self.warmup_t: 80 | self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in self.base_values] 81 | super().update_groups(self.warmup_lr_init) 82 | else: 83 | self.warmup_steps = [1 for _ in self.base_values] 84 | 85 | def _get_lr(self, t): 86 | if t < self.warmup_t: 87 | lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps] 88 | else: 89 | t = t - self.warmup_t 90 | total_t = self.t_initial - self.warmup_t 91 | lrs = [v - ((v - v * self.lr_min_rate) * (t / total_t)) for v in self.base_values] 92 | return lrs 93 | 94 | def get_epoch_values(self, epoch: int): 95 | if self.t_in_epochs: 96 | return self._get_lr(epoch) 97 | else: 98 | return None 99 | 100 | def get_update_values(self, num_updates: int): 101 | if not self.t_in_epochs: 102 | return self._get_lr(num_updates) 103 | else: 104 | return None 105 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import os 12 | import time 13 | import argparse 14 | import datetime 15 | import numpy as np 16 | 17 | import torch 18 | import torch.nn as nn 19 | import torch.backends.cudnn as cudnn 20 | import torch.distributed as dist 21 | from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy 22 | from timm.utils import accuracy, AverageMeter 23 | 24 | from config import get_config 25 | from models import build_model 26 | from data import build_loader 27 | from lr_scheduler import build_scheduler 28 | from optimizer import build_optimizer 29 | from logger import create_logger 30 | from utils import load_checkpoint, load_pretrained, save_checkpoint, \ 31 | get_grad_norm, auto_resume_helper, reduce_tensor 32 | 33 | from torch.cuda.amp import GradScaler, autocast 34 | 35 | import warnings 36 | warnings.filterwarnings('ignore') 37 | 38 | 39 | def parse_option(): 40 | parser = argparse.ArgumentParser() 41 | parser.add_argument('--cfg', type=str, required=True, metavar="FILE", help='path to config file', ) 42 | parser.add_argument( 43 | "--opts", 44 | help="Modify config options by adding 'KEY VALUE' pairs. ", 45 | default=None, 46 | nargs='+', 47 | ) 48 | # easy config modification 49 | parser.add_argument('--batch-size', type=int, help="batch size for single GPU") 50 | parser.add_argument('--data-path', type=str, help='path to dataset') 51 | parser.add_argument('--resume', help='resume from checkpoint') 52 | parser.add_argument('--amp', action='store_true', default=False) 53 | parser.add_argument('--output', default='output', type=str, metavar='PATH', 54 | help='root of output folder, the full path is // (default: output)') 55 | parser.add_argument('--tag', help='tag of experiment') 56 | parser.add_argument('--eval', action='store_true', help='Perform evaluation only') 57 | parser.add_argument('--throughput', action='store_true', help='Test throughput only') 58 | parser.add_argument('--print-freq', type=int, help='Printing frequency.', default=100) 59 | 60 | args, unparsed = parser.parse_known_args() 61 | 62 | config = get_config(args) 63 | 64 | return args, config 65 | 66 | 67 | def main(): 68 | 69 | args, config = parse_option() 70 | local_rank = int(os.environ["LOCAL_RANK"]) 71 | rank = int(os.environ["RANK"]) 72 | world_size = int(os.environ['WORLD_SIZE']) 73 | dist.init_process_group(backend='nccl', init_method='env://', world_size=world_size, rank=rank) 74 | torch.cuda.set_device(local_rank) 75 | dist.barrier() 76 | 77 | seed = config.SEED + dist.get_rank() 78 | torch.manual_seed(seed) 79 | np.random.seed(seed) 80 | cudnn.enabled = True 81 | cudnn.benchmark = True 82 | 83 | if config.DATA.DATASET == 'imagenet': 84 | standard_bs = 512.0 85 | elif config.DATA.DATASET == 'imagenet22k': 86 | standard_bs = 4096.0 87 | else: 88 | raise RuntimeError("Wrong dataset!") 89 | 90 | # linear scale the learning rate according to total batch size, may not be optimal 91 | linear_scaled_lr = config.TRAIN.BASE_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / standard_bs 92 | linear_scaled_warmup_lr = config.TRAIN.WARMUP_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / standard_bs 93 | linear_scaled_min_lr = config.TRAIN.MIN_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / standard_bs 94 | config.defrost() 95 | config.TRAIN.BASE_LR = linear_scaled_lr 96 | config.TRAIN.WARMUP_LR = linear_scaled_warmup_lr 97 | config.TRAIN.MIN_LR = linear_scaled_min_lr 98 | config.LOCAL_RANK = local_rank 99 | config.freeze() 100 | 101 | os.makedirs(config.OUTPUT, exist_ok=True) 102 | logger = create_logger(output_dir=config.OUTPUT, dist_rank=dist.get_rank(), name=f"{config.MODEL.NAME}") 103 | 104 | if dist.get_rank() == 0: 105 | path = os.path.join(config.OUTPUT, "config.yaml") 106 | with open(path, "w") as f: 107 | f.write(config.dump()) 108 | logger.info(f"Full config saved to {path}") 109 | 110 | # print config 111 | logger.info(config.dump()) 112 | 113 | _, dataset_val, data_loader_train, data_loader_val, mixup_fn = build_loader(config) 114 | 115 | logger.info(f"Creating model:{config.MODEL.TYPE}/{config.MODEL.NAME}") 116 | model = build_model(config) 117 | model.cuda() 118 | model = nn.SyncBatchNorm.convert_sync_batchnorm(model) 119 | logger.info(str(model)) 120 | 121 | optimizer = build_optimizer(config, model) 122 | 123 | model = nn.parallel.DistributedDataParallel( 124 | model, device_ids=[local_rank], broadcast_buffers=True, 125 | find_unused_parameters=False) 126 | model_without_ddp = model.module 127 | 128 | lr_scheduler = build_scheduler(config, optimizer, len(data_loader_train)) 129 | 130 | if config.AUG.MIXUP > 0.: 131 | # smoothing is handled with mixup label transform 132 | criterion = SoftTargetCrossEntropy() 133 | elif config.MODEL.LABEL_SMOOTHING > 0.: 134 | criterion = LabelSmoothingCrossEntropy(smoothing=config.MODEL.LABEL_SMOOTHING) 135 | else: 136 | criterion = nn.CrossEntropyLoss() 137 | 138 | max_accuracy = 0.0 139 | 140 | if config.MODEL.PRETRAINED is not None: 141 | pretrained_ckpt_path = config.MODEL.PRETRAINED 142 | load_pretrained(pretrained_ckpt_path, model_without_ddp, logger) 143 | 144 | if config.TRAIN.AUTO_RESUME and config.MODEL.RESUME == '': 145 | resume_file = auto_resume_helper(config.OUTPUT) 146 | if resume_file: 147 | if config.MODEL.RESUME: 148 | logger.warning(f"auto-resume changing resume file from {config.MODEL.RESUME} to {resume_file}") 149 | config.defrost() 150 | config.MODEL.RESUME = resume_file 151 | config.freeze() 152 | logger.info(f'auto resuming from {resume_file}') 153 | else: 154 | logger.info(f'no checkpoint found in {config.OUTPUT}, ignoring auto resume') 155 | 156 | if config.MODEL.RESUME: 157 | max_accuracy = load_checkpoint(config, model_without_ddp, optimizer, lr_scheduler, logger) 158 | acc1, acc5, loss = validate(config, data_loader_val, model, logger) 159 | torch.cuda.empty_cache() 160 | logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") 161 | if config.EVAL_MODE: 162 | return 163 | 164 | if config.THROUGHPUT_MODE: 165 | throughput(data_loader_val, model, logger) 166 | return 167 | logger.info("Start training") 168 | start_time = time.time() 169 | for epoch in range(config.TRAIN.START_EPOCH, config.TRAIN.EPOCHS): 170 | data_loader_train.sampler.set_epoch(epoch) 171 | 172 | train_one_epoch(config, model, criterion, data_loader_train, optimizer, epoch, mixup_fn, lr_scheduler, logger) 173 | 174 | if dist.get_rank() == 0 and ((epoch + 1) % config.SAVE_FREQ == 0 or (epoch + 1) == (config.TRAIN.EPOCHS)): 175 | save_checkpoint(config, epoch + 1, model_without_ddp, max_accuracy, optimizer, lr_scheduler, logger) 176 | 177 | acc1, acc5, loss = validate(config, data_loader_val, model, logger) 178 | 179 | logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") 180 | max_accuracy = max(max_accuracy, acc1) 181 | logger.info(f'Max accuracy: {max_accuracy:.2f}%') 182 | 183 | total_time = time.time() - start_time 184 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 185 | logger.info('Training time {}'.format(total_time_str)) 186 | 187 | 188 | def train_one_epoch(config, model, criterion, data_loader, optimizer, epoch, mixup_fn, lr_scheduler, logger): 189 | model.train() 190 | optimizer.zero_grad() 191 | 192 | num_steps = len(data_loader) 193 | batch_time = AverageMeter() 194 | loss_meter = AverageMeter() 195 | norm_meter = AverageMeter() 196 | 197 | start = time.time() 198 | end = time.time() 199 | 200 | scaler = GradScaler() 201 | 202 | for idx, (samples, targets) in enumerate(data_loader): 203 | 204 | optimizer.zero_grad() 205 | samples = samples.cuda(non_blocking=True) 206 | targets = targets.cuda(non_blocking=True) 207 | 208 | if mixup_fn is not None: 209 | samples, targets = mixup_fn(samples, targets) 210 | 211 | if config.AMP: 212 | with autocast(): 213 | outputs, _, _ = model(samples) 214 | loss = criterion(outputs, targets) 215 | scaler.scale(loss).backward() 216 | if config.TRAIN.CLIP_GRAD: 217 | scaler.unscale_(optimizer) 218 | grad_norm = nn.utils.clip_grad_norm_(model.parameters(), config.TRAIN.CLIP_GRAD) 219 | scaler.step(optimizer) 220 | scaler.update() 221 | else: 222 | grad_norm = get_grad_norm(model.parameters()) 223 | scaler.step(optimizer) 224 | scaler.update() 225 | else: 226 | outputs, _, _ = model(samples) 227 | loss = criterion(outputs, targets) 228 | loss.backward() 229 | if config.TRAIN.CLIP_GRAD: 230 | grad_norm = nn.utils.clip_grad_norm_(model.parameters(), config.TRAIN.CLIP_GRAD) 231 | else: 232 | grad_norm = get_grad_norm(model.parameters()) 233 | optimizer.step() 234 | 235 | lr_scheduler.step_update(epoch * num_steps + idx) 236 | 237 | torch.cuda.synchronize() 238 | 239 | loss_meter.update(loss.item(), targets.size(0)) 240 | norm_meter.update(grad_norm) 241 | batch_time.update(time.time() - end) 242 | end = time.time() 243 | 244 | if (idx + 1) % config.PRINT_FREQ == 0: 245 | lr = optimizer.param_groups[0]['lr'] 246 | memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) 247 | etas = batch_time.avg * (num_steps - idx) 248 | logger.info( 249 | f'Train: [{epoch + 1}/{config.TRAIN.EPOCHS}][{idx + 1}/{num_steps}]\t' 250 | f'eta {datetime.timedelta(seconds=int(etas))} lr {lr:.6f}\t' 251 | f'time {batch_time.val:.4f} ({batch_time.avg:.4f})\t' 252 | f'loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' 253 | f'grad_norm {norm_meter.val:.4f} ({norm_meter.avg:.4f})\t' 254 | f'mem {memory_used:.0f}MB') 255 | epoch_time = time.time() - start 256 | logger.info(f"EPOCH {epoch + 1} training takes {datetime.timedelta(seconds=int(epoch_time))}") 257 | 258 | @torch.no_grad() 259 | def validate(config, data_loader, model, logger): 260 | criterion = nn.CrossEntropyLoss() 261 | model.eval() 262 | 263 | batch_time = AverageMeter() 264 | loss_meter = AverageMeter() 265 | acc1_meter = AverageMeter() 266 | acc5_meter = AverageMeter() 267 | 268 | end = time.time() 269 | for idx, (images, target) in enumerate(data_loader): 270 | images = images.cuda(non_blocking=True) 271 | target = target.cuda(non_blocking=True) 272 | 273 | # compute output 274 | output, _, _ = model(images) 275 | 276 | # measure accuracy and record loss 277 | loss = criterion(output, target) 278 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 279 | 280 | acc1 = reduce_tensor(acc1) 281 | acc5 = reduce_tensor(acc5) 282 | loss = reduce_tensor(loss) 283 | 284 | loss_meter.update(loss.item(), target.size(0)) 285 | acc1_meter.update(acc1.item(), target.size(0)) 286 | acc5_meter.update(acc5.item(), target.size(0)) 287 | 288 | # measure elapsed time 289 | batch_time.update(time.time() - end) 290 | end = time.time() 291 | 292 | if (idx + 1) % config.PRINT_FREQ == 0: 293 | memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) 294 | logger.info( 295 | f'Test: [{(idx + 1)}/{len(data_loader)}]\t' 296 | f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 297 | f'Loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' 298 | f'Acc@1 {acc1_meter.val:.3f} ({acc1_meter.avg:.3f})\t' 299 | f'Acc@5 {acc5_meter.val:.3f} ({acc5_meter.avg:.3f})\t' 300 | f'Mem {memory_used:.0f}MB') 301 | logger.info(f' * Acc@1 {acc1_meter.avg:.3f} Acc@5 {acc5_meter.avg:.3f}') 302 | return acc1_meter.avg, acc5_meter.avg, loss_meter.avg 303 | 304 | @torch.no_grad() 305 | def throughput(data_loader, model, logger): 306 | model.eval() 307 | 308 | for _, (images, _) in enumerate(data_loader): 309 | images = images.cuda(non_blocking=True) 310 | batch_size = images.shape[0] 311 | for i in range(50): 312 | model(images) 313 | torch.cuda.synchronize() 314 | logger.info(f"throughput averaged with 30 times") 315 | tic1 = time.time() 316 | for i in range(30): 317 | model(images) 318 | torch.cuda.synchronize() 319 | tic2 = time.time() 320 | logger.info(f"batch_size {batch_size} throughput {30 * batch_size / (tic2 - tic1)}") 321 | return 322 | 323 | if __name__ == '__main__': 324 | main() 325 | -------------------------------------------------------------------------------- /map_22kto1k.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeapLabTHU/DAT/32173fcf10d71abe73267f4e99829cd8624b7ab6/map_22kto1k.pth -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | from .build import build_model -------------------------------------------------------------------------------- /models/build.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | from .dat import DAT 12 | 13 | def build_model(config): 14 | 15 | model_type = config.MODEL.TYPE 16 | if model_type == 'dat': 17 | model = DAT(**config.MODEL.DAT) 18 | else: 19 | raise NotImplementedError(f"Unkown model: {model_type}") 20 | 21 | return model 22 | -------------------------------------------------------------------------------- /models/dat.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import math 12 | import torch 13 | import torch.nn as nn 14 | import torch.nn.functional as F 15 | 16 | from timm.models.layers import DropPath, to_2tuple 17 | 18 | from .slide import SlideAttention 19 | from .dat_blocks import * 20 | from .nat import NeighborhoodAttention2D 21 | from .qna import FusedKQnA 22 | 23 | 24 | class LayerScale(nn.Module): 25 | 26 | def __init__(self, 27 | dim: int, 28 | inplace: bool = False, 29 | init_values: float = 1e-5): 30 | super().__init__() 31 | self.inplace = inplace 32 | self.weight = nn.Parameter(torch.ones(dim) * init_values) 33 | 34 | def forward(self, x): 35 | if self.inplace: 36 | return x.mul_(self.weight.view(-1, 1, 1)) 37 | else: 38 | return x * self.weight.view(-1, 1, 1) 39 | 40 | class TransformerStage(nn.Module): 41 | 42 | def __init__(self, fmap_size, window_size, ns_per_pt, 43 | dim_in, dim_embed, depths, stage_spec, n_groups, 44 | use_pe, sr_ratio, 45 | heads, heads_q, stride, 46 | offset_range_factor, 47 | dwc_pe, no_off, fixed_pe, 48 | attn_drop, proj_drop, expansion, drop, drop_path_rate, 49 | use_dwc_mlp, ksize, nat_ksize, 50 | k_qna, nq_qna, qna_activation, 51 | layer_scale_value, use_lpu, log_cpb): 52 | 53 | super().__init__() 54 | fmap_size = to_2tuple(fmap_size) 55 | self.depths = depths 56 | hc = dim_embed // heads 57 | assert dim_embed == heads * hc 58 | self.proj = nn.Conv2d(dim_in, dim_embed, 1, 1, 0) if dim_in != dim_embed else nn.Identity() 59 | self.stage_spec = stage_spec 60 | self.use_lpu = use_lpu 61 | 62 | self.ln_cnvnxt = nn.ModuleDict( 63 | {str(d): LayerNormProxy(dim_embed) for d in range(depths) if stage_spec[d] == 'X'} 64 | ) 65 | self.layer_norms = nn.ModuleList( 66 | [LayerNormProxy(dim_embed) if stage_spec[d // 2] != 'X' else nn.Identity() for d in range(2 * depths)] 67 | ) 68 | 69 | mlp_fn = TransformerMLPWithConv if use_dwc_mlp else TransformerMLP 70 | 71 | self.mlps = nn.ModuleList( 72 | [ 73 | mlp_fn(dim_embed, expansion, drop) for _ in range(depths) 74 | ] 75 | ) 76 | self.attns = nn.ModuleList() 77 | self.drop_path = nn.ModuleList() 78 | self.layer_scales = nn.ModuleList( 79 | [ 80 | LayerScale(dim_embed, init_values=layer_scale_value) if layer_scale_value > 0.0 else nn.Identity() 81 | for _ in range(2 * depths) 82 | ] 83 | ) 84 | self.local_perception_units = nn.ModuleList( 85 | [ 86 | nn.Conv2d(dim_embed, dim_embed, kernel_size=3, stride=1, padding=1, groups=dim_embed) if use_lpu else nn.Identity() 87 | for _ in range(depths) 88 | ] 89 | ) 90 | 91 | for i in range(depths): 92 | if stage_spec[i] == 'L': 93 | self.attns.append( 94 | LocalAttention(dim_embed, heads, window_size, attn_drop, proj_drop) 95 | ) 96 | elif stage_spec[i] == 'D': 97 | self.attns.append( 98 | DAttentionBaseline(fmap_size, fmap_size, heads, 99 | hc, n_groups, attn_drop, proj_drop, 100 | stride, offset_range_factor, use_pe, dwc_pe, 101 | no_off, fixed_pe, ksize, log_cpb) 102 | ) 103 | elif stage_spec[i] == 'S': 104 | shift_size = math.ceil(window_size / 2) 105 | self.attns.append( 106 | ShiftWindowAttention(dim_embed, heads, window_size, attn_drop, proj_drop, shift_size, fmap_size) 107 | ) 108 | elif stage_spec[i] == 'N': 109 | self.attns.append( 110 | NeighborhoodAttention2D(dim_embed, nat_ksize, heads, attn_drop, proj_drop) 111 | ) 112 | elif stage_spec[i] == 'P': 113 | self.attns.append( 114 | PyramidAttention(dim_embed, heads, attn_drop, proj_drop, sr_ratio) 115 | ) 116 | elif stage_spec[i] == 'Q': 117 | self.attns.append( 118 | FusedKQnA(nq_qna, dim_embed, heads_q, k_qna, 1, 0, qna_activation) 119 | ) 120 | elif self.stage_spec[i] == 'X': 121 | self.attns.append( 122 | nn.Conv2d(dim_embed, dim_embed, kernel_size=window_size, padding=window_size // 2, groups=dim_embed) 123 | ) 124 | elif self.stage_spec[i] == 'E': 125 | self.attns.append( 126 | SlideAttention(dim_embed, heads, 3) 127 | ) 128 | else: 129 | raise NotImplementedError(f'Spec: {stage_spec[i]} is not supported.') 130 | 131 | self.drop_path.append(DropPath(drop_path_rate[i]) if drop_path_rate[i] > 0.0 else nn.Identity()) 132 | 133 | def forward(self, x): 134 | 135 | x = self.proj(x) 136 | 137 | for d in range(self.depths): 138 | 139 | if self.use_lpu: 140 | x0 = x 141 | x = self.local_perception_units[d](x.contiguous()) 142 | x = x + x0 143 | 144 | if self.stage_spec[d] == 'X': 145 | x0 = x 146 | x = self.attns[d](x) 147 | x = self.mlps[d](self.ln_cnvnxt[str(d)](x)) 148 | x = self.drop_path[d](x) + x0 149 | else: 150 | x0 = x 151 | x, pos, ref = self.attns[d](self.layer_norms[2 * d](x)) 152 | x = self.layer_scales[2 * d](x) 153 | x = self.drop_path[d](x) + x0 154 | x0 = x 155 | x = self.mlps[d](self.layer_norms[2 * d + 1](x)) 156 | x = self.layer_scales[2 * d + 1](x) 157 | x = self.drop_path[d](x) + x0 158 | 159 | return x 160 | 161 | 162 | class DAT(nn.Module): 163 | 164 | def __init__(self, img_size=224, patch_size=4, num_classes=1000, expansion=4, 165 | dim_stem=96, dims=[96, 192, 384, 768], depths=[2, 2, 6, 2], 166 | heads=[3, 6, 12, 24], heads_q=[6, 12, 24, 48], 167 | window_sizes=[7, 7, 7, 7], 168 | drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, 169 | strides=[-1,-1,-1,-1], 170 | offset_range_factor=[1, 2, 3, 4], 171 | stage_spec=[['L', 'D'], ['L', 'D'], ['L', 'D', 'L', 'D', 'L', 'D'], ['L', 'D']], 172 | groups=[-1, -1, 3, 6], 173 | use_pes=[False, False, False, False], 174 | dwc_pes=[False, False, False, False], 175 | sr_ratios=[8, 4, 2, 1], 176 | lower_lr_kvs={}, 177 | fixed_pes=[False, False, False, False], 178 | no_offs=[False, False, False, False], 179 | ns_per_pts=[4, 4, 4, 4], 180 | use_dwc_mlps=[False, False, False, False], 181 | use_conv_patches=False, 182 | ksizes=[9, 7, 5, 3], 183 | ksize_qnas=[3, 3, 3, 3], 184 | nqs=[2, 2, 2, 2], 185 | qna_activation='exp', 186 | nat_ksizes=[3,3,3,3], 187 | layer_scale_values=[-1,-1,-1,-1], 188 | use_lpus=[False, False, False, False], 189 | log_cpb=[False, False, False, False], 190 | **kwargs): 191 | super().__init__() 192 | 193 | self.patch_proj = nn.Sequential( 194 | nn.Conv2d(3, dim_stem // 2, 3, patch_size // 2, 1), 195 | LayerNormProxy(dim_stem // 2), 196 | nn.GELU(), 197 | nn.Conv2d(dim_stem // 2, dim_stem, 3, patch_size // 2, 1), 198 | LayerNormProxy(dim_stem) 199 | ) if use_conv_patches else nn.Sequential( 200 | nn.Conv2d(3, dim_stem, patch_size, patch_size, 0), 201 | LayerNormProxy(dim_stem) 202 | ) 203 | 204 | img_size = img_size // patch_size 205 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] 206 | 207 | self.stages = nn.ModuleList() 208 | for i in range(4): 209 | dim1 = dim_stem if i == 0 else dims[i - 1] * 2 210 | dim2 = dims[i] 211 | self.stages.append( 212 | TransformerStage( 213 | img_size, window_sizes[i], ns_per_pts[i], 214 | dim1, dim2, depths[i], 215 | stage_spec[i], groups[i], use_pes[i], 216 | sr_ratios[i], heads[i], heads_q[i], strides[i], 217 | offset_range_factor[i], 218 | dwc_pes[i], no_offs[i], fixed_pes[i], 219 | attn_drop_rate, drop_rate, expansion, drop_rate, 220 | dpr[sum(depths[:i]):sum(depths[:i + 1])], use_dwc_mlps[i], 221 | ksizes[i], nat_ksizes[i], ksize_qnas[i], nqs[i],qna_activation, 222 | layer_scale_values[i], use_lpus[i], log_cpb[i] 223 | ) 224 | ) 225 | img_size = img_size // 2 226 | 227 | self.down_projs = nn.ModuleList() 228 | for i in range(3): 229 | self.down_projs.append( 230 | nn.Sequential( 231 | nn.Conv2d(dims[i], dims[i + 1], 3, 2, 1, bias=False), 232 | LayerNormProxy(dims[i + 1]) 233 | ) if use_conv_patches else nn.Sequential( 234 | nn.Conv2d(dims[i], dims[i + 1], 2, 2, 0, bias=False), 235 | LayerNormProxy(dims[i + 1]) 236 | ) 237 | ) 238 | 239 | self.cls_norm = LayerNormProxy(dims[-1]) 240 | self.cls_head = nn.Linear(dims[-1], num_classes) 241 | 242 | self.lower_lr_kvs = lower_lr_kvs 243 | 244 | self.reset_parameters() 245 | 246 | def reset_parameters(self): 247 | 248 | for m in self.parameters(): 249 | if isinstance(m, (nn.Linear, nn.Conv2d)): 250 | nn.init.kaiming_normal_(m.weight) 251 | nn.init.zeros_(m.bias) 252 | 253 | @torch.no_grad() 254 | def load_pretrained(self, state_dict, lookup_22k): 255 | 256 | new_state_dict = {} 257 | for state_key, state_value in state_dict.items(): 258 | keys = state_key.split('.') 259 | m = self 260 | for key in keys: 261 | if key.isdigit(): 262 | m = m[int(key)] 263 | else: 264 | m = getattr(m, key) 265 | if m.shape == state_value.shape: 266 | new_state_dict[state_key] = state_value 267 | else: 268 | # Ignore different shapes 269 | if 'relative_position_index' in keys: 270 | new_state_dict[state_key] = m.data 271 | if 'q_grid' in keys: 272 | new_state_dict[state_key] = m.data 273 | if 'reference' in keys: 274 | new_state_dict[state_key] = m.data 275 | # Bicubic Interpolation 276 | if 'relative_position_bias_table' in keys: 277 | n, c = state_value.size() 278 | l_side = int(math.sqrt(n)) 279 | assert n == l_side ** 2 280 | L = int(math.sqrt(m.shape[0])) 281 | pre_interp = state_value.reshape(1, l_side, l_side, c).permute(0, 3, 1, 2) 282 | post_interp = F.interpolate(pre_interp, (L, L), mode='bicubic') 283 | new_state_dict[state_key] = post_interp.reshape(c, L ** 2).permute(1, 0) 284 | if 'rpe_table' in keys: 285 | c, h, w = state_value.size() 286 | C, H, W = m.data.size() 287 | pre_interp = state_value.unsqueeze(0) 288 | post_interp = F.interpolate(pre_interp, (H, W), mode='bicubic') 289 | new_state_dict[state_key] = post_interp.squeeze(0) 290 | if 'cls_head' in keys: 291 | new_state_dict[state_key] = state_value[lookup_22k] 292 | 293 | msg = self.load_state_dict(new_state_dict, strict=False) 294 | return msg 295 | 296 | @torch.jit.ignore 297 | def no_weight_decay(self): 298 | return {'absolute_pos_embed'} 299 | 300 | @torch.jit.ignore 301 | def no_weight_decay_keywords(self): 302 | return {'relative_position_bias_table', 'rpe_table'} 303 | 304 | def forward(self, x): 305 | x = self.patch_proj(x) 306 | for i in range(4): 307 | x = self.stages[i](x) 308 | if i < 3: 309 | x = self.down_projs[i](x) 310 | x = self.cls_norm(x) 311 | x = F.adaptive_avg_pool2d(x, 1) 312 | x = torch.flatten(x, 1) 313 | x = self.cls_head(x) 314 | return x, None, None 315 | -------------------------------------------------------------------------------- /models/dat_blocks.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import math 12 | import numpy as np 13 | import torch 14 | import torch.nn as nn 15 | import torch.nn.functional as F 16 | import einops 17 | from timm.models.layers import to_2tuple, trunc_normal_ 18 | 19 | class LocalAttention(nn.Module): 20 | 21 | def __init__(self, dim, heads, window_size, attn_drop, proj_drop): 22 | 23 | super().__init__() 24 | 25 | window_size = to_2tuple(window_size) 26 | 27 | self.proj_qkv = nn.Linear(dim, 3 * dim) 28 | self.heads = heads 29 | assert dim % heads == 0 30 | head_dim = dim // heads 31 | self.scale = head_dim ** -0.5 32 | self.proj_out = nn.Linear(dim, dim) 33 | self.window_size = window_size 34 | self.proj_drop = nn.Dropout(proj_drop, inplace=True) 35 | self.attn_drop = nn.Dropout(attn_drop, inplace=True) 36 | 37 | Wh, Ww = self.window_size 38 | self.relative_position_bias_table = nn.Parameter( 39 | torch.zeros((2 * Wh - 1) * (2 * Ww - 1), heads) 40 | ) 41 | trunc_normal_(self.relative_position_bias_table, std=0.01) 42 | 43 | coords_h = torch.arange(self.window_size[0]) 44 | coords_w = torch.arange(self.window_size[1]) 45 | coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww 46 | coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww 47 | relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww 48 | relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 49 | relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 50 | relative_coords[:, :, 1] += self.window_size[1] - 1 51 | relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 52 | relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww 53 | self.register_buffer("relative_position_index", relative_position_index) 54 | 55 | def forward(self, x, mask=None): 56 | 57 | B, C, H, W = x.size() 58 | r1, r2 = H // self.window_size[0], W // self.window_size[1] 59 | 60 | x_total = einops.rearrange(x, 'b c (r1 h1) (r2 w1) -> b (r1 r2) (h1 w1) c', h1=self.window_size[0], w1=self.window_size[1]) # B x Nr x Ws x C 61 | 62 | x_total = einops.rearrange(x_total, 'b m n c -> (b m) n c') 63 | 64 | qkv = self.proj_qkv(x_total) # B' x N x 3C 65 | q, k, v = torch.chunk(qkv, 3, dim=2) 66 | 67 | q = q * self.scale 68 | q, k, v = [einops.rearrange(t, 'b n (h c1) -> b h n c1', h=self.heads) for t in [q, k, v]] 69 | attn = torch.einsum('b h m c, b h n c -> b h m n', q, k) 70 | 71 | relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( 72 | self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH 73 | relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww 74 | attn_bias = relative_position_bias 75 | attn = attn + attn_bias.unsqueeze(0) 76 | 77 | if mask is not None: 78 | # attn : (b * nW) h w w 79 | # mask : nW ww ww 80 | nW, ww, _ = mask.size() 81 | attn = einops.rearrange(attn, '(b n) h w1 w2 -> b n h w1 w2', n=nW, h=self.heads, w1=ww, w2=ww) + mask.reshape(1, nW, 1, ww, ww) 82 | attn = einops.rearrange(attn, 'b n h w1 w2 -> (b n) h w1 w2') 83 | attn = self.attn_drop(attn.softmax(dim=3)) 84 | 85 | x = torch.einsum('b h m n, b h n c -> b h m c', attn, v) 86 | x = einops.rearrange(x, 'b h n c1 -> b n (h c1)') 87 | x = self.proj_drop(self.proj_out(x)) # B' x N x C 88 | x = einops.rearrange(x, '(b r1 r2) (h1 w1) c -> b c (r1 h1) (r2 w1)', r1=r1, r2=r2, h1=self.window_size[0], w1=self.window_size[1]) # B x C x H x W 89 | 90 | return x, None, None 91 | 92 | 93 | class ShiftWindowAttention(LocalAttention): 94 | 95 | def __init__(self, dim, heads, window_size, attn_drop, proj_drop, shift_size, fmap_size): 96 | 97 | super().__init__(dim, heads, window_size, attn_drop, proj_drop) 98 | 99 | self.fmap_size = to_2tuple(fmap_size) 100 | self.shift_size = shift_size 101 | 102 | assert 0 < self.shift_size < min(self.window_size), "wrong shift size." 103 | 104 | img_mask = torch.zeros(*self.fmap_size) # H W 105 | h_slices = (slice(0, -self.window_size[0]), 106 | slice(-self.window_size[0], -self.shift_size), 107 | slice(-self.shift_size, None)) 108 | w_slices = (slice(0, -self.window_size[1]), 109 | slice(-self.window_size[1], -self.shift_size), 110 | slice(-self.shift_size, None)) 111 | cnt = 0 112 | for h in h_slices: 113 | for w in w_slices: 114 | img_mask[h, w] = cnt 115 | cnt += 1 116 | mask_windows = einops.rearrange(img_mask, '(r1 h1) (r2 w1) -> (r1 r2) (h1 w1)', h1=self.window_size[0],w1=self.window_size[1]) 117 | attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) # nW ww ww 118 | attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) 119 | self.register_buffer("attn_mask", attn_mask) 120 | 121 | def forward(self, x): 122 | 123 | shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(2, 3)) 124 | sw_x, _, _ = super().forward(shifted_x, self.attn_mask) 125 | x = torch.roll(sw_x, shifts=(self.shift_size, self.shift_size), dims=(2, 3)) 126 | 127 | return x, None, None 128 | 129 | 130 | class DAttentionBaseline(nn.Module): 131 | 132 | def __init__( 133 | self, q_size, kv_size, n_heads, n_head_channels, n_groups, 134 | attn_drop, proj_drop, stride, 135 | offset_range_factor, use_pe, dwc_pe, 136 | no_off, fixed_pe, ksize, log_cpb 137 | ): 138 | 139 | super().__init__() 140 | self.dwc_pe = dwc_pe 141 | self.n_head_channels = n_head_channels 142 | self.scale = self.n_head_channels ** -0.5 143 | self.n_heads = n_heads 144 | self.q_h, self.q_w = q_size 145 | # self.kv_h, self.kv_w = kv_size 146 | self.kv_h, self.kv_w = self.q_h // stride, self.q_w // stride 147 | self.nc = n_head_channels * n_heads 148 | self.n_groups = n_groups 149 | self.n_group_channels = self.nc // self.n_groups 150 | self.n_group_heads = self.n_heads // self.n_groups 151 | self.use_pe = use_pe 152 | self.fixed_pe = fixed_pe 153 | self.no_off = no_off 154 | self.offset_range_factor = offset_range_factor 155 | self.ksize = ksize 156 | self.log_cpb = log_cpb 157 | self.stride = stride 158 | kk = self.ksize 159 | pad_size = kk // 2 if kk != stride else 0 160 | 161 | self.conv_offset = nn.Sequential( 162 | nn.Conv2d(self.n_group_channels, self.n_group_channels, kk, stride, pad_size, groups=self.n_group_channels), 163 | LayerNormProxy(self.n_group_channels), 164 | nn.GELU(), 165 | nn.Conv2d(self.n_group_channels, 2, 1, 1, 0, bias=False) 166 | ) 167 | if self.no_off: 168 | for m in self.conv_offset.parameters(): 169 | m.requires_grad_(False) 170 | 171 | self.proj_q = nn.Conv2d( 172 | self.nc, self.nc, 173 | kernel_size=1, stride=1, padding=0 174 | ) 175 | 176 | self.proj_k = nn.Conv2d( 177 | self.nc, self.nc, 178 | kernel_size=1, stride=1, padding=0 179 | ) 180 | 181 | self.proj_v = nn.Conv2d( 182 | self.nc, self.nc, 183 | kernel_size=1, stride=1, padding=0 184 | ) 185 | 186 | self.proj_out = nn.Conv2d( 187 | self.nc, self.nc, 188 | kernel_size=1, stride=1, padding=0 189 | ) 190 | 191 | self.proj_drop = nn.Dropout(proj_drop, inplace=True) 192 | self.attn_drop = nn.Dropout(attn_drop, inplace=True) 193 | 194 | if self.use_pe and not self.no_off: 195 | if self.dwc_pe: 196 | self.rpe_table = nn.Conv2d( 197 | self.nc, self.nc, kernel_size=3, stride=1, padding=1, groups=self.nc) 198 | elif self.fixed_pe: 199 | self.rpe_table = nn.Parameter( 200 | torch.zeros(self.n_heads, self.q_h * self.q_w, self.kv_h * self.kv_w) 201 | ) 202 | trunc_normal_(self.rpe_table, std=0.01) 203 | elif self.log_cpb: 204 | # Borrowed from Swin-V2 205 | self.rpe_table = nn.Sequential( 206 | nn.Linear(2, 32, bias=True), 207 | nn.ReLU(inplace=True), 208 | nn.Linear(32, self.n_group_heads, bias=False) 209 | ) 210 | else: 211 | self.rpe_table = nn.Parameter( 212 | torch.zeros(self.n_heads, self.q_h * 2 - 1, self.q_w * 2 - 1) 213 | ) 214 | trunc_normal_(self.rpe_table, std=0.01) 215 | else: 216 | self.rpe_table = None 217 | 218 | @torch.no_grad() 219 | def _get_ref_points(self, H_key, W_key, B, dtype, device): 220 | 221 | ref_y, ref_x = torch.meshgrid( 222 | torch.linspace(0.5, H_key - 0.5, H_key, dtype=dtype, device=device), 223 | torch.linspace(0.5, W_key - 0.5, W_key, dtype=dtype, device=device), 224 | indexing='ij' 225 | ) 226 | ref = torch.stack((ref_y, ref_x), -1) 227 | ref[..., 1].div_(W_key - 1.0).mul_(2.0).sub_(1.0) 228 | ref[..., 0].div_(H_key - 1.0).mul_(2.0).sub_(1.0) 229 | ref = ref[None, ...].expand(B * self.n_groups, -1, -1, -1) # B * g H W 2 230 | 231 | return ref 232 | 233 | @torch.no_grad() 234 | def _get_q_grid(self, H, W, B, dtype, device): 235 | 236 | ref_y, ref_x = torch.meshgrid( 237 | torch.arange(0, H, dtype=dtype, device=device), 238 | torch.arange(0, W, dtype=dtype, device=device), 239 | indexing='ij' 240 | ) 241 | ref = torch.stack((ref_y, ref_x), -1) 242 | ref[..., 1].div_(W - 1.0).mul_(2.0).sub_(1.0) 243 | ref[..., 0].div_(H - 1.0).mul_(2.0).sub_(1.0) 244 | ref = ref[None, ...].expand(B * self.n_groups, -1, -1, -1) # B * g H W 2 245 | 246 | return ref 247 | 248 | def forward(self, x): 249 | 250 | B, C, H, W = x.size() 251 | dtype, device = x.dtype, x.device 252 | 253 | q = self.proj_q(x) 254 | q_off = einops.rearrange(q, 'b (g c) h w -> (b g) c h w', g=self.n_groups, c=self.n_group_channels) 255 | offset = self.conv_offset(q_off).contiguous() # B * g 2 Hg Wg 256 | Hk, Wk = offset.size(2), offset.size(3) 257 | n_sample = Hk * Wk 258 | 259 | if self.offset_range_factor >= 0 and not self.no_off: 260 | offset_range = torch.tensor([1.0 / (Hk - 1.0), 1.0 / (Wk - 1.0)], device=device).reshape(1, 2, 1, 1) 261 | offset = offset.tanh().mul(offset_range).mul(self.offset_range_factor) 262 | 263 | offset = einops.rearrange(offset, 'b p h w -> b h w p') 264 | reference = self._get_ref_points(Hk, Wk, B, dtype, device) 265 | 266 | if self.no_off: 267 | offset = offset.fill_(0.0) 268 | 269 | if self.offset_range_factor >= 0: 270 | pos = offset + reference 271 | else: 272 | pos = (offset + reference).clamp(-1., +1.) 273 | 274 | if self.no_off: 275 | x_sampled = F.avg_pool2d(x, kernel_size=self.stride, stride=self.stride) 276 | assert x_sampled.size(2) == Hk and x_sampled.size(3) == Wk, f"Size is {x_sampled.size()}" 277 | else: 278 | x_sampled = F.grid_sample( 279 | input=x.reshape(B * self.n_groups, self.n_group_channels, H, W), 280 | grid=pos[..., (1, 0)], # y, x -> x, y 281 | mode='bilinear', align_corners=True) # B * g, Cg, Hg, Wg 282 | 283 | 284 | x_sampled = x_sampled.reshape(B, C, 1, n_sample) 285 | 286 | q = q.reshape(B * self.n_heads, self.n_head_channels, H * W) 287 | k = self.proj_k(x_sampled).reshape(B * self.n_heads, self.n_head_channels, n_sample) 288 | v = self.proj_v(x_sampled).reshape(B * self.n_heads, self.n_head_channels, n_sample) 289 | 290 | attn = torch.einsum('b c m, b c n -> b m n', q, k) # B * h, HW, Ns 291 | attn = attn.mul(self.scale) 292 | 293 | if self.use_pe and (not self.no_off): 294 | 295 | if self.dwc_pe: 296 | residual_lepe = self.rpe_table(q.reshape(B, C, H, W)).reshape(B * self.n_heads, self.n_head_channels, H * W) 297 | elif self.fixed_pe: 298 | rpe_table = self.rpe_table 299 | attn_bias = rpe_table[None, ...].expand(B, -1, -1, -1) 300 | attn = attn + attn_bias.reshape(B * self.n_heads, H * W, n_sample) 301 | elif self.log_cpb: 302 | q_grid = self._get_q_grid(H, W, B, dtype, device) 303 | displacement = (q_grid.reshape(B * self.n_groups, H * W, 2).unsqueeze(2) - pos.reshape(B * self.n_groups, n_sample, 2).unsqueeze(1)).mul(4.0) # d_y, d_x [-8, +8] 304 | displacement = torch.sign(displacement) * torch.log2(torch.abs(displacement) + 1.0) / np.log2(8.0) 305 | attn_bias = self.rpe_table(displacement) # B * g, H * W, n_sample, h_g 306 | attn = attn + einops.rearrange(attn_bias, 'b m n h -> (b h) m n', h=self.n_group_heads) 307 | else: 308 | rpe_table = self.rpe_table 309 | rpe_bias = rpe_table[None, ...].expand(B, -1, -1, -1) 310 | q_grid = self._get_q_grid(H, W, B, dtype, device) 311 | displacement = (q_grid.reshape(B * self.n_groups, H * W, 2).unsqueeze(2) - pos.reshape(B * self.n_groups, n_sample, 2).unsqueeze(1)).mul(0.5) 312 | attn_bias = F.grid_sample( 313 | input=einops.rearrange(rpe_bias, 'b (g c) h w -> (b g) c h w', c=self.n_group_heads, g=self.n_groups), 314 | grid=displacement[..., (1, 0)], 315 | mode='bilinear', align_corners=True) # B * g, h_g, HW, Ns 316 | 317 | attn_bias = attn_bias.reshape(B * self.n_heads, H * W, n_sample) 318 | attn = attn + attn_bias 319 | 320 | attn = F.softmax(attn, dim=2) 321 | attn = self.attn_drop(attn) 322 | 323 | out = torch.einsum('b m n, b c n -> b c m', attn, v) 324 | 325 | if self.use_pe and self.dwc_pe: 326 | out = out + residual_lepe 327 | out = out.reshape(B, C, H, W) 328 | 329 | y = self.proj_drop(self.proj_out(out)) 330 | 331 | return y, pos.reshape(B, self.n_groups, Hk, Wk, 2), reference.reshape(B, self.n_groups, Hk, Wk, 2) 332 | 333 | 334 | class PyramidAttention(nn.Module): 335 | 336 | def __init__(self, dim, num_heads=8, attn_drop=0., proj_drop=0., sr_ratio=1): 337 | 338 | super().__init__() 339 | 340 | assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}." 341 | 342 | self.dim = dim 343 | self.num_heads = num_heads 344 | self.head_dim = dim // num_heads 345 | self.scale = self.head_dim ** -0.5 346 | 347 | self.q = nn.Conv2d(dim, dim, 1, 1, 0) 348 | self.kv = nn.Conv2d(dim, dim * 2, 1, 1, 0) 349 | self.attn_drop = nn.Dropout(attn_drop) 350 | self.proj = nn.Conv2d(dim, dim, 1, 1, 0) 351 | self.proj_drop = nn.Dropout(proj_drop) 352 | 353 | self.sr_ratio = sr_ratio 354 | if sr_ratio > 1: 355 | self.proj_ds = nn.Sequential( 356 | nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio), 357 | LayerNormProxy(dim) 358 | ) 359 | 360 | 361 | def forward(self, x): 362 | 363 | B, C, H, W = x.size() 364 | Nq = H * W 365 | q = self.q(x) 366 | 367 | if self.sr_ratio > 1: 368 | x_ds = self.proj_ds(x) 369 | kv = self.kv(x_ds) 370 | else: 371 | kv = self.kv(x) 372 | 373 | k, v = torch.chunk(kv, 2, dim=1) 374 | Nk = (H // self.sr_ratio) * (W // self.sr_ratio) 375 | q = q.reshape(B * self.num_heads, self.head_dim, Nq).mul(self.scale) 376 | k = k.reshape(B * self.num_heads, self.head_dim, Nk) 377 | v = v.reshape(B * self.num_heads, self.head_dim, Nk) 378 | attn = torch.einsum('b c m, b c n -> b m n', q, k) 379 | attn = F.softmax(attn, dim=2) 380 | attn = self.attn_drop(attn) 381 | 382 | x = torch.einsum('b m n, b c n -> b c m', attn, v) 383 | x = x.reshape(B, C, H, W) 384 | x = self.proj(x) 385 | x = self.proj_drop(x) 386 | 387 | return x, None, None 388 | 389 | 390 | class TransformerMLP(nn.Module): 391 | 392 | def __init__(self, channels, expansion, drop): 393 | 394 | super().__init__() 395 | 396 | self.dim1 = channels 397 | self.dim2 = channels * expansion 398 | self.chunk = nn.Sequential() 399 | self.chunk.add_module('linear1', nn.Linear(self.dim1, self.dim2)) 400 | self.chunk.add_module('act', nn.GELU()) 401 | self.chunk.add_module('drop1', nn.Dropout(drop, inplace=True)) 402 | self.chunk.add_module('linear2', nn.Linear(self.dim2, self.dim1)) 403 | self.chunk.add_module('drop2', nn.Dropout(drop, inplace=True)) 404 | 405 | def forward(self, x): 406 | 407 | _, _, H, W = x.size() 408 | x = einops.rearrange(x, 'b c h w -> b (h w) c') 409 | x = self.chunk(x) 410 | x = einops.rearrange(x, 'b (h w) c -> b c h w', h=H, w=W) 411 | return x 412 | 413 | class LayerNormProxy(nn.Module): 414 | 415 | def __init__(self, dim): 416 | 417 | super().__init__() 418 | self.norm = nn.LayerNorm(dim) 419 | 420 | def forward(self, x): 421 | 422 | x = einops.rearrange(x, 'b c h w -> b h w c') 423 | x = self.norm(x) 424 | return einops.rearrange(x, 'b h w c -> b c h w') 425 | 426 | 427 | class TransformerMLPWithConv(nn.Module): 428 | 429 | def __init__(self, channels, expansion, drop): 430 | 431 | super().__init__() 432 | 433 | self.dim1 = channels 434 | self.dim2 = channels * expansion 435 | self.linear1 = nn.Sequential( 436 | nn.Conv2d(self.dim1, self.dim2, 1, 1, 0), 437 | # nn.GELU(), 438 | # nn.BatchNorm2d(self.dim2, eps=1e-5) 439 | ) 440 | self.drop1 = nn.Dropout(drop, inplace=True) 441 | self.act = nn.GELU() 442 | # self.bn = nn.BatchNorm2d(self.dim2, eps=1e-5) 443 | self.linear2 = nn.Sequential( 444 | nn.Conv2d(self.dim2, self.dim1, 1, 1, 0), 445 | # nn.BatchNorm2d(self.dim1, eps=1e-5) 446 | ) 447 | self.drop2 = nn.Dropout(drop, inplace=True) 448 | self.dwc = nn.Conv2d(self.dim2, self.dim2, 3, 1, 1, groups=self.dim2) 449 | 450 | def forward(self, x): 451 | 452 | x = self.linear1(x) 453 | x = self.drop1(x) 454 | x = x + self.dwc(x) 455 | x = self.act(x) 456 | # x = self.bn(x) 457 | x = self.linear2(x) 458 | x = self.drop2(x) 459 | 460 | return x -------------------------------------------------------------------------------- /models/nat.py: -------------------------------------------------------------------------------- 1 | ################################################################################################# 2 | # Copyright (c) 2023 Ali Hassani. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy 5 | # of this software and associated documentation files (the "Software"), to deal 6 | # in the Software without restriction, including without limitation the rights 7 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | # copies of the Software, and to permit persons to whom the Software is 9 | # furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in all 12 | # copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | # SOFTWARE. 21 | # 22 | ################################################################################################# 23 | # -------------------------------------------------------- 24 | # Vision Transformer with Deformable Attention 25 | # Modified by Zhuofan Xia 26 | # Originated from https://github.com/SHI-Labs/NATTEN/blob/main/src/natten/natten2d.py 27 | # -------------------------------------------------------- 28 | 29 | import torch 30 | from torch import nn 31 | from torch.nn.functional import pad 32 | from torch.nn.init import trunc_normal_ 33 | from natten.functional import NATTEN2DQKRPBFunction, NATTEN2DAVFunction 34 | 35 | 36 | class NeighborhoodAttention2D(nn.Module): 37 | """ 38 | Neighborhood Attention 2D Module 39 | """ 40 | def __init__(self, dim, kernel_size, num_heads, attn_drop=0., proj_drop=0., 41 | dilation=None): 42 | super().__init__() 43 | self.fp16_enabled = False 44 | self.num_heads = num_heads 45 | self.head_dim = dim // self.num_heads 46 | self.scale = self.head_dim ** -0.5 47 | assert kernel_size > 1 and kernel_size % 2 == 1, \ 48 | f"Kernel size must be an odd number greater than 1, got {kernel_size}." 49 | assert kernel_size in [3, 5, 7, 9, 11, 13], \ 50 | f"CUDA kernel only supports kernel sizes 3, 5, 7, 9, 11, and 13; got {kernel_size}." 51 | self.kernel_size = kernel_size 52 | if type(dilation) is str: 53 | self.dilation = None 54 | self.window_size = None 55 | else: 56 | assert dilation is None or dilation >= 1, \ 57 | f"Dilation must be greater than or equal to 1, got {dilation}." 58 | self.dilation = dilation or 1 59 | self.window_size = self.kernel_size * self.dilation 60 | 61 | self.qkv = nn.Linear(dim, dim * 3) 62 | self.rpb = nn.Parameter(torch.zeros(num_heads, (2 * kernel_size - 1), (2 * kernel_size - 1))) 63 | trunc_normal_(self.rpb, std=.02, mean=0., a=-2., b=2.) 64 | self.attn_drop = nn.Dropout(attn_drop) 65 | self.proj = nn.Linear(dim, dim) 66 | self.proj_drop = nn.Dropout(proj_drop) 67 | 68 | def forward(self, x): 69 | # assert x.dtype == torch.float16, f"AMP failed!, dtype={x.dtype}" 70 | x = x.permute(0, 2, 3, 1) 71 | B, Hp, Wp, C = x.shape 72 | H, W = int(Hp), int(Wp) 73 | pad_l = pad_t = pad_r = pad_b = 0 74 | dilation = self.dilation 75 | window_size = self.window_size 76 | if window_size is None: 77 | dilation = max(min(H, W) // self.kernel_size, 1) 78 | window_size = dilation * self.kernel_size 79 | if H < window_size or W < window_size: 80 | pad_l = pad_t = 0 81 | pad_r = max(0, window_size - W) 82 | pad_b = max(0, window_size - H) 83 | x = pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) 84 | _, H, W, _ = x.shape 85 | qkv = self.qkv(x).reshape(B, H, W, 3, self.num_heads, self.head_dim).permute(3, 0, 4, 1, 2, 5) 86 | q, k, v = qkv[0], qkv[1], qkv[2] 87 | q = q * self.scale 88 | # breakpoint() 89 | attn = NATTEN2DQKRPBFunction.apply(q, k, self.rpb, self.kernel_size, dilation) 90 | attn = attn.softmax(dim=-1) 91 | attn = self.attn_drop(attn) 92 | x = NATTEN2DAVFunction.apply(attn, v, self.kernel_size, dilation) 93 | x = x.permute(0, 2, 3, 1, 4).reshape(B, H, W, C) 94 | if pad_r or pad_b: 95 | x = x[:, :Hp, :Wp, :] 96 | 97 | return self.proj_drop(self.proj(x)).permute(0, 3, 1, 2), None, None -------------------------------------------------------------------------------- /models/qna.py: -------------------------------------------------------------------------------- 1 | # Learned Queries for Efficient Local Attention 2 | # Modified from the JAX Implementation of QnA (20220830) 3 | # https://github.com/moabarar/qna/blob/main/layers/qna.py 4 | # -------------------------------------------------------- 5 | # Vision Transformer with Deformable Attention 6 | # Modified by Zhuofan Xia 7 | # Not used in the journal paper, only for reference. 8 | # -------------------------------------------------------- 9 | 10 | import torch 11 | import torch.nn as nn 12 | import torch.nn.functional as F 13 | from timm.models.layers import trunc_normal_ 14 | import einops 15 | import math 16 | 17 | class FusedKQnA(nn.Module): 18 | 19 | def __init__(self, n_q, n_channels, n_heads, ksize, stride, padding, qna_activation): 20 | 21 | super().__init__() 22 | self.n_q = n_q 23 | self.n_channels = n_channels 24 | self.n_heads = n_heads 25 | self.ksize = ksize 26 | self.stride = stride 27 | self.padding = padding 28 | self.head_channels = n_channels // n_heads 29 | self.qna_activation = qna_activation 30 | 31 | 32 | self.proj_k = nn.Linear(self.n_channels, self.n_channels * stride, bias=False) 33 | self.proj_v = nn.Linear(self.n_channels, self.n_channels * stride, bias=False) 34 | self.proj_out = nn.Conv2d(self.n_channels * stride, self.n_channels * stride, 1, 1, 0, bias=False) 35 | self.scale = self.head_channels ** -0.5 36 | self.q_param = nn.Parameter(torch.empty(self.n_q, self.n_channels * stride)) 37 | trunc_normal_(self.q_param, std=math.sqrt(1.0 / self.head_channels)) 38 | 39 | self.attn_scale = nn.Parameter(torch.empty(1, 1, self.ksize ** 2, self.n_q * self.n_heads * stride)) 40 | nn.init.normal_(self.attn_scale, std=0.02) 41 | 42 | self.rpb_table = nn.Parameter(torch.empty(self.ksize ** 2, self.n_q * self.n_heads * stride)) 43 | trunc_normal_(self.rpb_table, std=0.02) 44 | 45 | def forward(self, x): 46 | # assert not torch.isnan(x).any(), 'NaN in x' 47 | B, C, H, W = x.size() 48 | x = einops.rearrange(x, 'b c h w -> b (h w) c') 49 | N = H * W 50 | q = self.q_param[None, ...].expand(B, self.n_q, C * self.stride) 51 | # assert not torch.isnan(q).any(), 'NaN in q' 52 | q = einops.rearrange(q, 'b q (h c) -> b h q c', h=self.n_heads * self.stride, c=self.head_channels, q=self.n_q) 53 | # q_norm_l2 = torch.linalg.vector_norm(q, ord=2, dim=3, keepdim=True) 54 | # q = q / (q_norm_l2 + 1e-6) 55 | k = self.proj_k(x) 56 | B, N, C = k.size() 57 | # assert not torch.isnan(k).any(), 'NaN in k' 58 | k = einops.rearrange(k, 'b k (h c) -> b h k c', h=self.n_heads * self.stride, c=self.head_channels, k=N) 59 | q = q * self.scale 60 | qkT = torch.einsum('b h q c, b h k c -> b h q k', q, k) 61 | qkT = einops.rearrange(qkT, 'b h q k -> b k q h') 62 | 63 | # assert not torch.isnan(qkT).any(), 'NaN in qkT' 64 | 65 | v = self.proj_v(x) 66 | attn_scale = self.attn_scale.reshape(self.ksize, self.ksize, 1, self.n_q * self.n_heads * self.stride) 67 | rpb = self.rpb_table.reshape(self.ksize, self.ksize, 1, self.n_q * self.n_heads * self.stride) 68 | 69 | if self.qna_activation == 'exp': 70 | cost_exp = torch.exp(qkT - qkT.max().detach()) 71 | elif self.qna_activation == 'sigmoid': 72 | cost_exp = qkT.sigmoid() 73 | elif self.qna_activation == 'linear': 74 | cost_exp = qkT 75 | 76 | # assert not torch.isnan(cost_exp).any(), 'NaN in cost_exp' 77 | 78 | v_cost_exp = cost_exp[..., None] * v.reshape(B, N, 1, self.n_heads * self.stride, self.head_channels) 79 | # v_cost_exp : B N n_q h ch 80 | v_cost_exp = v_cost_exp.reshape(B, N, self.n_q * self.n_heads * self.stride * self.head_channels) 81 | 82 | if self.qna_activation == 'exp': 83 | rpb_exp = torch.exp(rpb - rpb.max().detach()) 84 | elif self.qna_activation == 'sigmoid': 85 | rpb_exp = rpb.sigmoid() 86 | elif self.qna_activation == 'linear': 87 | rpb_exp = rpb 88 | 89 | summation_kernel = (rpb_exp * attn_scale).repeat_interleave(self.head_channels, dim=3) 90 | # summation_kernel : [kh, kw, 1, n_q * h * Ch] HWIO 91 | v_cost_exp_ = einops.rearrange(v_cost_exp, 'b (h w) c -> b c h w', h=H, w=W) 92 | v_kern_ = einops.rearrange(summation_kernel, 'h w i o -> o i h w') 93 | sum_num = F.conv2d( 94 | v_cost_exp_, 95 | v_kern_, 96 | stride=self.stride, 97 | padding=self.padding, 98 | groups=self.n_q * self.n_channels * self.stride 99 | ) # B Nq*h*Ch H 100 | sum_num = einops.rearrange( 101 | sum_num, 102 | 'b (q g c) h w -> b q g c h w', 103 | q=self.n_q, g=self.n_heads * self.stride, c=self.head_channels) 104 | cost_exp_ = einops.rearrange( 105 | cost_exp, 106 | 'b (h w) q c -> b (q c) h w', 107 | h=H, 108 | w=W, 109 | q=self.n_q, 110 | c=self.n_heads * self.stride) # B Nq*h H W 111 | kern_ = einops.rearrange(rpb_exp, 'h w i o -> o i h w') 112 | 113 | sum_den = F.conv2d( 114 | cost_exp_, 115 | kern_, 116 | stride=self.stride, 117 | padding=self.padding, 118 | groups=self.n_q * self.n_heads * self.stride 119 | ) # B Nq*h H W 120 | sum_den = einops.rearrange( 121 | sum_den, 122 | 'b (q g c) h w -> b q g c h w', 123 | q=self.n_q, g=self.n_heads * self.stride, c=1) 124 | H = H // self.stride 125 | W = W // self.stride 126 | out = (sum_num / sum_den).sum(dim=1).reshape(B, C, H, W) 127 | out = self.proj_out(out) 128 | return out, None, None 129 | 130 | -------------------------------------------------------------------------------- /models/slide.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Slide-Transformer: Hierarchical Vision Transformer with Local Self-Attention 3 | # Originally written by Xuran Pan 4 | # -------------------------------------------------------- 5 | # Vision Transformer with Deformable Attention 6 | # Modified by Zhuofan Xia 7 | # -------------------------------------------------------- 8 | 9 | import torch 10 | import torch.nn as nn 11 | import einops 12 | from timm.models.layers import trunc_normal_ 13 | 14 | 15 | class SlideAttention(nn.Module): 16 | 17 | def __init__( 18 | self, dim, num_heads, ka, qkv_bias=True, qk_scale=None, attn_drop=0., 19 | proj_drop=0.,dim_reduction=4, rpb=True, padding_mode='zeros', 20 | share_dwc_kernel=True, share_qkv=False): 21 | 22 | super().__init__() 23 | self.dim = dim 24 | self.num_heads = num_heads 25 | head_dim = dim // num_heads 26 | self.scale = qk_scale or head_dim ** -0.5 27 | if share_qkv: 28 | self.qkv_scale = 1 29 | else: 30 | self.qkv_scale = 3 31 | self.rpb = rpb 32 | self.share_dwc_kernel = share_dwc_kernel 33 | self.padding_mode = padding_mode 34 | self.share_qkv = share_qkv 35 | self.ka = ka 36 | self.dim_reduction = dim_reduction 37 | self.qkv = nn.Linear(dim, dim * self.qkv_scale//self.dim_reduction, bias=qkv_bias) 38 | self.attn_drop = nn.Dropout(attn_drop) 39 | self.proj = nn.Linear(dim//self.dim_reduction, dim) 40 | self.proj_drop = nn.Dropout(proj_drop) 41 | 42 | self.dep_conv = nn.Conv2d(dim//self.dim_reduction//self.num_heads, self.ka*self.ka*dim//self.dim_reduction//self.num_heads, kernel_size=self.ka, bias=True, groups=dim//self.dim_reduction//self.num_heads, padding=self.ka//2, padding_mode=padding_mode) 43 | self.dep_conv1 = nn.Conv2d(dim//self.dim_reduction//self.num_heads, self.ka*self.ka*dim//self.dim_reduction//self.num_heads, kernel_size=self.ka, bias=True, groups=dim//self.dim_reduction//self.num_heads, padding=self.ka//2, padding_mode=padding_mode) 44 | if not share_dwc_kernel: 45 | self.dep_conv2 = nn.Conv2d(dim//self.dim_reduction//self.num_heads, self.ka*self.ka*dim//self.dim_reduction//self.num_heads, kernel_size=self.ka, bias=True, groups=dim//self.dim_reduction//self.num_heads, padding=self.ka//2, padding_mode=padding_mode) 46 | 47 | self.reset_parameters() 48 | 49 | # define a parameter table of relative position bias 50 | if self.rpb: 51 | self.relative_position_bias_table = nn.Parameter( 52 | torch.zeros(1, self.num_heads, 1, self.ka*self.ka, 1, 1)) 53 | trunc_normal_(self.relative_position_bias_table, std=.02) 54 | self.softmax = nn.Softmax(dim=3) 55 | 56 | def reset_parameters(self): 57 | # shift initialization for group convolution 58 | kernel = torch.zeros(self.ka*self.ka, self.ka, self.ka) 59 | for i in range(self.ka*self.ka): 60 | kernel[i, i//self.ka, i%self.ka] = 1. 61 | kernel = kernel.unsqueeze(1).repeat(self.dim//self.dim_reduction//self.num_heads, 1, 1, 1) 62 | self.dep_conv.weight = nn.Parameter(data=kernel, requires_grad=False) 63 | 64 | def forward(self, x): 65 | 66 | x = einops.rearrange(x, 'b c h w -> b h w c') 67 | B, H, W, C = x.shape 68 | qkv = self.qkv(x) 69 | 70 | f_conv = qkv.permute(0, 3, 1, 2).reshape(B*self.num_heads, self.qkv_scale*C//self.dim_reduction//self.num_heads, H, W) 71 | 72 | if self.qkv_scale == 3: 73 | q = (f_conv[:, :C//self.dim_reduction//self.num_heads, :, :] * self.scale).reshape(B, self.num_heads, C//self.dim_reduction//self.num_heads, 1, H, W) 74 | k = f_conv[:, C//self.dim_reduction//self.num_heads:2*C//self.dim_reduction//self.num_heads, :, :] # B*self.nhead, C//self.nhead, H, W 75 | v = f_conv[:, 2*C//self.dim_reduction//self.num_heads:, :, :] 76 | elif self.qkv_scale == 1: 77 | q = (f_conv * self.scale).reshape(B, self.num_heads, C//self.dim_reduction//self.num_heads, 1, H, W) 78 | k = v = f_conv 79 | 80 | if self.share_dwc_kernel: 81 | k = (self.dep_conv(k) + self.dep_conv1(k)).reshape(B, self.num_heads, C//self.dim_reduction//self.num_heads, self.ka*self.ka, H, W) 82 | v = (self.dep_conv(v) + self.dep_conv1(v)).reshape(B, self.num_heads, C//self.dim_reduction//self.num_heads, self.ka*self.ka, H, W) 83 | else: 84 | k = (self.dep_conv(k) + self.dep_conv1(k)).reshape(B, self.num_heads, C//self.dim_reduction//self.num_heads, self.ka*self.ka, H, W) 85 | v = (self.dep_conv(v) + self.dep_conv2(v)).reshape(B, self.num_heads, C//self.dim_reduction//self.num_heads, self.ka*self.ka, H, W) 86 | 87 | if self.rpb: 88 | k = k + self.relative_position_bias_table 89 | attn = (q * k).sum(2, keepdim=True) # B, self.nhead, 1, k^2, H, W 90 | 91 | attn = self.softmax(attn) 92 | attn = self.attn_drop(attn) 93 | 94 | x = (attn * v).sum(3).reshape(B, C//self.dim_reduction, H, W).permute(0, 2, 3, 1) 95 | x = self.proj(x) 96 | x = self.proj_drop(x) 97 | x = einops.rearrange(x, 'b h w c -> b c h w') 98 | return x, None, None -------------------------------------------------------------------------------- /optimizer.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import torch.optim as optim 12 | 13 | def build_optimizer(config, model): 14 | """ 15 | Build optimizer, set weight decay of normalization to 0 by default. 16 | """ 17 | skip = {} 18 | skip_keywords = {} 19 | if hasattr(model, 'no_weight_decay'): 20 | skip = model.no_weight_decay() 21 | if hasattr(model, 'no_weight_decay_keywords'): 22 | skip_keywords = model.no_weight_decay_keywords() 23 | 24 | if hasattr(model, 'lower_lr_kvs'): 25 | lower_lr_kvs = model.lower_lr_kvs 26 | else: 27 | lower_lr_kvs = {} 28 | 29 | parameters = set_weight_decay_and_lr( 30 | model, skip, skip_keywords, lower_lr_kvs, config.TRAIN.BASE_LR) 31 | 32 | opt_lower = config.TRAIN.OPTIMIZER.NAME.lower() 33 | optimizer = None 34 | if opt_lower == 'sgd': 35 | optimizer = optim.SGD(parameters, momentum=config.TRAIN.OPTIMIZER.MOMENTUM, nesterov=True, 36 | lr=config.TRAIN.BASE_LR, weight_decay=config.TRAIN.WEIGHT_DECAY) 37 | elif opt_lower == 'adamw': 38 | optimizer = optim.AdamW(parameters, eps=config.TRAIN.OPTIMIZER.EPS, betas=config.TRAIN.OPTIMIZER.BETAS, 39 | lr=config.TRAIN.BASE_LR, weight_decay=config.TRAIN.WEIGHT_DECAY) 40 | 41 | return optimizer 42 | 43 | 44 | def set_weight_decay_and_lr( 45 | model, 46 | skip_list=(), skip_keywords=(), 47 | lower_lr_kvs={}, base_lr=5e-4): 48 | # breakpoint() 49 | assert len(lower_lr_kvs) == 1 or len(lower_lr_kvs) == 0 50 | has_lower_lr = len(lower_lr_kvs) == 1 51 | if has_lower_lr: 52 | for k,v in lower_lr_kvs.items(): 53 | lower_lr_key = k 54 | lower_lr = v * base_lr 55 | 56 | has_decay = [] 57 | has_decay_low = [] 58 | no_decay = [] 59 | no_decay_low = [] 60 | 61 | for name, param in model.named_parameters(): 62 | if not param.requires_grad: 63 | continue # frozen weights 64 | if len(param.shape) == 1 or name.endswith(".bias") or (name in skip_list) or \ 65 | check_keywords_in_name(name, skip_keywords): 66 | 67 | if has_lower_lr and check_keywords_in_name(name, (lower_lr_key,)): 68 | no_decay_low.append(param) 69 | else: 70 | no_decay.append(param) 71 | 72 | else: 73 | 74 | if has_lower_lr and check_keywords_in_name(name, (lower_lr_key,)): 75 | has_decay_low.append(param) 76 | else: 77 | has_decay.append(param) 78 | 79 | if has_lower_lr: 80 | result = [ 81 | {'params': has_decay}, 82 | {'params': has_decay_low, 'lr': lower_lr}, 83 | {'params': no_decay, 'weight_decay': 0.}, 84 | {'params': no_decay_low, 'weight_decay': 0., 'lr': lower_lr} 85 | ] 86 | else: 87 | result = [ 88 | {'params': has_decay}, 89 | {'params': no_decay, 'weight_decay': 0.} 90 | ] 91 | # breakpoint() 92 | return result 93 | 94 | 95 | def check_keywords_in_name(name, keywords=()): 96 | isin = False 97 | for keyword in keywords: 98 | if keyword in name: 99 | isin = True 100 | return isin 101 | -------------------------------------------------------------------------------- /slurm_main.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import os 12 | import time 13 | import argparse 14 | import datetime 15 | import numpy as np 16 | 17 | import torch 18 | import torch.nn as nn 19 | import torch.backends.cudnn as cudnn 20 | import torch.distributed as dist 21 | from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy 22 | from timm.utils import accuracy, AverageMeter 23 | 24 | from config import get_config 25 | from models import build_model 26 | from data import build_loader 27 | from lr_scheduler import build_scheduler 28 | from optimizer import build_optimizer 29 | from logger import create_logger 30 | from utils import load_checkpoint, load_pretrained, save_checkpoint, \ 31 | get_grad_norm, auto_resume_helper, reduce_tensor, init_dist_slurm 32 | 33 | from torch.cuda.amp import GradScaler, autocast 34 | 35 | import warnings 36 | warnings.filterwarnings('ignore') 37 | 38 | 39 | def parse_option(): 40 | parser = argparse.ArgumentParser() 41 | parser.add_argument('--cfg', type=str, required=True, metavar="FILE", help='path to config file', ) 42 | parser.add_argument( 43 | "--opts", 44 | help="Modify config options by adding 'KEY VALUE' pairs. ", 45 | default=None, 46 | nargs='+', 47 | ) 48 | # easy config modification 49 | parser.add_argument('--batch-size', type=int, help="batch size for single GPU") 50 | parser.add_argument('--data-path', type=str, help='path to dataset') 51 | parser.add_argument('--resume', help='resume from checkpoint') 52 | parser.add_argument('--amp', action='store_true', default=False) 53 | parser.add_argument('--output', default='output', type=str, metavar='PATH', 54 | help='root of output folder, the full path is // (default: output)') 55 | parser.add_argument('--tag', help='tag of experiment') 56 | parser.add_argument('--eval', action='store_true', help='Perform evaluation only') 57 | parser.add_argument('--throughput', action='store_true', help='Test throughput only') 58 | parser.add_argument('--print-freq', type=int, help='Printing frequency.', default=100) 59 | 60 | args, unparsed = parser.parse_known_args() 61 | 62 | config = get_config(args) 63 | 64 | return args, config 65 | 66 | 67 | def main(): 68 | 69 | args, config = parse_option() 70 | init_dist_slurm() 71 | torch.cuda.set_device(config.LOCAL_RANK) 72 | dist.barrier() 73 | 74 | seed = config.SEED + dist.get_rank() 75 | torch.manual_seed(seed) 76 | np.random.seed(seed) 77 | cudnn.enabled = True 78 | cudnn.benchmark = True 79 | 80 | if config.DATA.DATASET == 'imagenet': 81 | standard_bs = 512.0 82 | elif config.DATA.DATASET == 'imagenet22k': 83 | standard_bs = 4096.0 84 | else: 85 | raise RuntimeError("Wrong dataset!") 86 | 87 | # linear scale the learning rate according to total batch size, may not be optimal 88 | linear_scaled_lr = config.TRAIN.BASE_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / standard_bs 89 | linear_scaled_warmup_lr = config.TRAIN.WARMUP_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / standard_bs 90 | linear_scaled_min_lr = config.TRAIN.MIN_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / standard_bs 91 | config.defrost() 92 | config.TRAIN.BASE_LR = linear_scaled_lr 93 | config.TRAIN.WARMUP_LR = linear_scaled_warmup_lr 94 | config.TRAIN.MIN_LR = linear_scaled_min_lr 95 | config.LOCAL_RANK = int(os.environ['LOCAL_RANK']) 96 | config.freeze() 97 | 98 | os.makedirs(config.OUTPUT, exist_ok=True) 99 | logger = create_logger(output_dir=config.OUTPUT, dist_rank=dist.get_rank(), name=f"{config.MODEL.NAME}") 100 | 101 | if dist.get_rank() == 0: 102 | path = os.path.join(config.OUTPUT, "config.yaml") 103 | with open(path, "w") as f: 104 | f.write(config.dump()) 105 | logger.info(f"Full config saved to {path}") 106 | 107 | # print config 108 | logger.info(config.dump()) 109 | 110 | _, dataset_val, data_loader_train, data_loader_val, mixup_fn = build_loader(config) 111 | 112 | logger.info(f"Creating model:{config.MODEL.TYPE}/{config.MODEL.NAME}") 113 | model = build_model(config) 114 | model.cuda() 115 | model = nn.SyncBatchNorm.convert_sync_batchnorm(model) 116 | logger.info(str(model)) 117 | 118 | optimizer = build_optimizer(config, model) 119 | 120 | model = nn.parallel.DistributedDataParallel(model, device_ids=[config.LOCAL_RANK], broadcast_buffers=True, find_unused_parameters=False) 121 | model_without_ddp = model.module 122 | 123 | lr_scheduler = build_scheduler(config, optimizer, len(data_loader_train)) 124 | 125 | if config.AUG.MIXUP > 0.: 126 | # smoothing is handled with mixup label transform 127 | criterion = SoftTargetCrossEntropy() 128 | elif config.MODEL.LABEL_SMOOTHING > 0.: 129 | criterion = LabelSmoothingCrossEntropy(smoothing=config.MODEL.LABEL_SMOOTHING) 130 | else: 131 | criterion = nn.CrossEntropyLoss() 132 | 133 | max_accuracy = 0.0 134 | 135 | if config.MODEL.PRETRAINED is not None: 136 | pretrained_ckpt_path = config.MODEL.PRETRAINED 137 | load_pretrained(pretrained_ckpt_path, model_without_ddp, logger) 138 | 139 | if config.TRAIN.AUTO_RESUME and config.MODEL.RESUME == '': 140 | resume_file = auto_resume_helper(config.OUTPUT) 141 | if resume_file: 142 | if config.MODEL.RESUME: 143 | logger.warning(f"auto-resume changing resume file from {config.MODEL.RESUME} to {resume_file}") 144 | config.defrost() 145 | config.MODEL.RESUME = resume_file 146 | config.freeze() 147 | logger.info(f'auto resuming from {resume_file}') 148 | else: 149 | logger.info(f'no checkpoint found in {config.OUTPUT}, ignoring auto resume') 150 | 151 | if config.MODEL.RESUME: 152 | max_accuracy = load_checkpoint(config, model_without_ddp, optimizer, lr_scheduler, logger) 153 | acc1, acc5, loss = validate(config, data_loader_val, model, logger) 154 | torch.cuda.empty_cache() 155 | logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") 156 | if config.EVAL_MODE: 157 | return 158 | if config.THROUGHPUT_MODE: 159 | throughput(data_loader_val, model, logger) 160 | return 161 | logger.info("Start training") 162 | start_time = time.time() 163 | for epoch in range(config.TRAIN.START_EPOCH, config.TRAIN.EPOCHS): 164 | data_loader_train.sampler.set_epoch(epoch) 165 | 166 | train_one_epoch(config, model, criterion, data_loader_train, optimizer, epoch, mixup_fn, lr_scheduler, logger) 167 | 168 | if dist.get_rank() == 0 and ((epoch + 1) % config.SAVE_FREQ == 0 or (epoch + 1) == (config.TRAIN.EPOCHS)): 169 | save_checkpoint(config, epoch + 1, model_without_ddp, max_accuracy, optimizer, lr_scheduler, logger) 170 | 171 | acc1, acc5, loss = validate(config, data_loader_val, model, logger) 172 | 173 | logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") 174 | max_accuracy = max(max_accuracy, acc1) 175 | logger.info(f'Max accuracy: {max_accuracy:.2f}%') 176 | 177 | total_time = time.time() - start_time 178 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 179 | logger.info('Training time {}'.format(total_time_str)) 180 | 181 | 182 | def train_one_epoch(config, model, criterion, data_loader, optimizer, epoch, mixup_fn, lr_scheduler, logger): 183 | model.train() 184 | optimizer.zero_grad() 185 | 186 | num_steps = len(data_loader) 187 | batch_time = AverageMeter() 188 | loss_meter = AverageMeter() 189 | norm_meter = AverageMeter() 190 | 191 | start = time.time() 192 | end = time.time() 193 | 194 | scaler = GradScaler() 195 | 196 | for idx, (samples, targets) in enumerate(data_loader): 197 | 198 | optimizer.zero_grad() 199 | samples = samples.cuda(non_blocking=True) 200 | targets = targets.cuda(non_blocking=True) 201 | 202 | if mixup_fn is not None: 203 | samples, targets = mixup_fn(samples, targets) 204 | 205 | if config.AMP: 206 | with autocast(): 207 | outputs, _, _ = model(samples) 208 | loss = criterion(outputs, targets) 209 | scaler.scale(loss).backward() 210 | if config.TRAIN.CLIP_GRAD: 211 | scaler.unscale_(optimizer) 212 | grad_norm = nn.utils.clip_grad_norm_(model.parameters(), config.TRAIN.CLIP_GRAD) 213 | scaler.step(optimizer) 214 | scaler.update() 215 | else: 216 | grad_norm = get_grad_norm(model.parameters()) 217 | scaler.step(optimizer) 218 | scaler.update() 219 | else: 220 | outputs, _, _ = model(samples) 221 | loss = criterion(outputs, targets) 222 | loss.backward() 223 | if config.TRAIN.CLIP_GRAD: 224 | grad_norm = nn.utils.clip_grad_norm_(model.parameters(), config.TRAIN.CLIP_GRAD) 225 | else: 226 | grad_norm = get_grad_norm(model.parameters()) 227 | optimizer.step() 228 | 229 | lr_scheduler.step_update(epoch * num_steps + idx) 230 | 231 | torch.cuda.synchronize() 232 | 233 | loss_meter.update(loss.item(), targets.size(0)) 234 | norm_meter.update(grad_norm) 235 | batch_time.update(time.time() - end) 236 | end = time.time() 237 | 238 | if (idx + 1) % config.PRINT_FREQ == 0: 239 | lr = optimizer.param_groups[0]['lr'] 240 | memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) 241 | etas = batch_time.avg * (num_steps - idx) 242 | logger.info( 243 | f'Train: [{epoch + 1}/{config.TRAIN.EPOCHS}][{idx + 1}/{num_steps}]\t' 244 | f'eta {datetime.timedelta(seconds=int(etas))} lr {lr:.6f}\t' 245 | f'time {batch_time.val:.4f} ({batch_time.avg:.4f})\t' 246 | f'loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' 247 | f'grad_norm {norm_meter.val:.4f} ({norm_meter.avg:.4f})\t' 248 | f'mem {memory_used:.0f}MB') 249 | epoch_time = time.time() - start 250 | logger.info(f"EPOCH {epoch + 1} training takes {datetime.timedelta(seconds=int(epoch_time))}") 251 | 252 | @torch.no_grad() 253 | def validate(config, data_loader, model, logger): 254 | criterion = nn.CrossEntropyLoss() 255 | model.eval() 256 | 257 | batch_time = AverageMeter() 258 | loss_meter = AverageMeter() 259 | acc1_meter = AverageMeter() 260 | acc5_meter = AverageMeter() 261 | 262 | end = time.time() 263 | for idx, (images, target) in enumerate(data_loader): 264 | images = images.cuda(non_blocking=True) 265 | target = target.cuda(non_blocking=True) 266 | 267 | # compute output 268 | output, _, _ = model(images) 269 | 270 | # measure accuracy and record loss 271 | loss = criterion(output, target) 272 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 273 | 274 | acc1 = reduce_tensor(acc1) 275 | acc5 = reduce_tensor(acc5) 276 | loss = reduce_tensor(loss) 277 | 278 | loss_meter.update(loss.item(), target.size(0)) 279 | acc1_meter.update(acc1.item(), target.size(0)) 280 | acc5_meter.update(acc5.item(), target.size(0)) 281 | 282 | # measure elapsed time 283 | batch_time.update(time.time() - end) 284 | end = time.time() 285 | 286 | if (idx + 1) % config.PRINT_FREQ == 0: 287 | memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) 288 | logger.info( 289 | f'Test: [{(idx + 1)}/{len(data_loader)}]\t' 290 | f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 291 | f'Loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' 292 | f'Acc@1 {acc1_meter.val:.3f} ({acc1_meter.avg:.3f})\t' 293 | f'Acc@5 {acc5_meter.val:.3f} ({acc5_meter.avg:.3f})\t' 294 | f'Mem {memory_used:.0f}MB') 295 | logger.info(f' * Acc@1 {acc1_meter.avg:.3f} Acc@5 {acc5_meter.avg:.3f}') 296 | return acc1_meter.avg, acc5_meter.avg, loss_meter.avg 297 | 298 | @torch.no_grad() 299 | def throughput(data_loader, model, logger): 300 | model.eval() 301 | 302 | for _, (images, _) in enumerate(data_loader): 303 | images = images.cuda(non_blocking=True) 304 | batch_size = images.shape[0] 305 | for i in range(50): 306 | model(images) 307 | torch.cuda.synchronize() 308 | logger.info(f"throughput averaged with 30 times") 309 | tic1 = time.time() 310 | for i in range(30): 311 | model(images) 312 | torch.cuda.synchronize() 313 | tic2 = time.time() 314 | logger.info(f"batch_size {batch_size} throughput {30 * batch_size / (tic2 - tic1)}") 315 | return 316 | if __name__ == '__main__': 317 | main() 318 | -------------------------------------------------------------------------------- /train.sh: -------------------------------------------------------------------------------- 1 | PORT=30001 2 | GPU=$1 3 | CFG=$2 4 | TAG=${3:-'default'} 5 | 6 | torchrun --nproc_per_node $GPU --master_port $PORT main.py --cfg $CFG --data-path --amp --tag $TAG -------------------------------------------------------------------------------- /train_slurm.sh: -------------------------------------------------------------------------------- 1 | set -x 2 | CFG=$1 3 | GPUS=$2 4 | JOB_NAME=$3 5 | 6 | GPUS_PER_NODE=${GPUS_PER_NODE:-8} 7 | CPUS_PER_TASK=${CPUS_PER_TASK:-8} 8 | srun -p RTX3090 \ 9 | --job-name=${JOB_NAME} \ 10 | --gres=gpu:${GPUS_PER_NODE} \ 11 | --ntasks=${GPUS} \ 12 | --ntasks-per-node=${GPUS_PER_NODE} \ 13 | --cpus-per-task=${CPUS_PER_TASK} \ 14 | --kill-on-bad-exit=1 \ 15 | python -u slurm_main.py --cfg="configs/${CFG}.yaml" --data-path="/home/data/ImageNet" --amp --tag="${CFG}" 16 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu 6 | # -------------------------------------------------------- 7 | # Vision Transformer with Deformable Attention 8 | # Modified by Zhuofan Xia 9 | # -------------------------------------------------------- 10 | 11 | import os 12 | import torch 13 | import torch.distributed as dist 14 | import subprocess 15 | 16 | 17 | def load_checkpoint(config, model, optimizer, lr_scheduler, logger): 18 | logger.info(f"==============> Resuming form {config.MODEL.RESUME}....................") 19 | if config.MODEL.RESUME.startswith('https'): 20 | checkpoint = torch.hub.load_state_dict_from_url( 21 | config.MODEL.RESUME, map_location='cpu', check_hash=True) 22 | else: 23 | checkpoint = torch.load(config.MODEL.RESUME, map_location='cpu') 24 | msg = model.load_state_dict(checkpoint['model'], strict=False) 25 | logger.info(msg) 26 | max_accuracy = 0.0 27 | if not config.EVAL_MODE and 'optimizer' in checkpoint and 'lr_scheduler' in checkpoint and 'epoch' in checkpoint: 28 | optimizer.load_state_dict(checkpoint['optimizer']) 29 | lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) 30 | config.defrost() 31 | config.TRAIN.START_EPOCH = checkpoint['epoch'] 32 | config.freeze() 33 | logger.info(f"=> loaded successfully '{config.MODEL.RESUME}' (epoch {checkpoint['epoch']})") 34 | if 'max_accuracy' in checkpoint: 35 | max_accuracy = checkpoint['max_accuracy'] 36 | 37 | del checkpoint 38 | torch.cuda.empty_cache() 39 | return max_accuracy 40 | 41 | def load_pretrained(ckpt_path, model, logger): 42 | logger.info(f"==============> Loading pretrained form {ckpt_path}....................") 43 | checkpoint = torch.load(ckpt_path, map_location='cpu') 44 | msg = model.load_pretrained(checkpoint['model']) 45 | logger.info(msg) 46 | logger.info(f"=> Loaded successfully {ckpt_path} ") 47 | del checkpoint 48 | torch.cuda.empty_cache() 49 | 50 | 51 | def save_checkpoint(config, epoch, model, max_accuracy, optimizer, lr_scheduler, logger): 52 | save_state = {'model': model.state_dict(), 53 | 'optimizer': optimizer.state_dict(), 54 | 'lr_scheduler': lr_scheduler.state_dict(), 55 | 'max_accuracy': max_accuracy, 56 | 'epoch': epoch, 57 | 'config': config} 58 | 59 | save_path = os.path.join(config.OUTPUT, f'ckpt_epoch_{epoch}.pth') 60 | logger.info(f"{save_path} saving......") 61 | torch.save(save_state, save_path) 62 | logger.info(f"{save_path} saved !!!") 63 | 64 | 65 | def get_grad_norm(parameters, norm_type=2): 66 | if isinstance(parameters, torch.Tensor): 67 | parameters = [parameters] 68 | parameters = list(filter(lambda p: p.grad is not None, parameters)) 69 | norm_type = float(norm_type) 70 | total_norm = 0 71 | for p in parameters: 72 | param_norm = p.grad.data.norm(norm_type) 73 | total_norm += param_norm.item() ** norm_type 74 | total_norm = total_norm ** (1. / norm_type) 75 | return total_norm 76 | 77 | 78 | def auto_resume_helper(output_dir): 79 | checkpoints = os.listdir(output_dir) 80 | checkpoints = [ckpt for ckpt in checkpoints if ckpt.endswith('pth')] 81 | print(f"All checkpoints founded in {output_dir}: {checkpoints}") 82 | if len(checkpoints) > 0: 83 | latest_checkpoint = max([os.path.join(output_dir, d) for d in checkpoints], key=os.path.getmtime) 84 | print(f"The latest checkpoint founded: {latest_checkpoint}") 85 | resume_file = latest_checkpoint 86 | else: 87 | resume_file = None 88 | return resume_file 89 | 90 | 91 | def reduce_tensor(tensor): 92 | rt = tensor.clone() 93 | dist.all_reduce(rt, op=dist.ReduceOp.SUM) 94 | rt /= dist.get_world_size() 95 | return rt 96 | 97 | def init_dist_slurm(): 98 | """Initialize slurm distributed training environment. 99 | If argument ``port`` is not specified, then the master port will be system 100 | environment variable ``MASTER_PORT``. If ``MASTER_PORT`` is not in system 101 | environment variable, then a default port ``29500`` will be used. 102 | Args: 103 | backend (str): Backend of torch.distributed. 104 | port (int, optional): Master port. Defaults to None. 105 | """ 106 | proc_id = int(os.environ['SLURM_PROCID']) 107 | ntasks = int(os.environ['SLURM_NTASKS']) 108 | node_list = os.environ['SLURM_NODELIST'] 109 | num_gpus = torch.cuda.device_count() 110 | torch.cuda.set_device(proc_id % num_gpus) 111 | addr = subprocess.getoutput( 112 | f'scontrol show hostname {node_list} | head -n1') 113 | # specify master port 114 | if 'MASTER_PORT' in os.environ: 115 | pass # use MASTER_PORT in the environment variable 116 | else: 117 | # 29500 is torch.distributed default port 118 | os.environ['MASTER_PORT'] = '29500' 119 | # use MASTER_ADDR in the environment variable if it already exists 120 | if 'MASTER_ADDR' not in os.environ: 121 | os.environ['MASTER_ADDR'] = addr 122 | 123 | os.environ['WORLD_SIZE'] = str(ntasks) 124 | os.environ['LOCAL_RANK'] = str(proc_id % num_gpus) 125 | os.environ['RANK'] = str(proc_id) 126 | 127 | dist.init_process_group(backend='nccl') --------------------------------------------------------------------------------