├── .gitignore ├── LICENSE ├── MODEL_DETAILS.md ├── README.md ├── configs └── spinenet │ ├── spinenet_143_B_8gpu.py │ ├── spinenet_190_B_8gpu.py │ ├── spinenet_49S_B_8gpu.py │ ├── spinenet_49_B_8gpu.py │ └── spinenet_96_B_8gpu.py └── mmdet └── models └── backbones ├── __init__.py └── spinenet.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 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MODEL_DETAILS.md: -------------------------------------------------------------------------------- 1 | # MODEL DETAILS 2 | In paper SpineNet was trained with three protocols. I only trained with protocol B. Training SpineNet takes lots of time, for example I took 7 days to train SpineNet-49 with 8 TITAN V gpus. 3 | 4 | - protocol A: random scale between[0.8,1.2];250 epochs;DropBlock 5 | - protocol B: random scale between[0.5,2.0];350 epochs 6 | - protocol C: random scale between[0.5,2.0];500 epochs;stochastic depth;Swish 7 | 8 | ### mAP 9 | 10 | | Variant | my code(B) | paper(A) | paper(B) | paper(C) | 11 | | ------------ | ---------- | -------- | -------- | -------- | 12 | | SpineNet-49S | 39.1 | —— | 39.9 | 41.5 | 13 | | SpineNet-49 | 42.7 | 40.8 | 42.8 | 44.3 | 14 | 15 | ### Details 16 | 17 | - SpineNet-49 18 | ``` 19 | Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.427 20 | Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.627 21 | Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.454 22 | Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.240 23 | Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.465 24 | Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.590 25 | Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.344 26 | Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.545 27 | Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.579 28 | Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.370 29 | Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.631 30 | Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.751 31 | ``` 32 | - SpineNet-49S 33 | ``` 34 | Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.391 35 | Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.587 36 | Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.422 37 | Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.202 38 | Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.425 39 | Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.563 40 | Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.323 41 | Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.514 42 | Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.546 43 | Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.327 44 | Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.596 45 | Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.724 46 | ``` 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpineNet-Pytorch 2 | SpineNet is a CVPR 2020 paper for object detection. This project is a kind of implementation of SpineNet using mmdetection. 3 | 4 | It is based on the 5 | 6 | * the paper [SpineNet: Learning Scale-Permuted Backbone for Recognition and Localization](https://arxiv.org/abs/1912.05027) 7 | * [official TensorFlow implementation](https://github.com/tensorflow/tpu/tree/master/models/official/detection) 8 | 9 | ## Models 10 | 11 | | Variant | mAP | Params | FLOPs | mAP in paper | Params in paper | FLOPs in paper | 12 | | ------------ | ---- | ------ | ------- | ------------ | --------------- | -------------- | 13 | | SpineNet-49S | 39.1 | 11.15M | 30.04B | 39.9 | 12.0M | 33.8B | 14 | | SpineNet-49 | 42.7 | 28.31M | 83.7B | 42.8 | 28.5M | 85.4B | 15 | | SpineNet-96 | —— | 42.74M | 261.35B | 47.1 | 43.0M | 265.4B | 16 | | SpineNet-143 | —— | —— | —— | 48.1 | 66.9M | 524.4B | 17 | | SpineNet-190 | —— | —— | —— | —— | 163.6M | 1885B | 18 | 19 | **Note**: The parameters and flops are a little different from paper, so I think there are some difference between my code and official's code. More information about models can see in [MODEL_DETAILS.md](MODEL_DETAILS.md) 20 | 21 | ## Usage 22 | 23 | 1. **Install mmdetection** 24 | 25 | This implementation is based on [mmdetection](https://github.com/open-mmlab/mmdetection)(v1.1.0+8732ed9). Please refer to [INSTALL.md](docs/INSTALL.md) for installation and dataset preparation. 26 | 27 | 2. **Copy the codes to mmdetection directory** 28 | 29 | ```shell 30 | cp -r mmdet/ ${MMDETECTION_PATH}/ 31 | cp -r configs/ ${MMDETECTION_PATH}/ 32 | ``` 33 | 34 | 3. **Prepare data** 35 | 36 | The directories should be arranged like this: 37 | 38 | > mmdetection 39 | > ├── mmdet 40 | > ├── tools 41 | > ├── configs 42 | > ├── data 43 | > │ ├── coco 44 | > │ │ ├── annotations 45 | > │ │ ├── train2017 46 | > │ │ ├── val2017 47 | > │ │ ├── test2017 48 | 49 | 50 | 4. **Train D0 with 4 GPUs** 51 | 52 | ```shell 53 | CONFIG_FILE=configs/spinenet/spinenet_49_B_8gpu.py 54 | ./ tools/dist_train.py ${CONFIG_FILE} 4 55 | ``` 56 | 57 | 5. **Calculate parameters and flops** 58 | 59 | ```shell 60 | python tools/get_flops.py ${CONFIG_FILE} --shape $SIZE $SIZE 61 | ``` 62 | 63 | 6. **Test** 64 | 65 | ```shell 66 | python tools/test.py ${CONFIG_FILE} ${CHECKPOINT_FILE} --out ${OUTPUT_FILE} --eval bbox 67 | ``` 68 | 69 | More usages can reference [mmdetection documentation](https://mmdetection.readthedocs.io/en/latest/GETTING_STARTED.html#inference-with-pretrained-models). 70 | 71 | ## Update log 72 | 73 | - [2020-05-30] Add SpineNet-49S results. 74 | - [2020-05-13] Update codes and results. 75 | - [2020-05-02] Create this repository. 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /configs/spinenet/spinenet_143_B_8gpu.py: -------------------------------------------------------------------------------- 1 | cudnn_benchmark = True 2 | # model settings 3 | norm_cfg = dict(type='SyncBN', momentum=0.01, eps=1e-3, requires_grad=True) 4 | model = dict( 5 | type='RetinaNet', 6 | backbone=dict( 7 | type='SpineNet', 8 | arch="143", 9 | norm_cfg=norm_cfg), 10 | neck=None, 11 | bbox_head=dict( 12 | type='RetinaSepBNHead', 13 | num_classes=81, 14 | num_ins=5, 15 | in_channels=256, 16 | stacked_convs=4, 17 | feat_channels=256, 18 | octave_base_scale=4, 19 | scales_per_octave=3, 20 | anchor_ratios=[0.5, 1.0, 2.0], 21 | anchor_strides=[8, 16, 32, 64, 128], 22 | target_means=[.0, .0, .0, .0], 23 | target_stds=[1.0, 1.0, 1.0, 1.0], 24 | norm_cfg=norm_cfg, 25 | loss_cls=dict( 26 | type='FocalLoss', 27 | use_sigmoid=True, 28 | gamma=2.0, 29 | alpha=0.25, 30 | loss_weight=1.0), 31 | loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0))) 32 | # training and testing settings 33 | train_cfg = dict( 34 | assigner=dict( 35 | type='MaxIoUAssigner', 36 | pos_iou_thr=0.5, 37 | neg_iou_thr=0.5, 38 | min_pos_iou=0, 39 | ignore_iof_thr=-1), 40 | allowed_border=-1, 41 | pos_weight=-1, 42 | debug=False) 43 | test_cfg = dict( 44 | nms_pre=1000, 45 | min_bbox_size=0, 46 | score_thr=0.05, 47 | nms=dict(type='nms', iou_thr=0.5), 48 | max_per_img=100) 49 | # dataset settings 50 | dataset_type = 'CocoDataset' 51 | data_root = 'data/coco/' 52 | img_norm_cfg = dict( 53 | mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) 54 | train_pipeline = [ 55 | dict(type='LoadImageFromFile'), 56 | dict(type='LoadAnnotations', with_bbox=True), 57 | dict( 58 | type='Resize', 59 | img_scale=(1280, 1280), 60 | ratio_range=(0.1, 1.9), 61 | keep_ratio=True), 62 | dict(type='RandomCrop', crop_size=(1280, 1280)), 63 | dict(type='RandomFlip', flip_ratio=0.5), 64 | dict(type='Normalize', **img_norm_cfg), 65 | dict(type='Pad', size=(1280, 1280)), 66 | dict(type='DefaultFormatBundle'), 67 | dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), 68 | ] 69 | test_pipeline = [ 70 | dict(type='LoadImageFromFile'), 71 | dict( 72 | type='MultiScaleFlipAug', 73 | img_scale=(1280, 1280), 74 | flip=False, 75 | transforms=[ 76 | dict(type='Resize', keep_ratio=True), 77 | dict(type='RandomFlip'), 78 | dict(type='Normalize', **img_norm_cfg), 79 | dict(type='Pad', size_divisor=128), 80 | dict(type='ImageToTensor', keys=['img']), 81 | dict(type='Collect', keys=['img']), 82 | ]) 83 | ] 84 | data = dict( 85 | imgs_per_gpu=8, 86 | workers_per_gpu=4, 87 | train=dict( 88 | type=dataset_type, 89 | ann_file=data_root + 'annotations/instances_train2017.json', 90 | img_prefix=data_root + 'train2017/', 91 | pipeline=train_pipeline), 92 | val=dict( 93 | type=dataset_type, 94 | ann_file=data_root + 'annotations/instances_val2017.json', 95 | img_prefix=data_root + 'val2017/', 96 | pipeline=test_pipeline), 97 | test=dict( 98 | type=dataset_type, 99 | ann_file=data_root + 'annotations/instances_val2017.json', 100 | img_prefix=data_root + 'val2017/', 101 | pipeline=test_pipeline)) 102 | evaluation = dict(interval=1, metric='bbox') 103 | # optimizer 104 | optimizer = dict( 105 | type='SGD', 106 | lr=0.07, 107 | momentum=0.9, 108 | weight_decay=4e-5, 109 | paramwise_options=dict(norm_decay_mult=0)) 110 | optimizer_config = dict(grad_clip=dict(max_norm=10, norm_type=2)) 111 | # learning policy 112 | lr_config = dict( 113 | policy='step', 114 | warmup='linear', 115 | warmup_iters=8000, 116 | warmup_ratio=0.1, 117 | step=[320, 340]) 118 | checkpoint_config = dict(interval=1) 119 | # yapf:disable 120 | log_config = dict( 121 | interval=50, 122 | hooks=[ 123 | dict(type='TextLoggerHook'), 124 | # dict(type='TensorboardLoggerHook') 125 | ]) 126 | # yapf:enable 127 | # runtime settings 128 | total_epochs = 50 129 | dist_params = dict(backend='nccl') 130 | log_level = 'INFO' 131 | work_dir = './work_dirs/spinenet_143_B/' 132 | load_from = None 133 | resume_from = None 134 | workflow = [('train', 1)] 135 | -------------------------------------------------------------------------------- /configs/spinenet/spinenet_190_B_8gpu.py: -------------------------------------------------------------------------------- 1 | cudnn_benchmark = True 2 | # model settings 3 | norm_cfg = dict(type='SyncBN', momentum=0.01, eps=1e-3, requires_grad=True) 4 | model = dict( 5 | type='RetinaNet', 6 | backbone=dict( 7 | type='SpineNet', 8 | arch="190", 9 | norm_cfg=norm_cfg), 10 | neck=None, 11 | bbox_head=dict( 12 | type='RetinaSepBNHead', 13 | num_classes=81, 14 | num_ins=5, 15 | in_channels=512, 16 | stacked_convs=7, 17 | feat_channels=512, 18 | octave_base_scale=4, 19 | scales_per_octave=3, 20 | anchor_ratios=[0.5, 1.0, 2.0], 21 | anchor_strides=[8, 16, 32, 64, 128], 22 | target_means=[.0, .0, .0, .0], 23 | target_stds=[1.0, 1.0, 1.0, 1.0], 24 | norm_cfg=norm_cfg, 25 | loss_cls=dict( 26 | type='FocalLoss', 27 | use_sigmoid=True, 28 | gamma=2.0, 29 | alpha=0.25, 30 | loss_weight=1.0), 31 | loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0))) 32 | # training and testing settings 33 | train_cfg = dict( 34 | assigner=dict( 35 | type='MaxIoUAssigner', 36 | pos_iou_thr=0.5, 37 | neg_iou_thr=0.5, 38 | min_pos_iou=0, 39 | ignore_iof_thr=-1), 40 | allowed_border=-1, 41 | pos_weight=-1, 42 | debug=False) 43 | test_cfg = dict( 44 | nms_pre=1000, 45 | min_bbox_size=0, 46 | score_thr=0.05, 47 | nms=dict(type='nms', iou_thr=0.5), 48 | max_per_img=100) 49 | # dataset settings 50 | dataset_type = 'CocoDataset' 51 | data_root = 'data/coco/' 52 | img_norm_cfg = dict( 53 | mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) 54 | train_pipeline = [ 55 | dict(type='LoadImageFromFile'), 56 | dict(type='LoadAnnotations', with_bbox=True), 57 | dict( 58 | type='Resize', 59 | img_scale=(1280, 1280), 60 | ratio_range=(0.1, 1.9), 61 | keep_ratio=True), 62 | dict(type='RandomCrop', crop_size=(1280, 1280)), 63 | dict(type='RandomFlip', flip_ratio=0.5), 64 | dict(type='Normalize', **img_norm_cfg), 65 | dict(type='Pad', size=(1280, 1280)), 66 | dict(type='DefaultFormatBundle'), 67 | dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), 68 | ] 69 | test_pipeline = [ 70 | dict(type='LoadImageFromFile'), 71 | dict( 72 | type='MultiScaleFlipAug', 73 | img_scale=(1280, 1280), 74 | flip=False, 75 | transforms=[ 76 | dict(type='Resize', keep_ratio=True), 77 | dict(type='RandomFlip'), 78 | dict(type='Normalize', **img_norm_cfg), 79 | dict(type='Pad', size_divisor=128), 80 | dict(type='ImageToTensor', keys=['img']), 81 | dict(type='Collect', keys=['img']), 82 | ]) 83 | ] 84 | data = dict( 85 | imgs_per_gpu=8, 86 | workers_per_gpu=4, 87 | train=dict( 88 | type=dataset_type, 89 | ann_file=data_root + 'annotations/instances_train2017.json', 90 | img_prefix=data_root + 'train2017/', 91 | pipeline=train_pipeline), 92 | val=dict( 93 | type=dataset_type, 94 | ann_file=data_root + 'annotations/instances_val2017.json', 95 | img_prefix=data_root + 'val2017/', 96 | pipeline=test_pipeline), 97 | test=dict( 98 | type=dataset_type, 99 | ann_file=data_root + 'annotations/instances_val2017.json', 100 | img_prefix=data_root + 'val2017/', 101 | pipeline=test_pipeline)) 102 | evaluation = dict(interval=1, metric='bbox') 103 | # optimizer 104 | optimizer = dict( 105 | type='SGD', 106 | lr=0.07, 107 | momentum=0.9, 108 | weight_decay=4e-5, 109 | paramwise_options=dict(norm_decay_mult=0)) 110 | optimizer_config = dict(grad_clip=dict(max_norm=10, norm_type=2)) 111 | # learning policy 112 | lr_config = dict( 113 | policy='step', 114 | warmup='linear', 115 | warmup_iters=8000, 116 | warmup_ratio=0.1, 117 | step=[320, 340]) 118 | checkpoint_config = dict(interval=1) 119 | # yapf:disable 120 | log_config = dict( 121 | interval=50, 122 | hooks=[ 123 | dict(type='TextLoggerHook'), 124 | # dict(type='TensorboardLoggerHook') 125 | ]) 126 | # yapf:enable 127 | # runtime settings 128 | total_epochs = 50 129 | dist_params = dict(backend='nccl') 130 | log_level = 'INFO' 131 | work_dir = './work_dirs/spinenet_190_B/' 132 | load_from = None 133 | resume_from = None 134 | workflow = [('train', 1)] 135 | -------------------------------------------------------------------------------- /configs/spinenet/spinenet_49S_B_8gpu.py: -------------------------------------------------------------------------------- 1 | # mAP 39.1 2 | 3 | cudnn_benchmark = True 4 | # model settings 5 | norm_cfg = dict(type='SyncBN', momentum=0.01, eps=1e-3, requires_grad=True) 6 | model = dict( 7 | type='RetinaNet', 8 | backbone=dict( 9 | type='SpineNet', 10 | arch="49S", 11 | norm_cfg=norm_cfg), 12 | neck=None, 13 | bbox_head=dict( 14 | type='RetinaSepBNHead', 15 | num_classes=81, 16 | num_ins=5, 17 | in_channels=128, 18 | stacked_convs=4, 19 | feat_channels=128, 20 | octave_base_scale=3, 21 | scales_per_octave=3, 22 | anchor_ratios=[0.5, 1.0, 2.0], 23 | anchor_strides=[8, 16, 32, 64, 128], 24 | target_means=[.0, .0, .0, .0], 25 | target_stds=[1.0, 1.0, 1.0, 1.0], 26 | norm_cfg=norm_cfg, 27 | loss_cls=dict( 28 | type='FocalLoss', 29 | use_sigmoid=True, 30 | gamma=2.0, 31 | alpha=0.25, 32 | loss_weight=1.0), 33 | loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0))) 34 | # training and testing settings 35 | train_cfg = dict( 36 | assigner=dict( 37 | type='MaxIoUAssigner', 38 | pos_iou_thr=0.5, 39 | neg_iou_thr=0.5, 40 | min_pos_iou=0, 41 | ignore_iof_thr=-1), 42 | allowed_border=-1, 43 | pos_weight=-1, 44 | debug=False) 45 | test_cfg = dict( 46 | nms_pre=1000, 47 | min_bbox_size=0, 48 | score_thr=0.05, 49 | nms=dict(type='nms', iou_thr=0.5), 50 | max_per_img=100) 51 | # dataset settings 52 | dataset_type = 'CocoDataset' 53 | data_root = 'data/coco/' 54 | img_norm_cfg = dict( 55 | mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) 56 | train_pipeline = [ 57 | dict(type='LoadImageFromFile'), 58 | dict(type='LoadAnnotations', with_bbox=True), 59 | dict( 60 | type='Resize', 61 | img_scale=(640, 640), 62 | ratio_range=(0.5, 2.0), 63 | keep_ratio=True), 64 | dict(type='RandomCrop', crop_size=(640, 640)), 65 | dict(type='RandomFlip', flip_ratio=0.5), 66 | dict(type='Normalize', **img_norm_cfg), 67 | dict(type='Pad', size=(640, 640)), 68 | dict(type='DefaultFormatBundle'), 69 | dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), 70 | ] 71 | test_pipeline = [ 72 | dict(type='LoadImageFromFile'), 73 | dict( 74 | type='MultiScaleFlipAug', 75 | img_scale=(640, 640), 76 | flip=False, 77 | transforms=[ 78 | dict(type='Resize', keep_ratio=True), 79 | dict(type='RandomFlip'), 80 | dict(type='Normalize', **img_norm_cfg), 81 | dict(type='Pad', size_divisor=128), 82 | dict(type='ImageToTensor', keys=['img']), 83 | dict(type='Collect', keys=['img']), 84 | ]) 85 | ] 86 | data = dict( 87 | imgs_per_gpu=8, 88 | workers_per_gpu=4, 89 | train=dict( 90 | type=dataset_type, 91 | ann_file=data_root + 'annotations/instances_train2017.json', 92 | img_prefix=data_root + 'train2017/', 93 | pipeline=train_pipeline), 94 | val=dict( 95 | type=dataset_type, 96 | ann_file=data_root + 'annotations/instances_val2017.json', 97 | img_prefix=data_root + 'val2017/', 98 | pipeline=test_pipeline), 99 | test=dict( 100 | type=dataset_type, 101 | ann_file=data_root + 'annotations/instances_val2017.json', 102 | img_prefix=data_root + 'val2017/', 103 | pipeline=test_pipeline)) 104 | evaluation = dict(interval=1, metric='bbox') 105 | # optimizer 106 | optimizer = dict( 107 | type='SGD', 108 | lr=0.07, 109 | momentum=0.9, 110 | weight_decay=4e-5, 111 | paramwise_options=dict(norm_decay_mult=0)) 112 | optimizer_config = dict(grad_clip=dict(max_norm=10, norm_type=2)) 113 | # learning policy 114 | lr_config = dict( 115 | policy='step', 116 | warmup='linear', 117 | warmup_iters=8000, 118 | warmup_ratio=0.1, 119 | step=[320, 340]) 120 | checkpoint_config = dict(interval=1) 121 | # yapf:disable 122 | log_config = dict( 123 | interval=50, 124 | hooks=[ 125 | dict(type='TextLoggerHook'), 126 | # dict(type='TensorboardLoggerHook') 127 | ]) 128 | # yapf:enable 129 | # runtime settings 130 | total_epochs = 50 131 | dist_params = dict(backend='nccl') 132 | log_level = 'INFO' 133 | work_dir = './work_dirs/spinenet_49S_B/' 134 | load_from = None 135 | resume_from = None 136 | workflow = [('train', 1)] 137 | -------------------------------------------------------------------------------- /configs/spinenet/spinenet_49_B_8gpu.py: -------------------------------------------------------------------------------- 1 | # mAP 42.7 2 | 3 | cudnn_benchmark = True 4 | # model settings 5 | norm_cfg = dict(type='SyncBN', momentum=0.01, eps=1e-3, requires_grad=True) 6 | model = dict( 7 | type='RetinaNet', 8 | backbone=dict( 9 | type='SpineNet', 10 | arch="49", 11 | norm_cfg=norm_cfg), 12 | neck=None, 13 | bbox_head=dict( 14 | type='RetinaSepBNHead', 15 | num_classes=81, 16 | num_ins=5, 17 | in_channels=256, 18 | stacked_convs=4, 19 | feat_channels=256, 20 | octave_base_scale=3, 21 | scales_per_octave=3, 22 | anchor_ratios=[0.5, 1.0, 2.0], 23 | anchor_strides=[8, 16, 32, 64, 128], 24 | target_means=[.0, .0, .0, .0], 25 | target_stds=[1.0, 1.0, 1.0, 1.0], 26 | norm_cfg=norm_cfg, 27 | loss_cls=dict( 28 | type='FocalLoss', 29 | use_sigmoid=True, 30 | gamma=2.0, 31 | alpha=0.25, 32 | loss_weight=1.0), 33 | loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0))) 34 | # training and testing settings 35 | train_cfg = dict( 36 | assigner=dict( 37 | type='MaxIoUAssigner', 38 | pos_iou_thr=0.5, 39 | neg_iou_thr=0.5, 40 | min_pos_iou=0, 41 | ignore_iof_thr=-1), 42 | allowed_border=-1, 43 | pos_weight=-1, 44 | debug=False) 45 | test_cfg = dict( 46 | nms_pre=1000, 47 | min_bbox_size=0, 48 | score_thr=0.05, 49 | nms=dict(type='nms', iou_thr=0.5), 50 | max_per_img=100) 51 | # dataset settings 52 | dataset_type = 'CocoDataset' 53 | data_root = 'data/coco/' 54 | img_norm_cfg = dict( 55 | mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) 56 | train_pipeline = [ 57 | dict(type='LoadImageFromFile'), 58 | dict(type='LoadAnnotations', with_bbox=True), 59 | dict( 60 | type='Resize', 61 | img_scale=(640, 640), 62 | ratio_range=(0.5, 2.0), 63 | keep_ratio=True), 64 | dict(type='RandomCrop', crop_size=(640, 640)), 65 | dict(type='RandomFlip', flip_ratio=0.5), 66 | dict(type='Normalize', **img_norm_cfg), 67 | dict(type='Pad', size=(640, 640)), 68 | dict(type='DefaultFormatBundle'), 69 | dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), 70 | ] 71 | test_pipeline = [ 72 | dict(type='LoadImageFromFile'), 73 | dict( 74 | type='MultiScaleFlipAug', 75 | img_scale=(640, 640), 76 | flip=False, 77 | transforms=[ 78 | dict(type='Resize', keep_ratio=True), 79 | dict(type='RandomFlip'), 80 | dict(type='Normalize', **img_norm_cfg), 81 | dict(type='Pad', size_divisor=64), 82 | dict(type='ImageToTensor', keys=['img']), 83 | dict(type='Collect', keys=['img']), 84 | ]) 85 | ] 86 | data = dict( 87 | imgs_per_gpu=8, 88 | workers_per_gpu=4, 89 | train=dict( 90 | type=dataset_type, 91 | ann_file=data_root + 'annotations/instances_train2017.json', 92 | img_prefix=data_root + 'train2017/', 93 | pipeline=train_pipeline), 94 | val=dict( 95 | type=dataset_type, 96 | ann_file=data_root + 'annotations/instances_val2017.json', 97 | img_prefix=data_root + 'val2017/', 98 | pipeline=test_pipeline), 99 | test=dict( 100 | type=dataset_type, 101 | ann_file=data_root + 'annotations/instances_val2017.json', 102 | img_prefix=data_root + 'val2017/', 103 | pipeline=test_pipeline)) 104 | evaluation = dict(interval=1, metric='bbox') 105 | # optimizer 106 | optimizer = dict( 107 | type='SGD', 108 | lr=0.07, 109 | momentum=0.9, 110 | weight_decay=4e-5, 111 | paramwise_options=dict(norm_decay_mult=0)) 112 | optimizer_config = dict(grad_clip=dict(max_norm=10, norm_type=2)) 113 | # learning policy 114 | lr_config = dict( 115 | policy='step', 116 | warmup='linear', 117 | warmup_iters=8000, 118 | warmup_ratio=0.1, 119 | step=[320, 340]) 120 | checkpoint_config = dict(interval=1) 121 | # yapf:disable 122 | log_config = dict( 123 | interval=50, 124 | hooks=[ 125 | dict(type='TextLoggerHook'), 126 | # dict(type='TensorboardLoggerHook') 127 | ]) 128 | # yapf:enable 129 | # runtime settings 130 | total_epochs = 50 131 | dist_params = dict(backend='nccl') 132 | log_level = 'INFO' 133 | work_dir = './work_dirs/spinenet_49_B/' 134 | load_from = None 135 | resume_from = None 136 | workflow = [('train', 1)] 137 | -------------------------------------------------------------------------------- /configs/spinenet/spinenet_96_B_8gpu.py: -------------------------------------------------------------------------------- 1 | cudnn_benchmark = True 2 | # model settings 3 | norm_cfg = dict(type='SyncBN', momentum=0.01, eps=1e-3, requires_grad=True) 4 | model = dict( 5 | type='RetinaNet', 6 | backbone=dict( 7 | type='SpineNet', 8 | arch="96", 9 | norm_cfg=norm_cfg), 10 | neck=None, 11 | bbox_head=dict( 12 | type='RetinaSepBNHead', 13 | num_classes=81, 14 | num_ins=5, 15 | in_channels=256, 16 | stacked_convs=4, 17 | feat_channels=256, 18 | octave_base_scale=3, 19 | scales_per_octave=3, 20 | anchor_ratios=[0.5, 1.0, 2.0], 21 | anchor_strides=[8, 16, 32, 64, 128], 22 | target_means=[.0, .0, .0, .0], 23 | target_stds=[1.0, 1.0, 1.0, 1.0], 24 | norm_cfg=norm_cfg, 25 | loss_cls=dict( 26 | type='FocalLoss', 27 | use_sigmoid=True, 28 | gamma=2.0, 29 | alpha=0.25, 30 | loss_weight=1.0), 31 | loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0))) 32 | # training and testing settings 33 | train_cfg = dict( 34 | assigner=dict( 35 | type='MaxIoUAssigner', 36 | pos_iou_thr=0.5, 37 | neg_iou_thr=0.5, 38 | min_pos_iou=0, 39 | ignore_iof_thr=-1), 40 | allowed_border=-1, 41 | pos_weight=-1, 42 | debug=False) 43 | test_cfg = dict( 44 | nms_pre=1000, 45 | min_bbox_size=0, 46 | score_thr=0.05, 47 | nms=dict(type='nms', iou_thr=0.5), 48 | max_per_img=100) 49 | # dataset settings 50 | dataset_type = 'CocoDataset' 51 | data_root = 'data/coco/' 52 | img_norm_cfg = dict( 53 | mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) 54 | train_pipeline = [ 55 | dict(type='LoadImageFromFile'), 56 | dict(type='LoadAnnotations', with_bbox=True), 57 | dict( 58 | type='Resize', 59 | img_scale=(1024, 1024), 60 | ratio_range=(0.5, 2.0), 61 | keep_ratio=True), 62 | dict(type='RandomCrop', crop_size=(1024, 1024)), 63 | dict(type='RandomFlip', flip_ratio=0.5), 64 | dict(type='Normalize', **img_norm_cfg), 65 | dict(type='Pad', size=(1024, 1024)), 66 | dict(type='DefaultFormatBundle'), 67 | dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), 68 | ] 69 | test_pipeline = [ 70 | dict(type='LoadImageFromFile'), 71 | dict( 72 | type='MultiScaleFlipAug', 73 | img_scale=(1024, 1024), 74 | flip=False, 75 | transforms=[ 76 | dict(type='Resize', keep_ratio=True), 77 | dict(type='RandomFlip'), 78 | dict(type='Normalize', **img_norm_cfg), 79 | dict(type='Pad', size_divisor=128), 80 | dict(type='ImageToTensor', keys=['img']), 81 | dict(type='Collect', keys=['img']), 82 | ]) 83 | ] 84 | data = dict( 85 | imgs_per_gpu=8, 86 | workers_per_gpu=4, 87 | train=dict( 88 | type=dataset_type, 89 | ann_file=data_root + 'annotations/instances_train2017.json', 90 | img_prefix=data_root + 'train2017/', 91 | pipeline=train_pipeline), 92 | val=dict( 93 | type=dataset_type, 94 | ann_file=data_root + 'annotations/instances_val2017.json', 95 | img_prefix=data_root + 'val2017/', 96 | pipeline=test_pipeline), 97 | test=dict( 98 | type=dataset_type, 99 | ann_file=data_root + 'annotations/instances_val2017.json', 100 | img_prefix=data_root + 'val2017/', 101 | pipeline=test_pipeline)) 102 | evaluation = dict(interval=1, metric='bbox') 103 | # optimizer 104 | optimizer = dict( 105 | type='SGD', 106 | lr=0.07, 107 | momentum=0.9, 108 | weight_decay=4e-5, 109 | paramwise_options=dict(norm_decay_mult=0)) 110 | optimizer_config = dict(grad_clip=dict(max_norm=10, norm_type=2)) 111 | # learning policy 112 | lr_config = dict( 113 | policy='step', 114 | warmup='linear', 115 | warmup_iters=8000, 116 | warmup_ratio=0.1, 117 | step=[320, 340]) 118 | checkpoint_config = dict(interval=1) 119 | # yapf:disable 120 | log_config = dict( 121 | interval=50, 122 | hooks=[ 123 | dict(type='TextLoggerHook'), 124 | # dict(type='TensorboardLoggerHook') 125 | ]) 126 | # yapf:enable 127 | # runtime settings 128 | total_epochs = 50 129 | dist_params = dict(backend='nccl') 130 | log_level = 'INFO' 131 | work_dir = './work_dirs/spinenet_96_B/' 132 | load_from = None 133 | resume_from = None 134 | workflow = [('train', 1)] 135 | -------------------------------------------------------------------------------- /mmdet/models/backbones/__init__.py: -------------------------------------------------------------------------------- 1 | from .hrnet import HRNet 2 | from .resnet import ResNet, make_res_layer 3 | from .resnext import ResNeXt 4 | from .ssd_vgg import SSDVGG 5 | from .spinenet import SpineNet 6 | 7 | __all__ = ['ResNet', 'make_res_layer', 'ResNeXt', 'SSDVGG', 'HRNet', 'SpineNet'] 8 | 9 | -------------------------------------------------------------------------------- /mmdet/models/backbones/spinenet.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch.nn.functional as F 3 | 4 | from .resnet import BasicBlock, Bottleneck, make_res_layer 5 | from mmdet.ops import ConvModule 6 | from mmcv.cnn import constant_init, kaiming_init 7 | from torch.nn.modules.batchnorm import _BatchNorm 8 | from ..registry import BACKBONES 9 | 10 | FILTER_SIZE_MAP = { 11 | 1: 32, 12 | 2: 64, 13 | 3: 128, 14 | 4: 256, 15 | 5: 256, 16 | 6: 256, 17 | 7: 256, 18 | } 19 | 20 | # The fixed SpineNet architecture discovered by NAS. 21 | # Each element represents a specification of a building block: 22 | # (block_level, block_fn, (input_offset0, input_offset1), is_output). 23 | SPINENET_BLOCK_SPECS = [ 24 | (2, Bottleneck, (None, None), False), # init block 25 | (2, Bottleneck, (None, None), False), # init block 26 | (2, Bottleneck, (0, 1), False), 27 | (4, BasicBlock, (0, 1), False), 28 | (3, Bottleneck, (2, 3), False), 29 | (4, Bottleneck, (2, 4), False), 30 | (6, BasicBlock, (3, 5), False), 31 | (4, Bottleneck, (3, 5), False), 32 | (5, BasicBlock, (6, 7), False), 33 | (7, BasicBlock, (6, 8), False), 34 | (5, Bottleneck, (8, 9), False), 35 | (5, Bottleneck, (8, 10), False), 36 | (4, Bottleneck, (5, 10), True), 37 | (3, Bottleneck, (4, 10), True), 38 | (5, Bottleneck, (7, 12), True), 39 | (7, Bottleneck, (5, 14), True), 40 | (6, Bottleneck, (12, 14), True), 41 | ] 42 | 43 | SCALING_MAP = { 44 | '49S': { 45 | 'endpoints_num_filters': 128, 46 | 'filter_size_scale': 0.65, 47 | 'resample_alpha': 0.5, 48 | 'block_repeats': 1, 49 | }, 50 | '49': { 51 | 'endpoints_num_filters': 256, 52 | 'filter_size_scale': 1.0, 53 | 'resample_alpha': 0.5, 54 | 'block_repeats': 1, 55 | }, 56 | '96': { 57 | 'endpoints_num_filters': 256, 58 | 'filter_size_scale': 1.0, 59 | 'resample_alpha': 0.5, 60 | 'block_repeats': 2, 61 | }, 62 | '143': { 63 | 'endpoints_num_filters': 256, 64 | 'filter_size_scale': 1.0, 65 | 'resample_alpha': 1.0, 66 | 'block_repeats': 3, 67 | }, 68 | '190': { 69 | 'endpoints_num_filters': 512, 70 | 'filter_size_scale': 1.3, 71 | 'resample_alpha': 1.0, 72 | 'block_repeats': 4, 73 | }, 74 | } 75 | 76 | 77 | class BlockSpec(object): 78 | """A container class that specifies the block configuration for SpineNet.""" 79 | 80 | def __init__(self, level, block_fn, input_offsets, is_output): 81 | self.level = level 82 | self.block_fn = block_fn 83 | self.input_offsets = input_offsets 84 | self.is_output = is_output 85 | 86 | 87 | def build_block_specs(block_specs=None): 88 | """Builds the list of BlockSpec objects for SpineNet.""" 89 | if not block_specs: 90 | block_specs = SPINENET_BLOCK_SPECS 91 | return [BlockSpec(*b) for b in block_specs] 92 | 93 | 94 | class Resample(nn.Module): 95 | def __init__(self, in_channels, out_channels, scale, block_type, norm_cfg=dict(type="BN"), alpha=1.0): 96 | super(Resample, self).__init__() 97 | self.scale = scale 98 | new_in_channels = int(in_channels * alpha) 99 | if block_type == Bottleneck: 100 | in_channels *= 4 101 | self.squeeze_conv = ConvModule(in_channels, new_in_channels, 1, norm_cfg=norm_cfg) 102 | if scale < 1: 103 | self.downsample_conv = ConvModule(new_in_channels, new_in_channels, 3, padding=1, stride=2, norm_cfg=norm_cfg) 104 | self.expand_conv = ConvModule(new_in_channels, out_channels, 1, norm_cfg=norm_cfg, act_cfg=None) 105 | 106 | def _resize(self, x): 107 | if self.scale == 1: 108 | return x 109 | elif self.scale > 1: 110 | return F.interpolate(x, scale_factor=self.scale, mode='nearest') 111 | else: 112 | x = self.downsample_conv(x) 113 | if self.scale < 0.5: 114 | new_kernel_size = 3 if self.scale >= 0.25 else 5 115 | x = F.max_pool2d(x, kernel_size=new_kernel_size, stride=int(0.5/self.scale), padding=new_kernel_size//2) 116 | return x 117 | 118 | def forward(self, inputs): 119 | feat = self.squeeze_conv(inputs) 120 | feat = self._resize(feat) 121 | feat = self.expand_conv(feat) 122 | return feat 123 | 124 | 125 | class Merge(nn.Module): 126 | """Merge two input tensors""" 127 | def __init__(self, block_spec, norm_cfg, alpha, filter_size_scale): 128 | super(Merge, self).__init__() 129 | out_channels = int(FILTER_SIZE_MAP[block_spec.level] * filter_size_scale) 130 | if block_spec.block_fn == Bottleneck: 131 | out_channels *= 4 132 | self.block = block_spec.block_fn 133 | self.resample_ops = nn.ModuleList() 134 | for spec_idx in block_spec.input_offsets: 135 | spec = BlockSpec(*SPINENET_BLOCK_SPECS[spec_idx]) 136 | in_channels = int(FILTER_SIZE_MAP[spec.level] * filter_size_scale) 137 | scale = 2**(spec.level - block_spec.level) 138 | self.resample_ops.append( 139 | Resample(in_channels, out_channels, scale, spec.block_fn, norm_cfg, alpha) 140 | ) 141 | 142 | def forward(self, inputs): 143 | assert len(inputs) == len(self.resample_ops) 144 | parent0_feat = self.resample_ops[0](inputs[0]) 145 | parent1_feat = self.resample_ops[1](inputs[1]) 146 | target_feat = parent0_feat + parent1_feat 147 | return target_feat 148 | 149 | 150 | @BACKBONES.register_module 151 | class SpineNet(nn.Module): 152 | """Class to build SpineNet backbone""" 153 | def __init__(self, 154 | arch, 155 | in_channels=3, 156 | output_level=[3, 4, 5, 6, 7], 157 | conv_cfg=None, 158 | norm_cfg=dict(type='BN', requires_grad=True), 159 | zero_init_residual=True, 160 | activation='relu'): 161 | super(SpineNet, self).__init__() 162 | self._block_specs = build_block_specs()[2:] 163 | self._endpoints_num_filters = SCALING_MAP[arch]['endpoints_num_filters'] 164 | self._resample_alpha = SCALING_MAP[arch]['resample_alpha'] 165 | self._block_repeats = SCALING_MAP[arch]['block_repeats'] 166 | self._filter_size_scale = SCALING_MAP[arch]['filter_size_scale'] 167 | self._init_block_fn = Bottleneck 168 | self._num_init_blocks = 2 169 | self.conv_cfg = conv_cfg 170 | self.norm_cfg = norm_cfg 171 | self.zero_init_residual = zero_init_residual 172 | assert min(output_level) > 2 and max(output_level) < 8, "Output level out of range" 173 | self.output_level = output_level 174 | 175 | self._make_stem_layer(in_channels) 176 | self._make_scale_permuted_network() 177 | self._make_endpoints() 178 | 179 | def _make_stem_layer(self, in_channels): 180 | """Build the stem network.""" 181 | # Build the first conv and maxpooling layers. 182 | self.conv1 = ConvModule( 183 | in_channels, 184 | 64, 185 | kernel_size=7, 186 | stride=2, 187 | padding=3, 188 | conv_cfg=self.conv_cfg, 189 | norm_cfg=self.norm_cfg) 190 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 191 | 192 | # Build the initial level 2 blocks. 193 | self.init_block1 = make_res_layer( 194 | self._init_block_fn, 195 | 64, 196 | int(FILTER_SIZE_MAP[2] * self._filter_size_scale), 197 | self._block_repeats, 198 | conv_cfg=self.conv_cfg, 199 | norm_cfg=self.norm_cfg) 200 | self.init_block2 = make_res_layer( 201 | self._init_block_fn, 202 | int(FILTER_SIZE_MAP[2] * self._filter_size_scale) * 4, 203 | int(FILTER_SIZE_MAP[2] * self._filter_size_scale), 204 | self._block_repeats, 205 | conv_cfg=self.conv_cfg, 206 | norm_cfg=self.norm_cfg) 207 | 208 | def _make_endpoints(self): 209 | self.endpoint_convs = nn.ModuleDict() 210 | for block_spec in self._block_specs: 211 | if block_spec.is_output: 212 | in_channels = int(FILTER_SIZE_MAP[block_spec.level]*self._filter_size_scale) * 4 213 | self.endpoint_convs[str(block_spec.level)] = ConvModule(in_channels, 214 | self._endpoints_num_filters, 215 | kernel_size=1, 216 | norm_cfg=self.norm_cfg, 217 | act_cfg=None) 218 | 219 | def _make_scale_permuted_network(self): 220 | self.merge_ops = nn.ModuleList() 221 | self.scale_permuted_blocks = nn.ModuleList() 222 | for spec in self._block_specs: 223 | self.merge_ops.append( 224 | Merge(spec, self.norm_cfg, self._resample_alpha, self._filter_size_scale) 225 | ) 226 | channels = int(FILTER_SIZE_MAP[spec.level] * self._filter_size_scale) 227 | in_channels = channels * 4 if spec.block_fn == Bottleneck else channels 228 | self.scale_permuted_blocks.append( 229 | make_res_layer(spec.block_fn, 230 | in_channels, 231 | channels, 232 | self._block_repeats, 233 | conv_cfg=self.conv_cfg, 234 | norm_cfg=self.norm_cfg) 235 | ) 236 | 237 | def init_weights(self, pretrained=None): 238 | for m in self.modules(): 239 | if isinstance(m, nn.Conv2d): 240 | kaiming_init(m) 241 | elif isinstance(m, (_BatchNorm, nn.GroupNorm)): 242 | constant_init(m, 1) 243 | if self.zero_init_residual: 244 | for m in self.modules(): 245 | if isinstance(m, Bottleneck): 246 | constant_init(m.norm3, 0) 247 | elif isinstance(m, BasicBlock): 248 | constant_init(m.norm2, 0) 249 | 250 | def forward(self, input): 251 | feat = self.maxpool(self.conv1(input)) 252 | feat1 = self.init_block1(feat) 253 | feat2 = self.init_block2(feat1) 254 | block_feats = [feat1, feat2] 255 | output_feat = {} 256 | num_outgoing_connections = [0, 0] 257 | 258 | for i, spec in enumerate(self._block_specs): 259 | target_feat = self.merge_ops[i]([block_feats[feat_idx] for feat_idx in spec.input_offsets]) 260 | # Connect intermediate blocks with outdegree 0 to the output block. 261 | if spec.is_output: 262 | for j, (j_feat, j_connections) in enumerate( 263 | zip(block_feats, num_outgoing_connections)): 264 | if j_connections == 0 and j_feat.shape == target_feat.shape: 265 | target_feat += j_feat 266 | num_outgoing_connections[j] += 1 267 | target_feat = F.relu(target_feat, inplace=True) 268 | target_feat = self.scale_permuted_blocks[i](target_feat) 269 | block_feats.append(target_feat) 270 | num_outgoing_connections.append(0) 271 | for feat_idx in spec.input_offsets: 272 | num_outgoing_connections[feat_idx] += 1 273 | if spec.is_output: 274 | output_feat[spec.level] = target_feat 275 | 276 | return [self.endpoint_convs[str(level)](output_feat[level]) for level in self.output_level] 277 | --------------------------------------------------------------------------------