├── .github ├── CODE_OF_CONDUCT.md └── CONTRIBUTING.md ├── .gitignore ├── LICENSE ├── README.md ├── denseCL.png ├── densecl ├── __init__.py ├── builder.py ├── cross_entropy.py ├── cutmix.py ├── loader.py ├── resnet.py └── rince.py ├── detection ├── README.md ├── configs │ ├── Base-RCNN-C4-BN.yaml │ ├── coco_R_50_C4_2x.yaml │ ├── coco_R_50_C4_2x_moco.yaml │ ├── pascal_voc_R_101_C4_24k_moco.yaml │ ├── pascal_voc_R_50_C4_24k.yaml │ └── pascal_voc_R_50_C4_24k_moco.yaml ├── convert-pretrain-to-detectron2.py ├── datasets ├── dist_train.sh └── train_net.py ├── dist_train.sh ├── main_densecl.py └── main_lincls.py /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to moco 2 | We want to make contributing to this project as easy and transparent as 3 | possible. 4 | 5 | ## Pull Requests 6 | We actively welcome your pull requests. 7 | But note that this is a research project for reproducing results in a paper, 8 | we may not accept PRs adding new features if they do not align with the goal of reproducing 9 | results in the paper. 10 | 11 | If you haven't already, complete the Contributor License Agreement ("CLA") before sending a pull 12 | request. 13 | 14 | ## Contributor License Agreement ("CLA") 15 | In order to accept your pull request, we need you to submit a CLA. You only need 16 | to do this once to work on any of Facebook's open source projects. 17 | 18 | Complete your CLA here: 19 | 20 | ## Issues 21 | We use GitHub issues to track public bugs. Please ensure your description is 22 | clear and has sufficient instructions to be able to reproduce the issue. 23 | 24 | Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe 25 | disclosure of security bugs. In those cases, please go through the process 26 | outlined on that page and do not file a public issue. 27 | 28 | ## License 29 | By contributing to moco, you agree that your contributions will be licensed 30 | under the LICENSE file in the root directory of this source tree. 31 | -------------------------------------------------------------------------------- /.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 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | wheels/ 22 | pip-wheel-metadata/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | db.sqlite3-journal 62 | 63 | # Flask stuff: 64 | instance/ 65 | .webassets-cache 66 | 67 | # Scrapy stuff: 68 | .scrapy 69 | 70 | # Sphinx documentation 71 | docs/_build/ 72 | 73 | # PyBuilder 74 | target/ 75 | 76 | # Jupyter Notebook 77 | .ipynb_checkpoints 78 | 79 | # IPython 80 | profile_default/ 81 | ipython_config.py 82 | 83 | # pyenv 84 | .python-version 85 | 86 | # pipenv 87 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 88 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 89 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 90 | # install all needed dependencies. 91 | #Pipfile.lock 92 | 93 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 94 | __pypackages__/ 95 | 96 | # Celery stuff 97 | celerybeat-schedule 98 | celerybeat.pid 99 | 100 | # SageMath parsed files 101 | *.sage.py 102 | 103 | # Environments 104 | .env 105 | .venv 106 | env/ 107 | venv/ 108 | ENV/ 109 | env.bak/ 110 | venv.bak/ 111 | 112 | # Spyder project settings 113 | .spyderproject 114 | .spyproject 115 | 116 | # Rope project settings 117 | .ropeproject 118 | 119 | # mkdocs documentation 120 | /site 121 | 122 | # mypy 123 | .mypy_cache/ 124 | .dmypy.json 125 | dmypy.json 126 | 127 | # Pyre type checker 128 | .pyre/ 129 | 130 | 131 | ## Coin: 132 | res/ 133 | *pth 134 | dist_train_1.sh 135 | dist_train_2.sh 136 | *tar 137 | detection/output/ 138 | *pkl 139 | pretrained/ 140 | detection/output_denseCL_200ep.pkl 141 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | Section 1 -- Definitions. 71 | 72 | a. Adapted Material means material subject to Copyright and Similar 73 | Rights that is derived from or based upon the Licensed Material 74 | and in which the Licensed Material is translated, altered, 75 | arranged, transformed, or otherwise modified in a manner requiring 76 | permission under the Copyright and Similar Rights held by the 77 | Licensor. For purposes of this Public License, where the Licensed 78 | Material is a musical work, performance, or sound recording, 79 | Adapted Material is always produced where the Licensed Material is 80 | synched in timed relation with a moving image. 81 | 82 | b. Adapter's License means the license You apply to Your Copyright 83 | and Similar Rights in Your contributions to Adapted Material in 84 | accordance with the terms and conditions of this Public License. 85 | 86 | c. Copyright and Similar Rights means copyright and/or similar rights 87 | closely related to copyright including, without limitation, 88 | performance, broadcast, sound recording, and Sui Generis Database 89 | Rights, without regard to how the rights are labeled or 90 | categorized. For purposes of this Public License, the rights 91 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 92 | Rights. 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. NonCommercial means not primarily intended for or directed towards 116 | commercial advantage or monetary compensation. For purposes of 117 | this Public License, the exchange of the Licensed Material for 118 | other material subject to Copyright and Similar Rights by digital 119 | file-sharing or similar means is NonCommercial provided there is 120 | no payment of monetary compensation in connection with the 121 | exchange. 122 | 123 | j. Share means to provide material to the public by any means or 124 | process that requires permission under the Licensed Rights, such 125 | as reproduction, public display, public performance, distribution, 126 | dissemination, communication, or importation, and to make material 127 | available to the public including in ways that members of the 128 | public may access the material from a place and at a time 129 | individually chosen by them. 130 | 131 | k. Sui Generis Database Rights means rights other than copyright 132 | resulting from Directive 96/9/EC of the European Parliament and of 133 | the Council of 11 March 1996 on the legal protection of databases, 134 | as amended and/or succeeded, as well as other essentially 135 | equivalent rights anywhere in the world. 136 | 137 | l. You means the individual or entity exercising the Licensed Rights 138 | under this Public License. Your has a corresponding meaning. 139 | 140 | Section 2 -- Scope. 141 | 142 | a. License grant. 143 | 144 | 1. Subject to the terms and conditions of this Public License, 145 | the Licensor hereby grants You a worldwide, royalty-free, 146 | non-sublicensable, non-exclusive, irrevocable license to 147 | exercise the Licensed Rights in the Licensed Material to: 148 | 149 | a. reproduce and Share the Licensed Material, in whole or 150 | in part, for NonCommercial purposes only; and 151 | 152 | b. produce, reproduce, and Share Adapted Material for 153 | NonCommercial purposes only. 154 | 155 | 2. Exceptions and Limitations. For the avoidance of doubt, where 156 | Exceptions and Limitations apply to Your use, this Public 157 | License does not apply, and You do not need to comply with 158 | its terms and conditions. 159 | 160 | 3. Term. The term of this Public License is specified in Section 161 | 6(a). 162 | 163 | 4. Media and formats; technical modifications allowed. The 164 | Licensor authorizes You to exercise the Licensed Rights in 165 | all media and formats whether now known or hereafter created, 166 | and to make technical modifications necessary to do so. The 167 | Licensor waives and/or agrees not to assert any right or 168 | authority to forbid You from making technical modifications 169 | necessary to exercise the Licensed Rights, including 170 | technical modifications necessary to circumvent Effective 171 | Technological Measures. For purposes of this Public License, 172 | simply making modifications authorized by this Section 2(a) 173 | (4) never produces Adapted Material. 174 | 175 | 5. Downstream recipients. 176 | 177 | a. Offer from the Licensor -- Licensed Material. Every 178 | recipient of the Licensed Material automatically 179 | receives an offer from the Licensor to exercise the 180 | Licensed Rights under the terms and conditions of this 181 | Public License. 182 | 183 | b. No downstream restrictions. You may not offer or impose 184 | any additional or different terms or conditions on, or 185 | apply any Effective Technological Measures to, the 186 | Licensed Material if doing so restricts exercise of the 187 | Licensed Rights by any recipient of the Licensed 188 | Material. 189 | 190 | 6. No endorsement. Nothing in this Public License constitutes or 191 | may be construed as permission to assert or imply that You 192 | are, or that Your use of the Licensed Material is, connected 193 | with, or sponsored, endorsed, or granted official status by, 194 | the Licensor or others designated to receive attribution as 195 | provided in Section 3(a)(1)(A)(i). 196 | 197 | b. Other rights. 198 | 199 | 1. Moral rights, such as the right of integrity, are not 200 | licensed under this Public License, nor are publicity, 201 | privacy, and/or other similar personality rights; however, to 202 | the extent possible, the Licensor waives and/or agrees not to 203 | assert any such rights held by the Licensor to the limited 204 | extent necessary to allow You to exercise the Licensed 205 | Rights, but not otherwise. 206 | 207 | 2. Patent and trademark rights are not licensed under this 208 | Public License. 209 | 210 | 3. To the extent possible, the Licensor waives any right to 211 | collect royalties from You for the exercise of the Licensed 212 | Rights, whether directly or through a collecting society 213 | under any voluntary or waivable statutory or compulsory 214 | licensing scheme. In all other cases the Licensor expressly 215 | reserves any right to collect such royalties, including when 216 | the Licensed Material is used other than for NonCommercial 217 | purposes. 218 | 219 | Section 3 -- License Conditions. 220 | 221 | Your exercise of the Licensed Rights is expressly made subject to the 222 | following conditions. 223 | 224 | a. Attribution. 225 | 226 | 1. If You Share the Licensed Material (including in modified 227 | form), You must: 228 | 229 | a. retain the following if it is supplied by the Licensor 230 | with the Licensed Material: 231 | 232 | i. identification of the creator(s) of the Licensed 233 | Material and any others designated to receive 234 | attribution, in any reasonable manner requested by 235 | the Licensor (including by pseudonym if 236 | designated); 237 | 238 | ii. a copyright notice; 239 | 240 | iii. a notice that refers to this Public License; 241 | 242 | iv. a notice that refers to the disclaimer of 243 | warranties; 244 | 245 | v. a URI or hyperlink to the Licensed Material to the 246 | extent reasonably practicable; 247 | 248 | b. indicate if You modified the Licensed Material and 249 | retain an indication of any previous modifications; and 250 | 251 | c. indicate the Licensed Material is licensed under this 252 | Public License, and include the text of, or the URI or 253 | hyperlink to, this Public License. 254 | 255 | 2. You may satisfy the conditions in Section 3(a)(1) in any 256 | reasonable manner based on the medium, means, and context in 257 | which You Share the Licensed Material. For example, it may be 258 | reasonable to satisfy the conditions by providing a URI or 259 | hyperlink to a resource that includes the required 260 | information. 261 | 262 | 3. If requested by the Licensor, You must remove any of the 263 | information required by Section 3(a)(1)(A) to the extent 264 | reasonably practicable. 265 | 266 | 4. If You Share Adapted Material You produce, the Adapter's 267 | License You apply must not prevent recipients of the Adapted 268 | Material from complying with this Public License. 269 | 270 | Section 4 -- Sui Generis Database Rights. 271 | 272 | Where the Licensed Rights include Sui Generis Database Rights that 273 | apply to Your use of the Licensed Material: 274 | 275 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 276 | to extract, reuse, reproduce, and Share all or a substantial 277 | portion of the contents of the database for NonCommercial purposes 278 | only; 279 | 280 | b. if You include all or a substantial portion of the database 281 | contents in a database in which You have Sui Generis Database 282 | Rights, then the database in which You have Sui Generis Database 283 | Rights (but not its individual contents) is Adapted Material; and 284 | 285 | c. You must comply with the conditions in Section 3(a) if You Share 286 | all or a substantial portion of the contents of the database. 287 | 288 | For the avoidance of doubt, this Section 4 supplements and does not 289 | replace Your obligations under this Public License where the Licensed 290 | Rights include other Copyright and Similar Rights. 291 | 292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 293 | 294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 304 | 305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 314 | 315 | c. The disclaimer of warranties and limitation of liability provided 316 | above shall be interpreted in a manner that, to the extent 317 | possible, most closely approximates an absolute disclaimer and 318 | waiver of all liability. 319 | 320 | Section 6 -- Term and Termination. 321 | 322 | a. This Public License applies for the term of the Copyright and 323 | Similar Rights licensed here. However, if You fail to comply with 324 | this Public License, then Your rights under this Public License 325 | terminate automatically. 326 | 327 | b. Where Your right to use the Licensed Material has terminated under 328 | Section 6(a), it reinstates: 329 | 330 | 1. automatically as of the date the violation is cured, provided 331 | it is cured within 30 days of Your discovery of the 332 | violation; or 333 | 334 | 2. upon express reinstatement by the Licensor. 335 | 336 | For the avoidance of doubt, this Section 6(b) does not affect any 337 | right the Licensor may have to seek remedies for Your violations 338 | of this Public License. 339 | 340 | c. For the avoidance of doubt, the Licensor may also offer the 341 | Licensed Material under separate terms or conditions or stop 342 | distributing the Licensed Material at any time; however, doing so 343 | will not terminate this Public License. 344 | 345 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 346 | License. 347 | 348 | Section 7 -- Other Terms and Conditions. 349 | 350 | a. The Licensor shall not be bound by any additional or different 351 | terms or conditions communicated by You unless expressly agreed. 352 | 353 | b. Any arrangements, understandings, or agreements regarding the 354 | Licensed Material not stated herein are separate from and 355 | independent of the terms and conditions of this Public License. 356 | 357 | Section 8 -- Interpretation. 358 | 359 | a. For the avoidance of doubt, this Public License does not, and 360 | shall not be interpreted to, reduce, limit, restrict, or impose 361 | conditions on any use of the Licensed Material that could lawfully 362 | be made without permission under this Public License. 363 | 364 | b. To the extent possible, if any provision of this Public License is 365 | deemed unenforceable, it shall be automatically reformed to the 366 | minimum extent necessary to make it enforceable. If the provision 367 | cannot be reformed, it shall be severed from this Public License 368 | without affecting the enforceability of the remaining terms and 369 | conditions. 370 | 371 | c. No term or condition of this Public License will be waived and no 372 | failure to comply consented to unless expressly agreed to by the 373 | Licensor. 374 | 375 | d. Nothing in this Public License constitutes or may be interpreted 376 | as a limitation upon, or waiver of, any privileges and immunities 377 | that apply to the Licensor or You, including from the legal 378 | processes of any jurisdiction or authority. 379 | 380 | ======================================================================= 381 | 382 | Creative Commons is not a party to its public 383 | licenses. Notwithstanding, Creative Commons may elect to apply one of 384 | its public licenses to material it publishes and in those instances 385 | will be considered the “Licensor.” The text of the Creative Commons 386 | public licenses is dedicated to the public domain under the CC0 Public 387 | Domain Dedication. Except for the limited purpose of indicating that 388 | material is shared under a Creative Commons public license or as 389 | otherwise permitted by the Creative Commons policies published at 390 | creativecommons.org/policies, Creative Commons does not authorize the 391 | use of the trademark "Creative Commons" or any other trademark or logo 392 | of Creative Commons without its prior written consent including, 393 | without limitation, in connection with any unauthorized modifications 394 | to any of its public licenses or any other arrangements, 395 | understandings, or agreements concerning use of licensed material. For 396 | the avoidance of doubt, this paragraph does not form part of the 397 | public licenses. 398 | 399 | Creative Commons may be contacted at creativecommons.org. 400 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## DenseCL: Dense Contrastive Learning for Self-Supervised Visual Pre-Training 2 | 3 | 4 |

5 | 6 |

7 | 8 | This is an unofficial PyTorch implementation of the [DenseCL paper](https://arxiv.org/abs/2011.09157), with the help and suggestions from @WXinlong and @DerrickWang005. 9 | 10 | Currently, [regionCL-D](https://arxiv.org/abs/2111.12309) is added, and pretrained checkpoints are uploaded. 11 | 12 | 13 | ### Preparation 14 | 15 | Install PyTorch and ImageNet dataset following the [official PyTorch ImageNet training code](https://github.com/pytorch/examples/tree/master/imagenet). 16 | 17 | This repo aims to be minimal modifications on that code. Check the modifications by: 18 | ``` 19 | diff main_densecl.py <(curl https://raw.githubusercontent.com/pytorch/examples/master/imagenet/main.py) 20 | diff main_lincls.py <(curl https://raw.githubusercontent.com/pytorch/examples/master/imagenet/main.py) 21 | ``` 22 | 23 | 24 | ### Unsupervised Training & Linear Classification 25 | 26 | This implementation only supports **multi-gpu**, **DistributedDataParallel** training, which is faster and simpler; single-gpu or DataParallel training is not supported. 27 | 28 | This implementation only supports **ResNet50/ResNet101**, since we need to modify computing graph architecture and I only modified ResNet50/ResNet101. 29 | 30 | To do unsupervised pre-training and linear-evaluation of a ResNet50/ResNet101 model on ImageNet in an 8-gpu machine, please refer to [dist_train.sh](./dist_train.sh) for relevant starting script. 31 | 32 | Since the paper says they use default mocov2 hyper-parameters, the above script uses same hyper-parameters as mocov2. 33 | 34 | ***Note***: for 4-gpu training, we recommend following the [linear lr scaling recipe](https://arxiv.org/abs/1706.02677): `--lr 0.015 --batch-size 128` with 4 gpus. We got similar results using this setting. 35 | 36 | 37 | ### Models 38 | 39 | Our pre-trained denseCL/RegionCL-D models can be downloaded as following: 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 |
epochsmlpaug+cosIM
top1
VOC
AP50
modelmd5
MoCov2 R5020067.782.4download59fd9945
DenseCL R5020063.882.7download7cfc894c
DenseCL R10120065.483.5download006675e5
RegionCL-D R5020067.583.3download8afad30e
RegionCL-D R10120067.584.3downloada1489ad4
104 | 105 | Here **IM** is imagenet-1k dataset. We freeze pretrained weights and only fine tune the last classifier layer. 106 | 107 | Please be aware that though DenseCL cannot match mocov2 in the filed of classification, it is superior to mocov2 in terms of object detection. More results of detection can be found [here](./detection). 108 | 109 | 110 | ### Transferring to Object Detection 111 | 112 | For details, see [./detection](./detection). 113 | 114 | 115 | ### License 116 | 117 | This project is under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for details. 118 | 119 | 120 | 121 | regioncl, r50: 122 | Acc@1 67.518 Acc@5 88.256 123 | Acc@1 67.534 Acc@5 88.212 124 | regioncl, r101: 125 | Acc@1 67.504 Acc@5 88.212 126 | Acc@1 67.470 Acc@5 88.104 127 | 128 | -------------------------------------------------------------------------------- /denseCL.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoinCheung/DenseCL/722d75cb32fa69b885212ea7efc10786f916b582/denseCL.png -------------------------------------------------------------------------------- /densecl/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | -------------------------------------------------------------------------------- /densecl/builder.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | import torch 3 | import torch.nn as nn 4 | 5 | from .cutmix import CutMixer 6 | 7 | 8 | 9 | class DenseCL(nn.Module): 10 | """ 11 | Build a DenseCL model with: a query encoder, a key encoder, and a queue 12 | https://arxiv.org/abs/2011.09157 13 | """ 14 | def __init__(self, base_model, dim=128, K=65536, m=0.999, T=0.07, mlp=False, cutmix=False): 15 | """ 16 | dim: feature dimension (default: 128) 17 | K: queue size; number of negative keys (default: 65536) 18 | m: moco momentum of updating key encoder (default: 0.999) 19 | T: softmax temperature (default: 0.07) 20 | """ 21 | super(DenseCL, self).__init__() 22 | 23 | self.cutmixer = CutMixer(T=T) if cutmix else None 24 | 25 | self.K = K 26 | self.m = m 27 | self.T = T 28 | 29 | # create the encoders 30 | # num_classes is the output fc dimension 31 | 32 | self.encoder_q = base_model(num_classes=dim) 33 | self.encoder_k = base_model(num_classes=dim) 34 | 35 | if mlp: # hack: brute-force replacement 36 | dim_mlp = self.encoder_q.fc.weight.shape[1] 37 | self.encoder_q.fc = nn.Sequential(nn.Linear(dim_mlp, dim_mlp), nn.ReLU(), self.encoder_q.fc) 38 | self.encoder_k.fc = nn.Sequential(nn.Linear(dim_mlp, dim_mlp), nn.ReLU(), self.encoder_k.fc) 39 | 40 | 41 | for param_q, param_k in zip(self.encoder_q.parameters(), self.encoder_k.parameters()): 42 | param_k.data.copy_(param_q.data) # initialize 43 | param_k.requires_grad = False # not update by gradient 44 | 45 | # create the queue 46 | self.register_buffer("queue", torch.randn(dim, K)) 47 | self.register_buffer("queue_dense", torch.randn(dim, K)) 48 | self.queue = nn.functional.normalize(self.queue, dim=0) 49 | self.queue_dense = nn.functional.normalize(self.queue_dense, dim=0) 50 | 51 | self.register_buffer("queue_ptr", torch.zeros(1, dtype=torch.long)) 52 | 53 | self.crit_cls = nn.CrossEntropyLoss() 54 | self.crit_dense = nn.CrossEntropyLoss() 55 | 56 | @torch.no_grad() 57 | def _momentum_update_key_encoder(self): 58 | """ 59 | Momentum update of the key encoder 60 | """ 61 | for param_q, param_k in zip(self.encoder_q.parameters(), self.encoder_k.parameters()): 62 | param_k.data = param_k.data * self.m + param_q.data * (1. - self.m) 63 | 64 | @torch.no_grad() 65 | def _dequeue_and_enqueue(self, keys, dense_keys): 66 | # gather keys before updating queue 67 | keys = concat_all_gather(keys) 68 | dense_keys = nn.functional.normalize(dense_keys.mean(dim=2), dim=1) 69 | dense_keys = concat_all_gather(dense_keys) 70 | 71 | batch_size = keys.shape[0] 72 | 73 | ptr = int(self.queue_ptr) 74 | assert self.K % batch_size == 0 # for simplicity 75 | 76 | # replace the keys at ptr (dequeue and enqueue) 77 | self.queue[:, ptr:ptr + batch_size] = keys.T 78 | self.queue_dense[:, ptr:ptr + batch_size] = dense_keys.T 79 | ptr = (ptr + batch_size) % self.K # move pointer 80 | 81 | self.queue_ptr[0] = ptr 82 | 83 | @torch.no_grad() 84 | def _batch_shuffle_ddp(self, x): 85 | """ 86 | Batch shuffle, for making use of BatchNorm. 87 | *** Only support DistributedDataParallel (DDP) model. *** 88 | """ 89 | # gather from all gpus 90 | batch_size_this = x.shape[0] 91 | x_gather = concat_all_gather(x) 92 | batch_size_all = x_gather.shape[0] 93 | 94 | num_gpus = batch_size_all // batch_size_this 95 | 96 | # random shuffle index 97 | idx_shuffle = torch.randperm(batch_size_all).cuda() 98 | 99 | # broadcast to all gpus 100 | torch.distributed.broadcast(idx_shuffle, src=0) 101 | 102 | # index for restoring 103 | idx_unshuffle = torch.argsort(idx_shuffle) 104 | 105 | # shuffled index for this gpu 106 | gpu_idx = torch.distributed.get_rank() 107 | idx_this = idx_shuffle.view(num_gpus, -1)[gpu_idx] 108 | 109 | return x_gather[idx_this], idx_unshuffle 110 | 111 | @torch.no_grad() 112 | def _batch_unshuffle_ddp(self, x, feat_k, dense_k_norm, idx_unshuffle): 113 | """ 114 | Undo batch shuffle. 115 | *** Only support DistributedDataParallel (DDP) model. *** 116 | """ 117 | # gather from all gpus 118 | batch_size_this = x.shape[0] 119 | x_gather = concat_all_gather(x) 120 | feat_k_gather = concat_all_gather(feat_k) 121 | dense_k_norm_gather = concat_all_gather(dense_k_norm) 122 | batch_size_all = x_gather.shape[0] 123 | 124 | num_gpus = batch_size_all // batch_size_this 125 | 126 | # restored index for this gpu 127 | gpu_idx = torch.distributed.get_rank() 128 | idx_this = idx_unshuffle.view(num_gpus, -1)[gpu_idx] 129 | 130 | return x_gather[idx_this], feat_k_gather[idx_this], dense_k_norm_gather[idx_this] 131 | 132 | def forward(self, im_q, im_k): 133 | """ 134 | Input: 135 | im_q: a batch of query images 136 | im_k: a batch of key images 137 | Output: 138 | logits, targets 139 | """ 140 | 141 | # compute query features 142 | q, dense_q, feat_q = self.encoder_q(im_q) # queries: NxC 143 | q = nn.functional.normalize(q, dim=1) 144 | n, c, h, w = feat_q.size() 145 | dim_dense = dense_q.size(1) 146 | dense_q, feat_q = dense_q.view(n, dim_dense, -1), feat_q.view(n, c, -1) 147 | dense_q = nn.functional.normalize(dense_q, dim=1) 148 | 149 | # compute key features 150 | with torch.no_grad(): # no gradient to keys 151 | self._momentum_update_key_encoder() # update the key encoder 152 | 153 | # shuffle for making use of BN 154 | im_k, idx_unshuffle = self._batch_shuffle_ddp(im_k) 155 | 156 | k, dense_k, feat_k = self.encoder_k(im_k) # keys: NxC 157 | k = nn.functional.normalize(k, dim=1) 158 | dense_k, feat_k = dense_k.view(n, dim_dense, -1), feat_k.view(n, c, -1) 159 | dense_k_norm = nn.functional.normalize(dense_k, dim=1) 160 | 161 | # undo shuffle 162 | k, feat_k, dense_k_norm = self._batch_unshuffle_ddp( 163 | k, feat_k, dense_k_norm, idx_unshuffle) 164 | 165 | ## match 166 | feat_q_norm = nn.functional.normalize(feat_q, dim=1) 167 | feat_k_norm = nn.functional.normalize(feat_k, dim=1) 168 | cosine = torch.einsum('nca,ncb->nab', feat_q_norm, feat_k_norm) 169 | pos_idx = cosine.argmax(dim=-1) 170 | dense_k_norm = dense_k_norm.gather(2, pos_idx.unsqueeze(1).expand(-1, dim_dense, -1)) 171 | 172 | # compute logits 173 | # Einstein sum is more intuitive 174 | # positive logits: Nx1 175 | l_pos = torch.einsum('nc,nc->n', [q, k]).unsqueeze(-1) 176 | # negative logits: NxK 177 | l_neg = torch.einsum('nc,ck->nk', [q, self.queue.clone().detach()]) 178 | 179 | # logits: Nx(1+K) 180 | logits = torch.cat([l_pos, l_neg], dim=1) 181 | # apply temperature 182 | logits /= self.T 183 | # labels: positive key indicators 184 | labels = torch.zeros(logits.shape[0], dtype=torch.long).cuda() 185 | 186 | loss_cls = self.crit_cls(logits, labels) 187 | 188 | 189 | ## densecl logits 190 | d_pos = torch.einsum('ncm,ncm->nm', dense_q, dense_k_norm).unsqueeze(1) 191 | d_neg = torch.einsum('ncm,ck->nkm', dense_q, self.queue_dense.clone().detach()) 192 | 193 | logits_dense = torch.cat([d_pos, d_neg], dim=1) 194 | logits_dense = logits_dense / self.T 195 | labels_dense = torch.zeros((n, h*w), dtype=torch.long).cuda() 196 | 197 | loss_dense = self.crit_dense(logits_dense, labels_dense) 198 | 199 | extra = {'qk': [q, k], 'dense_qk': [dense_q, dense_k_norm], 200 | 'logits': logits , 'labels': labels} 201 | 202 | ## regionCL 203 | if self.cutmixer: 204 | loss_cutmix = self.cutmixer.forward_mix( 205 | self.encoder_q, im_q, q, k, self.queue.detach()) 206 | extra.update({'loss_cutmix': loss_cutmix}) 207 | 208 | # dequeue and enqueue 209 | self._dequeue_and_enqueue(k, dense_k) 210 | 211 | return loss_cls, loss_dense, extra 212 | 213 | 214 | 215 | # utils 216 | @torch.no_grad() 217 | def concat_all_gather(tensor): 218 | """ 219 | Performs all_gather operation on the provided tensors. 220 | *** Warning ***: torch.distributed.all_gather has no gradient. 221 | """ 222 | tensors_gather = [torch.ones_like(tensor) 223 | for _ in range(torch.distributed.get_world_size())] 224 | torch.distributed.all_gather(tensors_gather, tensor, async_op=False) 225 | 226 | output = torch.cat(tensors_gather, dim=0) 227 | return output 228 | -------------------------------------------------------------------------------- /densecl/cross_entropy.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | cross entropy loss with input specially designed for moco/densecl 4 | ''' 5 | 6 | import torch 7 | import torch.nn as nn 8 | import torch.nn.functional as F 9 | 10 | 11 | 12 | class CrossEntropyLoss(nn.Module): 13 | 14 | def __init__(self, ): 15 | super(CrossEntropyLoss, self).__init__() 16 | self.crit = nn.CrossEntropyLoss() 17 | 18 | def forward(self, pos, neg): 19 | N, _, *M = pos.size() 20 | logits = torch.cat([pos, neg], dim=1) 21 | labels = torch.zeros((N, *M), dtype=torch.long).cuda() 22 | loss = self.crit(logits, labels) 23 | return loss 24 | -------------------------------------------------------------------------------- /densecl/cutmix.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import torch 4 | import torch.nn as nn 5 | 6 | 7 | 8 | class CutMixer(nn.Module): 9 | 10 | def __init__(self, divisor=32, lower=3, upper=6, T=0.07): 11 | super(CutMixer, self).__init__() 12 | ''' 13 | cropsize is within [lower*32, upper*32) 14 | ''' 15 | self.divisor = divisor 16 | self.lower, self.upper = lower, upper 17 | self.T = T 18 | self.crit = nn.CrossEntropyLoss() 19 | 20 | ## TODO: see if use different crop for each images 21 | @torch.no_grad() 22 | def mix_img(self, ims): 23 | bs, C, H, W = ims.size() 24 | assert H % self.divisor == 0 and W % self.divisor == 0 25 | nh, nw = H // self.divisor, W // self.divisor 26 | h, w = torch.randint(self.lower, self.upper, (2, )).tolist() 27 | hst = torch.randint(0, nh-h, (1,))[0] 28 | wst = torch.randint(0, nw-w, (1,))[0] 29 | hst_, wst_ = hst * self.divisor, wst * self.divisor 30 | h_, w_ = h * self.divisor, w * self.divisor 31 | 32 | perm = torch.randperm(bs).cuda() 33 | perm_unshuf = perm.argsort() 34 | ims_mix = ims.clone() 35 | ims_mix[:, :, hst_:hst_+h_, wst_:wst_+w_] = ims[perm, :, hst_:hst_+h_, wst_:wst_+w_] 36 | return ims_mix.detach(), perm, perm_unshuf, h, w, hst, wst 37 | 38 | def forward_mix(self, model, ims, q, k, queue): 39 | mix_res = self.mix_img(ims) 40 | ims_mix, perm, perm_unshuf, h, w, hst, wst = mix_res 41 | 42 | p, c = model.forward_cutmix(mix_res) 43 | p = nn.functional.normalize(p, dim=1) 44 | c = nn.functional.normalize(c, dim=1) 45 | p_unshuf = p[perm_unshuf] 46 | 47 | queue = queue.clone().detach() 48 | p_pos = torch.einsum('nc,nc->n', p_unshuf, k).unsqueeze(-1) 49 | p_neg1 = torch.einsum('nc,ck->nk', p_unshuf, queue) 50 | p_neg2 = torch.einsum('nc,nc->n', p_unshuf, c[perm].detach()).unsqueeze(-1) 51 | p_neg = torch.cat([p_neg1, p_neg2], dim=1) 52 | 53 | c_pos = torch.einsum('nc,nc->n', c, k).unsqueeze(-1) 54 | c_neg1 = torch.einsum('nc,ck->nk', c, queue) 55 | c_neg2 = torch.einsum('nc,nc->n', c, p.detach()).unsqueeze(-1) 56 | c_neg = torch.cat([c_neg1, c_neg2], dim=1) 57 | 58 | cp_pos = torch.cat([p_pos, c_pos], dim=0) 59 | cp_neg = torch.cat([p_neg, c_neg], dim=0) 60 | 61 | logits = torch.cat([cp_pos, cp_neg], dim=1) 62 | logits /= self.T 63 | labels = torch.zeros(logits.shape[0], dtype=torch.long).cuda() 64 | loss = self.crit(logits, labels) 65 | return loss 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /densecl/loader.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | from PIL import ImageFilter 3 | import random 4 | 5 | 6 | class TwoCropsTransform: 7 | """Take two random crops of one image as the query and key.""" 8 | 9 | def __init__(self, base_transform): 10 | self.base_transform = base_transform 11 | 12 | def __call__(self, x): 13 | q = self.base_transform(x) 14 | k = self.base_transform(x) 15 | return [q, k] 16 | 17 | 18 | class GaussianBlur(object): 19 | """Gaussian blur augmentation in SimCLR https://arxiv.org/abs/2002.05709""" 20 | 21 | def __init__(self, sigma=[.1, 2.]): 22 | self.sigma = sigma 23 | 24 | def __call__(self, x): 25 | sigma = random.uniform(self.sigma[0], self.sigma[1]) 26 | x = x.filter(ImageFilter.GaussianBlur(radius=sigma)) 27 | return x 28 | -------------------------------------------------------------------------------- /densecl/resnet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | # from .utils import load_state_dict_from_url 4 | 5 | 6 | __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 7 | 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', 8 | 'wide_resnet50_2', 'wide_resnet101_2'] 9 | 10 | 11 | model_urls = { 12 | 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 13 | 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 14 | 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 15 | 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 16 | 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', 17 | 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth', 18 | 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth', 19 | 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth', 20 | 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth', 21 | } 22 | 23 | 24 | def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): 25 | """3x3 convolution with padding""" 26 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 27 | padding=dilation, groups=groups, bias=False, dilation=dilation) 28 | 29 | 30 | def conv1x1(in_planes, out_planes, stride=1): 31 | """1x1 convolution""" 32 | return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) 33 | 34 | 35 | class BasicBlock(nn.Module): 36 | expansion = 1 37 | 38 | def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, 39 | base_width=64, dilation=1, norm_layer=None): 40 | super(BasicBlock, self).__init__() 41 | if norm_layer is None: 42 | norm_layer = nn.BatchNorm2d 43 | if groups != 1 or base_width != 64: 44 | raise ValueError('BasicBlock only supports groups=1 and base_width=64') 45 | if dilation > 1: 46 | raise NotImplementedError("Dilation > 1 not supported in BasicBlock") 47 | # Both self.conv1 and self.downsample layers downsample the input when stride != 1 48 | self.conv1 = conv3x3(inplanes, planes, stride) 49 | self.bn1 = norm_layer(planes) 50 | self.relu = nn.ReLU(inplace=True) 51 | self.conv2 = conv3x3(planes, planes) 52 | self.bn2 = norm_layer(planes) 53 | self.downsample = downsample 54 | self.stride = stride 55 | 56 | def forward(self, x): 57 | identity = x 58 | 59 | out = self.conv1(x) 60 | out = self.bn1(out) 61 | out = self.relu(out) 62 | 63 | out = self.conv2(out) 64 | out = self.bn2(out) 65 | 66 | if self.downsample is not None: 67 | identity = self.downsample(x) 68 | 69 | out += identity 70 | out = self.relu(out) 71 | 72 | return out 73 | 74 | 75 | class Bottleneck(nn.Module): 76 | # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2) 77 | # while original implementation places the stride at the first 1x1 convolution(self.conv1) 78 | # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385. 79 | # This variant is also known as ResNet V1.5 and improves accuracy according to 80 | # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch. 81 | 82 | expansion = 4 83 | 84 | def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, 85 | base_width=64, dilation=1, norm_layer=None): 86 | super(Bottleneck, self).__init__() 87 | if norm_layer is None: 88 | norm_layer = nn.BatchNorm2d 89 | width = int(planes * (base_width / 64.)) * groups 90 | # Both self.conv2 and self.downsample layers downsample the input when stride != 1 91 | self.conv1 = conv1x1(inplanes, width) 92 | self.bn1 = norm_layer(width) 93 | self.conv2 = conv3x3(width, width, stride, groups, dilation) 94 | self.bn2 = norm_layer(width) 95 | self.conv3 = conv1x1(width, planes * self.expansion) 96 | self.bn3 = norm_layer(planes * self.expansion) 97 | self.relu = nn.ReLU(inplace=True) 98 | self.downsample = downsample 99 | self.stride = stride 100 | 101 | def forward(self, x): 102 | identity = x 103 | 104 | out = self.conv1(x) 105 | out = self.bn1(out) 106 | out = self.relu(out) 107 | 108 | out = self.conv2(out) 109 | out = self.bn2(out) 110 | out = self.relu(out) 111 | 112 | out = self.conv3(out) 113 | out = self.bn3(out) 114 | 115 | if self.downsample is not None: 116 | identity = self.downsample(x) 117 | 118 | out += identity 119 | out = self.relu(out) 120 | 121 | return out 122 | 123 | 124 | class ResNet(nn.Module): 125 | 126 | def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, 127 | groups=1, width_per_group=64, replace_stride_with_dilation=None, 128 | norm_layer=None): 129 | super(ResNet, self).__init__() 130 | if norm_layer is None: 131 | norm_layer = nn.BatchNorm2d 132 | self._norm_layer = norm_layer 133 | 134 | self.inplanes = 64 135 | self.dilation = 1 136 | if replace_stride_with_dilation is None: 137 | # each element in the tuple indicates if we should replace 138 | # the 2x2 stride with a dilated convolution instead 139 | replace_stride_with_dilation = [False, False, False] 140 | if len(replace_stride_with_dilation) != 3: 141 | raise ValueError("replace_stride_with_dilation should be None " 142 | "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) 143 | self.groups = groups 144 | self.base_width = width_per_group 145 | self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, 146 | bias=False) 147 | self.bn1 = norm_layer(self.inplanes) 148 | self.relu = nn.ReLU(inplace=True) 149 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 150 | self.layer1 = self._make_layer(block, 64, layers[0]) 151 | self.layer2 = self._make_layer(block, 128, layers[1], stride=2, 152 | dilate=replace_stride_with_dilation[0]) 153 | self.layer3 = self._make_layer(block, 256, layers[2], stride=2, 154 | dilate=replace_stride_with_dilation[1]) 155 | self.layer4 = self._make_layer(block, 512, layers[3], stride=2, 156 | dilate=replace_stride_with_dilation[2]) 157 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) 158 | self.fc = nn.Linear(512 * block.expansion, num_classes) 159 | self.dense_head = nn.Sequential( 160 | nn.Conv2d(512 * block.expansion, 512 * block.expansion, 1, 1, 0, bias=True), 161 | nn.ReLU(inplace=True), 162 | nn.Conv2d(512 * block.expansion, num_classes, 1, 1, 0, bias=True) 163 | ) 164 | 165 | for m in self.modules(): 166 | if isinstance(m, nn.Conv2d): 167 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 168 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): 169 | nn.init.constant_(m.weight, 1) 170 | nn.init.constant_(m.bias, 0) 171 | 172 | # Zero-initialize the last BN in each residual branch, 173 | # so that the residual branch starts with zeros, and each residual block behaves like an identity. 174 | # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 175 | if zero_init_residual: 176 | for m in self.modules(): 177 | if isinstance(m, Bottleneck): 178 | nn.init.constant_(m.bn3.weight, 0) 179 | elif isinstance(m, BasicBlock): 180 | nn.init.constant_(m.bn2.weight, 0) 181 | 182 | def _make_layer(self, block, planes, blocks, stride=1, dilate=False): 183 | norm_layer = self._norm_layer 184 | downsample = None 185 | previous_dilation = self.dilation 186 | if dilate: 187 | self.dilation *= stride 188 | stride = 1 189 | if stride != 1 or self.inplanes != planes * block.expansion: 190 | downsample = nn.Sequential( 191 | conv1x1(self.inplanes, planes * block.expansion, stride), 192 | norm_layer(planes * block.expansion), 193 | ) 194 | 195 | layers = [] 196 | layers.append(block(self.inplanes, planes, stride, downsample, self.groups, 197 | self.base_width, previous_dilation, norm_layer)) 198 | self.inplanes = planes * block.expansion 199 | for _ in range(1, blocks): 200 | layers.append(block(self.inplanes, planes, groups=self.groups, 201 | base_width=self.base_width, dilation=self.dilation, 202 | norm_layer=norm_layer)) 203 | 204 | return nn.Sequential(*layers) 205 | 206 | def forward_backbone(self, x): 207 | # See note [TorchScript super()] 208 | x = self.conv1(x) 209 | x = self.bn1(x) 210 | x = self.relu(x) 211 | x = self.maxpool(x) 212 | 213 | x = self.layer1(x) 214 | x = self.layer2(x) 215 | x = self.layer3(x) 216 | feat = self.layer4(x) 217 | return feat 218 | 219 | def _forward_impl(self, x): 220 | feat = self.forward_backbone(x) 221 | x = self.avgpool(feat) 222 | x = torch.flatten(x, 1) 223 | logits = self.fc(x) 224 | dense = self.dense_head(feat) 225 | 226 | return logits, dense, feat 227 | # return x 228 | 229 | def forward(self, x): 230 | return self._forward_impl(x) 231 | 232 | def forward_cutmix(self, mix_res): 233 | ims_mix, perm, perm_unshuf, h, w, hst, wst = mix_res 234 | feat = self.forward_backbone(ims_mix) 235 | bs, C, H, W = feat.size() 236 | num_p = h * w 237 | num_c = H * W - h * w 238 | mask = torch.zeros(1, 1, H, W).to(feat.device).detach() 239 | mask[:, :, hst:hst+h, wst:wst+w] = 1 240 | p = (feat * mask).sum(dim=(2, 3)).div(num_p) 241 | c = (feat * (1-mask)).sum(dim=(2, 3)).div(num_c) 242 | p = self.fc(p) 243 | c = self.fc(c) 244 | return p, c 245 | 246 | 247 | def _resnet(arch, block, layers, pretrained, progress, **kwargs): 248 | model = ResNet(block, layers, **kwargs) 249 | # if pretrained: 250 | # state_dict = load_state_dict_from_url(model_urls[arch], 251 | # progress=progress) 252 | # model.load_state_dict(state_dict) 253 | return model 254 | 255 | 256 | def resnet18(pretrained=False, progress=True, **kwargs): 257 | r"""ResNet-18 model from 258 | `"Deep Residual Learning for Image Recognition" `_ 259 | 260 | Args: 261 | pretrained (bool): If True, returns a model pre-trained on ImageNet 262 | progress (bool): If True, displays a progress bar of the download to stderr 263 | """ 264 | return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, 265 | **kwargs) 266 | 267 | 268 | def resnet34(pretrained=False, progress=True, **kwargs): 269 | r"""ResNet-34 model from 270 | `"Deep Residual Learning for Image Recognition" `_ 271 | 272 | Args: 273 | pretrained (bool): If True, returns a model pre-trained on ImageNet 274 | progress (bool): If True, displays a progress bar of the download to stderr 275 | """ 276 | return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, 277 | **kwargs) 278 | 279 | 280 | def resnet50(pretrained=False, progress=True, **kwargs): 281 | r"""ResNet-50 model from 282 | `"Deep Residual Learning for Image Recognition" `_ 283 | 284 | Args: 285 | pretrained (bool): If True, returns a model pre-trained on ImageNet 286 | progress (bool): If True, displays a progress bar of the download to stderr 287 | """ 288 | return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, 289 | **kwargs) 290 | 291 | 292 | def resnet101(pretrained=False, progress=True, **kwargs): 293 | r"""ResNet-101 model from 294 | `"Deep Residual Learning for Image Recognition" `_ 295 | 296 | Args: 297 | pretrained (bool): If True, returns a model pre-trained on ImageNet 298 | progress (bool): If True, displays a progress bar of the download to stderr 299 | """ 300 | return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, 301 | **kwargs) 302 | 303 | 304 | def resnet152(pretrained=False, progress=True, **kwargs): 305 | r"""ResNet-152 model from 306 | `"Deep Residual Learning for Image Recognition" `_ 307 | 308 | Args: 309 | pretrained (bool): If True, returns a model pre-trained on ImageNet 310 | progress (bool): If True, displays a progress bar of the download to stderr 311 | """ 312 | return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress, 313 | **kwargs) 314 | 315 | 316 | def resnext50_32x4d(pretrained=False, progress=True, **kwargs): 317 | r"""ResNeXt-50 32x4d model from 318 | `"Aggregated Residual Transformation for Deep Neural Networks" `_ 319 | 320 | Args: 321 | pretrained (bool): If True, returns a model pre-trained on ImageNet 322 | progress (bool): If True, displays a progress bar of the download to stderr 323 | """ 324 | kwargs['groups'] = 32 325 | kwargs['width_per_group'] = 4 326 | return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3], 327 | pretrained, progress, **kwargs) 328 | 329 | 330 | def resnext101_32x8d(pretrained=False, progress=True, **kwargs): 331 | r"""ResNeXt-101 32x8d model from 332 | `"Aggregated Residual Transformation for Deep Neural Networks" `_ 333 | 334 | Args: 335 | pretrained (bool): If True, returns a model pre-trained on ImageNet 336 | progress (bool): If True, displays a progress bar of the download to stderr 337 | """ 338 | kwargs['groups'] = 32 339 | kwargs['width_per_group'] = 8 340 | return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3], 341 | pretrained, progress, **kwargs) 342 | 343 | 344 | def wide_resnet50_2(pretrained=False, progress=True, **kwargs): 345 | r"""Wide ResNet-50-2 model from 346 | `"Wide Residual Networks" `_ 347 | 348 | The model is the same as ResNet except for the bottleneck number of channels 349 | which is twice larger in every block. The number of channels in outer 1x1 350 | convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 351 | channels, and in Wide ResNet-50-2 has 2048-1024-2048. 352 | 353 | Args: 354 | pretrained (bool): If True, returns a model pre-trained on ImageNet 355 | progress (bool): If True, displays a progress bar of the download to stderr 356 | """ 357 | kwargs['width_per_group'] = 64 * 2 358 | return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3], 359 | pretrained, progress, **kwargs) 360 | 361 | 362 | def wide_resnet101_2(pretrained=False, progress=True, **kwargs): 363 | r"""Wide ResNet-101-2 model from 364 | `"Wide Residual Networks" `_ 365 | 366 | The model is the same as ResNet except for the bottleneck number of channels 367 | which is twice larger in every block. The number of channels in outer 1x1 368 | convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 369 | channels, and in Wide ResNet-50-2 has 2048-1024-2048. 370 | 371 | Args: 372 | pretrained (bool): If True, returns a model pre-trained on ImageNet 373 | progress (bool): If True, displays a progress bar of the download to stderr 374 | """ 375 | kwargs['width_per_group'] = 64 * 2 376 | return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3], 377 | pretrained, progress, **kwargs) 378 | -------------------------------------------------------------------------------- /densecl/rince.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Proposed in this paper: https://arxiv.org/abs/2201.04309 4 | 5 | This loss is not always greater than 0, and maybe we should add warmup to stablize training. 6 | 7 | Sadly, if we use this to train denseCL from scratch, the loss would become nan if we use identical training parameters as original implementation(tuned for using info-nce). From my observation, the loss generates fierce gradient thus the model output logits becomes nan. 8 | ''' 9 | 10 | import torch 11 | import torch.nn as nn 12 | import torch.nn.functional as F 13 | import torch.cuda.amp as amp 14 | 15 | 16 | 17 | class RINCE(nn.Module): 18 | 19 | def __init__(self, q=0.5, lam=0.025): 20 | super(RINCE, self).__init__() 21 | self.q = q 22 | self.lam = lam 23 | 24 | def forward(self, pos, neg): 25 | loss = RINCEFunc.apply(pos, neg, self.lam, self.q) 26 | return loss.mean() 27 | 28 | 29 | class RINCEFunc(torch.autograd.Function): 30 | 31 | @staticmethod 32 | @amp.custom_fwd(cast_inputs=torch.float32) 33 | def forward(ctx, pos, neg, lam, q): 34 | div_q = 1./q 35 | exp_pos = pos.exp().squeeze(1) 36 | exp_sum = exp_pos + neg.exp().sum(dim=1) 37 | term1 = exp_pos.pow(q).neg_() 38 | term2 = exp_sum.mul_(lam).pow_(q) 39 | loss = (term1 + term2).mul_(div_q) 40 | 41 | ctx.vars = pos, neg, lam, q 42 | 43 | return loss 44 | 45 | @staticmethod 46 | @amp.custom_bwd 47 | def backward(ctx, grad_output): 48 | pos, neg, lam, q = ctx.vars 49 | exp_pos = pos.exp().squeeze(1) 50 | exp_neg = neg.exp() 51 | exp_sum = exp_pos + exp_neg.sum(dim=1) 52 | 53 | d_pos = exp_sum.mul(lam).pow(q-1.).mul(lam).mul(exp_pos) - exp_pos.pow(q) 54 | d_neg = exp_sum.mul(lam).pow(q-1.).mul(lam).unsqueeze(1).mul(exp_neg) 55 | 56 | d_pos = d_pos.mul(grad_output).unsqueeze(1) 57 | d_neg = d_neg.mul(grad_output.unsqueeze(1)) 58 | 59 | return d_pos, d_neg, None, None 60 | 61 | 62 | class RINCEV2(nn.Module): 63 | 64 | def __init__(self, q=0.5, lam=0.025): 65 | super(RINCEV2, self).__init__() 66 | self.q = q 67 | self.div_q = 1./q 68 | self.lam = lam 69 | 70 | def forward(self, pos, neg): 71 | pos = pos.float() 72 | neg = neg.float() 73 | exp_pos = pos.exp().squeeze(1) 74 | exp_sum = exp_pos + neg.exp().sum(dim=1) 75 | 76 | term1 = exp_pos.pow(self.q).neg() 77 | term2 = exp_sum.mul(self.lam).pow(self.q) 78 | loss = (term1 + term2).mul(self.div_q) 79 | return loss.mean() 80 | 81 | 82 | # class RINCE(nn.Module): 83 | # 84 | # def __init__(self, q=0.5, lam=0.025): 85 | # super(RINCE, self).__init__() 86 | # self.q = q 87 | # self.div_q = 1./q 88 | # self.lam = lam 89 | # 90 | # def forward(self, logits, labels): 91 | # N, *M = labels.size() 92 | # C = logits.size(1) 93 | # lb_one_hot = torch.zeros_like(logits).bool().scatter_(1, labels.unsqueeze(1), True).detach() 94 | # exp = logits.exp() 95 | # exp_pos = exp[lb_one_hot].view(N, *M) 96 | # exp_sum = exp.sum(dim=1) 97 | # 98 | # term1 = exp_pos.pow(self.q).neg() 99 | # term2 = exp_sum.mul(self.lam).pow(self.q) 100 | # loss = (term1 + term2).mul(self.div_q) 101 | # return loss.mean() 102 | 103 | 104 | if __name__ == "__main__": 105 | logits = torch.randn(3, 4,5 ,6) 106 | # labels = torch.randint(0, 3, (3, 5, 6)) 107 | labels = torch.zeros((3, 5, 6)).long() 108 | crit = RINCE() 109 | 110 | N, *M = labels.size() 111 | C = logits.size(1) 112 | lb_one_hot = torch.zeros_like(logits).bool().scatter_(1, labels.unsqueeze(1), True).detach() 113 | pos = logits[lb_one_hot].view(N, 1, *M) 114 | neg = logits[~lb_one_hot].view(N, C-1, *M) 115 | print(pos.size()) 116 | print(neg.size()) 117 | loss = crit(pos, neg) 118 | 119 | # logits = torch.randn(2, 3,2) 120 | # labels = torch.zeros((2, 2)).long() 121 | # loss = crit(logits, labels) 122 | print(loss) 123 | 124 | # crit = RINCEV2() 125 | # print(crit(logits, labels)) 126 | 127 | 128 | import torchvision 129 | import torch 130 | import numpy as np 131 | import random 132 | 133 | net1 = torchvision.models.resnet18(pretrained=False) 134 | net1.cuda() 135 | net1.train() 136 | net1.double() 137 | net2 = torchvision.models.resnet18(pretrained=False) 138 | net2.load_state_dict(net1.state_dict()) 139 | net2.cuda() 140 | net2.train() 141 | net2.double() 142 | 143 | criteria1 = RINCE() 144 | criteria2 = RINCEV2() 145 | 146 | optim1 = torch.optim.SGD(net1.parameters(), lr=1e-3) 147 | optim2 = torch.optim.SGD(net2.parameters(), lr=1e-3) 148 | 149 | for it in range(1000): 150 | inten = torch.randn(16 ,3, 224, 224).cuda().double() 151 | 152 | logits1 = net1(inten) 153 | logits1 = logits1.tanh() 154 | pos1, neg1 = logits1[:, 0:1, ...], logits1[:, 1:, ...] 155 | loss1 = criteria1(pos1, neg1) 156 | optim1.zero_grad() 157 | loss1.backward() 158 | optim1.step() 159 | 160 | logits2 = net2(inten) 161 | logits2 = logits2.tanh() 162 | pos2, neg2 = logits2[:, 0:1, ...], logits2[:, 1:, ...] 163 | loss2 = criteria2(pos2, neg2) 164 | optim2.zero_grad() 165 | loss2.backward() 166 | optim2.step() 167 | with torch.no_grad(): 168 | if (it+1) % 50 == 0: 169 | print('iter: {}, ================='.format(it+1)) 170 | print('out.weight: ', torch.mean(torch.abs(net1.fc.weight - net2.fc.weight)).item()) 171 | print('conv1.weight: ', torch.mean(torch.abs(net1.conv1.weight - net2.conv1.weight)).item()) 172 | print('loss: ', loss1.item() - loss2.item()) 173 | print('loss1: ', loss1.item()) 174 | print('loss2: ', loss2.item()) 175 | -------------------------------------------------------------------------------- /detection/README.md: -------------------------------------------------------------------------------- 1 | 2 | ## DenseCL: Transferring to Detection 3 | 4 | The `train_net.py` script reproduces the object detection experiments on Pascal VOC and COCO. 5 | 6 | ### Instruction 7 | 8 | 1. Install [detectron2](https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md). 9 | ``` 10 | $ git clone https://github.com/facebookresearch/detectron2.git 11 | $ cd detectron2 12 | $ git checkout 3e71a2711bec 13 | $ python -m pip install -e . 14 | ``` 15 | This requires cuda10.2 to work. 16 | 17 | 2. Convert a pre-trained model to detectron2's format: 18 | ``` 19 | python3 convert-pretrain-to-detectron2.py input.pth.tar output.pkl 20 | ``` 21 | 22 | 3. Put dataset under "./datasets" directory, 23 | following the [directory structure](https://github.com/facebookresearch/detectron2/tree/master/datasets) 24 | requried by detectron2. 25 | ``` 26 | $ mkdir -p datasets && cd datasets 27 | $ ln -s VOC2007 . 28 | $ ln -s VOC2012 . 29 | ``` 30 | 31 | 4. Run training: 32 | ``` 33 | # r50 34 | python train_net.py --config-file configs/pascal_voc_R_50_C4_24k_moco.yaml \ 35 | --num-gpus 8 MODEL.WEIGHTS ./output.pkl 36 | # r101 37 | python train_net.py --config-file configs/pascal_voc_R_101_C4_24k_moco.yaml \ 38 | --num-gpus 8 MODEL.WEIGHTS ./output.pkl 39 | ``` 40 | 41 | Or you can see [dist_train.sh](./dist_train.sh) for the training scripts. 42 | 43 | ### Results 44 | 45 | Below are the results on Pascal VOC 2007 test, fine-tuned on 2007+2012 trainval for 24k iterations using Faster R-CNN with a R50/R101-C4 backbone: 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 |
pretrainAP50APAP75
ImageNet-1M, R50, supervised81.353.558.8
ImageNet-1M, R50, MoCo v1, 200ep81.555.962.6
ImageNet-1M, R50, MoCo v2, 200ep82.457.063.6
ImageNet-1M, R50, MoCo v2, 800ep82.557.464.0
ImageNet-1M, R50, DenseCL, 200ep82.758.565.6
ImageNet-1M, R101, DenseCL, 200ep83.5761.0268.20
ImageNet-1M, R50, RegionCL-D, 200ep83.3258.7265.57
ImageNet-1M, R101, RegionCL-D, 200ep84.3061.5968.17
98 | 99 | ***Note:*** These results are means of 5 trials. Variation on Pascal VOC is large: the std of AP50, AP, AP75 is expected to be 0.2, 0.2, 0.4 in most cases. We recommend to run 5 trials and compute means. 100 | 101 | 102 | denseCL, r50: 103 | 82.64/58.32/64.60 104 | 82.64/58.41/64.89 105 | 106 | denseCL, r101: 107 | 83.57/61.02/68.20 108 | 83.52/60.89/67.32 109 | 110 | regionCL-D, r50: 111 | 83.24/58.84/65.98 112 | 83.40/58.60/65.16 113 | 114 | regionCL-D, r101: 115 | 84.22/61.48/68.14 116 | 84.39/61.70/68.21 117 | 118 | 119 | -------------------------------------------------------------------------------- /detection/configs/Base-RCNN-C4-BN.yaml: -------------------------------------------------------------------------------- 1 | MODEL: 2 | META_ARCHITECTURE: "GeneralizedRCNN" 3 | RPN: 4 | PRE_NMS_TOPK_TEST: 6000 5 | POST_NMS_TOPK_TEST: 1000 6 | ROI_HEADS: 7 | NAME: "Res5ROIHeadsExtraNorm" 8 | BACKBONE: 9 | FREEZE_AT: 0 10 | RESNETS: 11 | NORM: "SyncBN" 12 | TEST: 13 | PRECISE_BN: 14 | ENABLED: True 15 | SOLVER: 16 | IMS_PER_BATCH: 16 17 | BASE_LR: 0.02 18 | -------------------------------------------------------------------------------- /detection/configs/coco_R_50_C4_2x.yaml: -------------------------------------------------------------------------------- 1 | _BASE_: "Base-RCNN-C4-BN.yaml" 2 | MODEL: 3 | MASK_ON: True 4 | WEIGHTS: "detectron2://ImageNetPretrained/MSRA/R-50.pkl" 5 | INPUT: 6 | MIN_SIZE_TRAIN: (640, 672, 704, 736, 768, 800) 7 | MIN_SIZE_TEST: 800 8 | DATASETS: 9 | TRAIN: ("coco_2017_train",) 10 | TEST: ("coco_2017_val",) 11 | SOLVER: 12 | STEPS: (120000, 160000) 13 | MAX_ITER: 180000 14 | -------------------------------------------------------------------------------- /detection/configs/coco_R_50_C4_2x_moco.yaml: -------------------------------------------------------------------------------- 1 | _BASE_: "coco_R_50_C4_2x.yaml" 2 | MODEL: 3 | PIXEL_MEAN: [123.675, 116.280, 103.530] 4 | PIXEL_STD: [58.395, 57.120, 57.375] 5 | WEIGHTS: "See Instructions" 6 | RESNETS: 7 | STRIDE_IN_1X1: False 8 | INPUT: 9 | FORMAT: "RGB" 10 | -------------------------------------------------------------------------------- /detection/configs/pascal_voc_R_101_C4_24k_moco.yaml: -------------------------------------------------------------------------------- 1 | _BASE_: "pascal_voc_R_50_C4_24k.yaml" 2 | MODEL: 3 | PIXEL_MEAN: [123.675, 116.280, 103.530] 4 | PIXEL_STD: [58.395, 57.120, 57.375] 5 | WEIGHTS: "See Instructions" 6 | RESNETS: 7 | DEPTH: 101 8 | STRIDE_IN_1X1: False 9 | INPUT: 10 | FORMAT: "RGB" 11 | -------------------------------------------------------------------------------- /detection/configs/pascal_voc_R_50_C4_24k.yaml: -------------------------------------------------------------------------------- 1 | _BASE_: "Base-RCNN-C4-BN.yaml" 2 | MODEL: 3 | MASK_ON: False 4 | WEIGHTS: "detectron2://ImageNetPretrained/MSRA/R-50.pkl" 5 | ROI_HEADS: 6 | NUM_CLASSES: 20 7 | INPUT: 8 | MIN_SIZE_TRAIN: (480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800) 9 | MIN_SIZE_TEST: 800 10 | DATASETS: 11 | TRAIN: ('voc_2007_trainval', 'voc_2012_trainval') 12 | TEST: ('voc_2007_test',) 13 | SOLVER: 14 | STEPS: (18000, 22000) 15 | MAX_ITER: 24000 16 | WARMUP_ITERS: 100 17 | -------------------------------------------------------------------------------- /detection/configs/pascal_voc_R_50_C4_24k_moco.yaml: -------------------------------------------------------------------------------- 1 | _BASE_: "pascal_voc_R_50_C4_24k.yaml" 2 | MODEL: 3 | PIXEL_MEAN: [123.675, 116.280, 103.530] 4 | PIXEL_STD: [58.395, 57.120, 57.375] 5 | WEIGHTS: "See Instructions" 6 | RESNETS: 7 | STRIDE_IN_1X1: False 8 | INPUT: 9 | FORMAT: "RGB" 10 | -------------------------------------------------------------------------------- /detection/convert-pretrain-to-detectron2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 3 | 4 | import pickle as pkl 5 | import sys 6 | import torch 7 | 8 | if __name__ == "__main__": 9 | input = sys.argv[1] 10 | 11 | obj = torch.load(input, map_location="cpu") 12 | obj = obj["state_dict"] 13 | 14 | newmodel = {} 15 | for k, v in obj.items(): 16 | if not k.startswith("module.encoder_q."): 17 | continue 18 | old_k = k 19 | k = k.replace("module.encoder_q.", "") 20 | if "layer" not in k: 21 | k = "stem." + k 22 | for t in [1, 2, 3, 4]: 23 | k = k.replace("layer{}".format(t), "res{}".format(t + 1)) 24 | for t in [1, 2, 3]: 25 | k = k.replace("bn{}".format(t), "conv{}.norm".format(t)) 26 | k = k.replace("downsample.0", "shortcut") 27 | k = k.replace("downsample.1", "shortcut.norm") 28 | print(old_k, "->", k) 29 | newmodel[k] = v.numpy() 30 | 31 | res = {"model": newmodel, "__author__": "MOCO", "matching_heuristics": True} 32 | 33 | with open(sys.argv[2], "wb") as f: 34 | pkl.dump(res, f) 35 | -------------------------------------------------------------------------------- /detection/datasets: -------------------------------------------------------------------------------- 1 | /data/zzy/.datasets/VOCC_all/datasets/ -------------------------------------------------------------------------------- /detection/dist_train.sh: -------------------------------------------------------------------------------- 1 | 2 | ## densecl 3 | 4 | CKPT=../checkpoint_0199.pth.tar 5 | CONFIG=configs/pascal_voc_R_50_C4_24k_moco.yaml 6 | # CONFIG=configs/pascal_voc_R_101_C4_24k_moco.yaml 7 | 8 | 9 | 10 | rm ./output_denseCL_200ep.pkl 11 | python convert-pretrain-to-detectron2.py ../checkpoint_0199.pth.tar ./output_denseCL_200ep.pkl 12 | python train_net.py --config-file $CONFIG --num-gpus 8 MODEL.WEIGHTS ./output_denseCL_200ep.pkl 13 | 14 | ## original supervised 15 | # python train_net.py --config-file configs/pascal_voc_R_50_C4_24k.yaml --num-gpus 8 16 | -------------------------------------------------------------------------------- /detection/train_net.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 3 | 4 | import os 5 | 6 | from detectron2.checkpoint import DetectionCheckpointer 7 | from detectron2.config import get_cfg 8 | from detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, launch 9 | from detectron2.evaluation import COCOEvaluator, PascalVOCDetectionEvaluator 10 | from detectron2.layers import get_norm 11 | from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, Res5ROIHeads 12 | 13 | 14 | @ROI_HEADS_REGISTRY.register() 15 | class Res5ROIHeadsExtraNorm(Res5ROIHeads): 16 | """ 17 | As described in the MOCO paper, there is an extra BN layer 18 | following the res5 stage. 19 | """ 20 | def _build_res5_block(self, cfg): 21 | seq, out_channels = super()._build_res5_block(cfg) 22 | norm = cfg.MODEL.RESNETS.NORM 23 | norm = get_norm(norm, out_channels) 24 | seq.add_module("norm", norm) 25 | return seq, out_channels 26 | 27 | 28 | class Trainer(DefaultTrainer): 29 | @classmethod 30 | def build_evaluator(cls, cfg, dataset_name, output_folder=None): 31 | if output_folder is None: 32 | output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") 33 | if "coco" in dataset_name: 34 | return COCOEvaluator(dataset_name, cfg, True, output_folder) 35 | else: 36 | assert "voc" in dataset_name 37 | return PascalVOCDetectionEvaluator(dataset_name) 38 | 39 | 40 | def setup(args): 41 | cfg = get_cfg() 42 | cfg.merge_from_file(args.config_file) 43 | cfg.merge_from_list(args.opts) 44 | cfg.freeze() 45 | default_setup(cfg, args) 46 | return cfg 47 | 48 | 49 | def main(args): 50 | cfg = setup(args) 51 | 52 | if args.eval_only: 53 | model = Trainer.build_model(cfg) 54 | DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load( 55 | cfg.MODEL.WEIGHTS, resume=args.resume 56 | ) 57 | res = Trainer.test(cfg, model) 58 | return res 59 | 60 | trainer = Trainer(cfg) 61 | trainer.resume_or_load(resume=args.resume) 62 | return trainer.train() 63 | 64 | 65 | if __name__ == "__main__": 66 | args = default_argument_parser().parse_args() 67 | print("Command Line Args:", args) 68 | launch( 69 | main, 70 | args.num_gpus, 71 | num_machines=args.num_machines, 72 | machine_rank=args.machine_rank, 73 | dist_url=args.dist_url, 74 | args=(args,), 75 | ) 76 | -------------------------------------------------------------------------------- /dist_train.sh: -------------------------------------------------------------------------------- 1 | 2 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 3 | 4 | 5 | ######## 6 | # for pretrain 7 | ######## 8 | 9 | ## denseCL r50/r101 10 | DATAPATH=/path/to/imagenet 11 | ARCH=resnet50/resnet101 12 | URL='tcp://localhost:10001' 13 | WORD_SIZE=1 14 | RANK=0 15 | EPOCHS=200 16 | LR=0.03 # 8 gpus 17 | python main_densecl.py -a $ARCH --lr $LR --batch-size 256 --epochs $EPOCHS --world-size $WORD_SIZE --rank $RANK --dist-url $URL --multiprocessing-distributed --use-mixed-precision --mlp --moco-t 0.2 --aug-plus --cos $DATAPATH 18 | 19 | 20 | ## regionCL-D r50/r101 21 | DATAPATH=/path/to/imagenet 22 | ARCH=resnet50/resnet101 23 | URL='tcp://localhost:10001' 24 | WORD_SIZE=1 25 | RANK=0 26 | EPOCHS=200 27 | LR=0.03 # 8 gpus 28 | python main_densecl.py -a $ARCH --lr $LR --batch-size 256 --epochs $EPOCHS --world-size $WORD_SIZE --rank $RANK --dist-url $URL --multiprocessing-distributed --use-mixed-precision --mlp --moco-t 0.2 --aug-plus --cos $DATAPATH --cutmix 29 | 30 | 31 | ######## 32 | # linear eval 33 | ######## 34 | URL='tcp://localhost:10001' 35 | WORD_SIZE=1 36 | RANK=0 37 | DATAPATH=/path/to/imagenet 38 | PRETRAINED=./checkpoint_0199.pth.tar 39 | ARCH=resnet50/resnet101 40 | python main_lincls.py -a $ARCH --lr 30.0 --batch-size 256 --pretrained $PRETRAINED --dist-url $URL --multiprocessing-distributed --world-size $WORD_SIZE --rank $RANK $DATAPATH 41 | 42 | -------------------------------------------------------------------------------- /main_densecl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 3 | import argparse 4 | import builtins 5 | import math 6 | import os 7 | import random 8 | import shutil 9 | import time 10 | import warnings 11 | 12 | import torch 13 | import torch.nn as nn 14 | import torch.nn.parallel 15 | import torch.backends.cudnn as cudnn 16 | import torch.distributed as dist 17 | import torch.optim 18 | import torch.multiprocessing as mp 19 | import torch.utils.data 20 | import torch.utils.data.distributed 21 | import torch.cuda.amp as amp 22 | import torchvision.transforms as transforms 23 | import torchvision.datasets as datasets 24 | import torchvision.models as models 25 | 26 | import densecl.loader 27 | from densecl.builder import DenseCL 28 | 29 | model_names = sorted(name for name in models.__dict__ 30 | if name.islower() and not name.startswith("__") 31 | and callable(models.__dict__[name])) 32 | 33 | from densecl.resnet import resnet50, resnet101 34 | model_names = ['resnet50', 'resnet101'] 35 | model_dict = {'resnet50': resnet50, 'resnet101': resnet101} 36 | 37 | parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') 38 | parser.add_argument('data', metavar='DIR', 39 | help='path to dataset') 40 | parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50', 41 | choices=model_names, 42 | help='model architecture: ' + 43 | ' | '.join(model_names) + 44 | ' (default: resnet50)') 45 | parser.add_argument('-j', '--workers', default=32, type=int, metavar='N', 46 | help='number of data loading workers (default: 32)') 47 | parser.add_argument('--warmup-epochs', default=5, type=int, metavar='N', 48 | help='number of warmup epochs to run') 49 | parser.add_argument('--epochs', default=200, type=int, metavar='N', 50 | help='number of total epochs to run') 51 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 52 | help='manual epoch number (useful on restarts)') 53 | parser.add_argument('-b', '--batch-size', default=256, type=int, 54 | metavar='N', 55 | help='mini-batch size (default: 256), this is the total ' 56 | 'batch size of all GPUs on the current node when ' 57 | 'using Data Parallel or Distributed Data Parallel') 58 | parser.add_argument('--lr', '--learning-rate', default=0.03, type=float, 59 | metavar='LR', help='initial learning rate', dest='lr') 60 | parser.add_argument('--schedule', default=[120, 160], nargs='*', type=int, 61 | help='learning rate schedule (when to drop lr by 10x)') 62 | parser.add_argument('--momentum', default=0.9, type=float, metavar='M', 63 | help='momentum of SGD solver') 64 | parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float, 65 | metavar='W', help='weight decay (default: 1e-4)', 66 | dest='weight_decay') 67 | parser.add_argument('-p', '--print-freq', default=100, type=int, 68 | metavar='N', help='print frequency (default: 10)') 69 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 70 | help='path to latest checkpoint (default: none)') 71 | parser.add_argument('--world-size', default=-1, type=int, 72 | help='number of nodes for distributed training') 73 | parser.add_argument('--rank', default=-1, type=int, 74 | help='node rank for distributed training') 75 | parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str, 76 | help='url used to set up distributed training') 77 | parser.add_argument('--dist-backend', default='nccl', type=str, 78 | help='distributed backend') 79 | parser.add_argument('--seed', default=None, type=int, 80 | help='seed for initializing training. ') 81 | parser.add_argument('--gpu', default=None, type=int, 82 | help='GPU id to use.') 83 | parser.add_argument('--multiprocessing-distributed', action='store_true', 84 | help='Use multi-processing distributed training to launch ' 85 | 'N processes per node, which has N GPUs. This is the ' 86 | 'fastest way to use PyTorch for either single node or ' 87 | 'multi node data parallel training') 88 | parser.add_argument('--use-mixed-precision', action='store_true', 89 | help='use mlp head') 90 | 91 | # moco specific configs: 92 | parser.add_argument('--moco-dim', default=128, type=int, 93 | help='feature dimension (default: 128)') 94 | parser.add_argument('--moco-k', default=65536, type=int, 95 | help='queue size; number of negative keys (default: 65536)') 96 | parser.add_argument('--moco-m', default=0.999, type=float, 97 | help='moco momentum of updating key encoder (default: 0.999)') 98 | parser.add_argument('--moco-t', default=0.07, type=float, 99 | help='softmax temperature (default: 0.07)') 100 | 101 | # options for moco v2 102 | parser.add_argument('--mlp', action='store_true', 103 | help='use mlp head') 104 | parser.add_argument('--aug-plus', action='store_true', 105 | help='use moco v2 data augmentation') 106 | parser.add_argument('--cos', action='store_true', 107 | help='use cosine lr schedule') 108 | 109 | # options for regionCL 110 | parser.add_argument('--cutmix', action='store_true', 111 | help='use regionCL') 112 | 113 | 114 | def main(): 115 | args = parser.parse_args() 116 | 117 | if args.seed is not None: 118 | random.seed(args.seed) 119 | torch.manual_seed(args.seed) 120 | cudnn.deterministic = True 121 | warnings.warn('You have chosen to seed training. ' 122 | 'This will turn on the CUDNN deterministic setting, ' 123 | 'which can slow down your training considerably! ' 124 | 'You may see unexpected behavior when restarting ' 125 | 'from checkpoints.') 126 | 127 | if args.gpu is not None: 128 | warnings.warn('You have chosen a specific GPU. This will completely ' 129 | 'disable data parallelism.') 130 | 131 | if args.dist_url == "env://" and args.world_size == -1: 132 | args.world_size = int(os.environ["WORLD_SIZE"]) 133 | 134 | args.distributed = args.world_size > 1 or args.multiprocessing_distributed 135 | 136 | ngpus_per_node = torch.cuda.device_count() 137 | if args.multiprocessing_distributed: 138 | # Since we have ngpus_per_node processes per node, the total world_size 139 | # needs to be adjusted accordingly 140 | args.world_size = ngpus_per_node * args.world_size 141 | # Use torch.multiprocessing.spawn to launch distributed processes: the 142 | # main_worker process function 143 | mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args)) 144 | else: 145 | # Simply call main_worker function 146 | main_worker(args.gpu, ngpus_per_node, args) 147 | 148 | 149 | def main_worker(gpu, ngpus_per_node, args): 150 | args.gpu = gpu 151 | 152 | # suppress printing if not master 153 | if args.multiprocessing_distributed and args.gpu != 0: 154 | def print_pass(*args): 155 | pass 156 | builtins.print = print_pass 157 | 158 | if args.gpu is not None: 159 | print("Use GPU: {} for training".format(args.gpu)) 160 | 161 | if args.distributed: 162 | if args.dist_url == "env://" and args.rank == -1: 163 | args.rank = int(os.environ["RANK"]) 164 | if args.multiprocessing_distributed: 165 | # For multiprocessing distributed training, rank needs to be the 166 | # global rank among all the processes 167 | args.rank = args.rank * ngpus_per_node + gpu 168 | dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 169 | world_size=args.world_size, rank=args.rank) 170 | # create model 171 | print("=> creating model '{}'".format(args.arch)) 172 | base_model = model_dict[args.arch] 173 | model = densecl.builder.DenseCL(base_model, 174 | args.moco_dim, args.moco_k, args.moco_m, 175 | args.moco_t, args.mlp, args.cutmix) 176 | print(model) 177 | 178 | if args.distributed: 179 | # For multiprocessing distributed, DistributedDataParallel constructor 180 | # should always set the single device scope, otherwise, 181 | # DistributedDataParallel will use all available devices. 182 | if args.gpu is not None: 183 | torch.cuda.set_device(args.gpu) 184 | model.cuda(args.gpu) 185 | # When using a single GPU per process and per 186 | # DistributedDataParallel, we need to divide the batch size 187 | # ourselves based on the total number of GPUs we have 188 | args.batch_size = int(args.batch_size / ngpus_per_node) 189 | args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node) 190 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) 191 | else: 192 | model.cuda() 193 | # DistributedDataParallel will divide and allocate batch_size to all 194 | # available GPUs if device_ids are not set 195 | model = torch.nn.parallel.DistributedDataParallel(model) 196 | elif args.gpu is not None: 197 | torch.cuda.set_device(args.gpu) 198 | model = model.cuda(args.gpu) 199 | # comment out the following line for debugging 200 | raise NotImplementedError("Only DistributedDataParallel is supported.") 201 | else: 202 | # AllGather implementation (batch shuffle, queue update, etc.) in 203 | # this code only supports DistributedDataParallel. 204 | raise NotImplementedError("Only DistributedDataParallel is supported.") 205 | 206 | optimizer = torch.optim.SGD(model.parameters(), args.lr, 207 | momentum=args.momentum, 208 | weight_decay=args.weight_decay) 209 | 210 | # optionally resume from a checkpoint 211 | if args.resume: 212 | if os.path.isfile(args.resume): 213 | print("=> loading checkpoint '{}'".format(args.resume)) 214 | if args.gpu is None: 215 | checkpoint = torch.load(args.resume) 216 | else: 217 | # Map model to be loaded to specified single gpu. 218 | loc = 'cuda:{}'.format(args.gpu) 219 | checkpoint = torch.load(args.resume, map_location=loc) 220 | args.start_epoch = checkpoint['epoch'] 221 | model.load_state_dict(checkpoint['state_dict']) 222 | optimizer.load_state_dict(checkpoint['optimizer']) 223 | print("=> loaded checkpoint '{}' (epoch {})" 224 | .format(args.resume, checkpoint['epoch'])) 225 | else: 226 | print("=> no checkpoint found at '{}'".format(args.resume)) 227 | 228 | cudnn.benchmark = True 229 | 230 | # Data loading code 231 | traindir = os.path.join(args.data, 'train') 232 | normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 233 | std=[0.229, 0.224, 0.225]) 234 | if args.aug_plus: 235 | # MoCo v2's aug: similar to SimCLR https://arxiv.org/abs/2002.05709 236 | augmentation = [ 237 | transforms.RandomResizedCrop(224, scale=(0.2, 1.)), 238 | transforms.RandomApply([ 239 | transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) # not strengthened 240 | ], p=0.8), 241 | transforms.RandomGrayscale(p=0.2), 242 | transforms.RandomApply([densecl.loader.GaussianBlur([.1, 2.])], p=0.5), 243 | transforms.RandomHorizontalFlip(), 244 | transforms.ToTensor(), 245 | normalize 246 | ] 247 | else: 248 | # MoCo v1's aug: the same as InstDisc https://arxiv.org/abs/1805.01978 249 | augmentation = [ 250 | transforms.RandomResizedCrop(224, scale=(0.2, 1.)), 251 | transforms.RandomGrayscale(p=0.2), 252 | transforms.ColorJitter(0.4, 0.4, 0.4, 0.4), 253 | transforms.RandomHorizontalFlip(), 254 | transforms.ToTensor(), 255 | normalize 256 | ] 257 | 258 | train_dataset = datasets.ImageFolder( 259 | traindir, 260 | densecl.loader.TwoCropsTransform(transforms.Compose(augmentation))) 261 | 262 | if args.distributed: 263 | train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) 264 | else: 265 | train_sampler = None 266 | 267 | train_loader = torch.utils.data.DataLoader( 268 | train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), 269 | num_workers=args.workers, pin_memory=True, sampler=train_sampler, drop_last=True) 270 | 271 | for epoch in range(args.start_epoch, args.epochs): 272 | if args.distributed: 273 | train_sampler.set_epoch(epoch) 274 | adjust_learning_rate(optimizer, epoch, args) 275 | 276 | # train for one epoch 277 | train(train_loader, model, optimizer, epoch, args) 278 | 279 | n_ckpt_period = 20 280 | if not args.multiprocessing_distributed or (args.multiprocessing_distributed 281 | and args.rank % ngpus_per_node == 0) and ((epoch + 1) % n_ckpt_period == 0): 282 | if epoch > args.epochs - 10: n_ckpt_period = 1 283 | save_checkpoint({ 284 | 'epoch': epoch + 1, 285 | 'arch': args.arch, 286 | 'state_dict': model.state_dict(), 287 | 'optimizer' : optimizer.state_dict(), 288 | }, is_best=False, filename='checkpoint_{:04d}.pth.tar'.format(epoch)) 289 | 290 | 291 | # def train(train_loader, model, criterion, criterion_dense, optimizer, epoch, args): 292 | def train(train_loader, model, optimizer, epoch, args): 293 | batch_time = AverageMeter('Time', ':6.3f') 294 | data_time = AverageMeter('Data', ':6.3f') 295 | losses = AverageMeter('Loss', ':.4e') 296 | top1 = AverageMeter('Acc@1', ':6.2f') 297 | top5 = AverageMeter('Acc@5', ':6.2f') 298 | progress = ProgressMeter( 299 | len(train_loader), 300 | [batch_time, data_time, losses, top1, top5], 301 | prefix="Epoch: [{}]".format(epoch)) 302 | 303 | # amp scalar 304 | scaler = amp.GradScaler() 305 | 306 | # switch to train mode 307 | model.train() 308 | 309 | end = time.time() 310 | for i, (images, _) in enumerate(train_loader): 311 | # measure data loading time 312 | data_time.update(time.time() - end) 313 | 314 | if args.gpu is not None: 315 | images[0] = images[0].cuda(args.gpu, non_blocking=True) 316 | images[1] = images[1].cuda(args.gpu, non_blocking=True) 317 | 318 | # compute output 319 | with amp.autocast(enabled=args.use_mixed_precision): 320 | loss_cls, loss_dense, extra = model( 321 | im_q=images[0], im_k=images[1]) 322 | 323 | loss = 0.5 * (loss_cls + loss_dense) 324 | if args.cutmix: 325 | loss_cutmix = extra['loss_cutmix'] 326 | loss = loss + loss_cutmix 327 | 328 | # acc1/acc5 are (K+1)-way contrast classifier accuracy 329 | # measure accuracy and record loss 330 | with torch.no_grad(): 331 | logits, labels = extra['logits'], extra['labels'] 332 | acc1, acc5 = accuracy(logits, labels, topk=(1, 5)) 333 | losses.update(loss.item(), images[0].size(0)) 334 | top1.update(acc1[0], images[0].size(0)) 335 | top5.update(acc5[0], images[0].size(0)) 336 | 337 | # compute gradient and do SGD step 338 | optimizer.zero_grad() 339 | scaler.scale(loss).backward() 340 | scaler.step(optimizer) 341 | scaler.update() 342 | # loss.backward() 343 | # optimizer.step() 344 | 345 | # measure elapsed time 346 | batch_time.update(time.time() - end) 347 | end = time.time() 348 | 349 | if i % args.print_freq == 0: 350 | progress.display(i) 351 | 352 | 353 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): 354 | torch.save(state, filename) 355 | if is_best: 356 | shutil.copyfile(filename, 'model_best.pth.tar') 357 | 358 | 359 | class AverageMeter(object): 360 | """Computes and stores the average and current value""" 361 | def __init__(self, name, fmt=':f'): 362 | self.name = name 363 | self.fmt = fmt 364 | self.reset() 365 | 366 | def reset(self): 367 | self.val = 0 368 | self.avg = 0 369 | self.sum = 0 370 | self.count = 0 371 | 372 | def update(self, val, n=1): 373 | self.val = val 374 | self.sum += val * n 375 | self.count += n 376 | self.avg = self.sum / self.count 377 | 378 | def __str__(self): 379 | fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' 380 | return fmtstr.format(**self.__dict__) 381 | 382 | 383 | class ProgressMeter(object): 384 | def __init__(self, num_batches, meters, prefix=""): 385 | self.batch_fmtstr = self._get_batch_fmtstr(num_batches) 386 | self.meters = meters 387 | self.prefix = prefix 388 | 389 | def display(self, batch): 390 | entries = [self.prefix + self.batch_fmtstr.format(batch)] 391 | entries += [str(meter) for meter in self.meters] 392 | print('\t'.join(entries)) 393 | 394 | def _get_batch_fmtstr(self, num_batches): 395 | num_digits = len(str(num_batches // 1)) 396 | fmt = '{:' + str(num_digits) + 'd}' 397 | return '[' + fmt + '/' + fmt.format(num_batches) + ']' 398 | 399 | 400 | def adjust_learning_rate(optimizer, epoch, args): 401 | """Decay the learning rate based on schedule""" 402 | lr = args.lr 403 | if args.cos: # cosine lr schedule 404 | # lr *= 0.5 * (1. + math.cos(math.pi * epoch / args.epochs)) 405 | if epoch < args.warmup_epochs: 406 | ratio = (epoch + 1) / args.warmup_epochs 407 | else: 408 | cur_epoch = epoch - args.warmup_epochs + 1 409 | total_epoch = args.epochs - args.warmup_epochs + 1 410 | ratio = 0.5 * (1. + math.cos(math.pi * cur_epoch / total_epoch)) 411 | lr *= ratio 412 | else: # stepwise lr schedule 413 | for milestone in args.schedule: 414 | lr *= 0.1 if epoch >= milestone else 1. 415 | for param_group in optimizer.param_groups: 416 | param_group['lr'] = lr 417 | 418 | 419 | def accuracy(output, target, topk=(1,)): 420 | """Computes the accuracy over the k top predictions for the specified values of k""" 421 | with torch.no_grad(): 422 | maxk = max(topk) 423 | batch_size = output.size(0) 424 | 425 | _, pred = output.topk(maxk, 1, True, True) 426 | pred = pred.t() 427 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 428 | 429 | res = [] 430 | for k in topk: 431 | correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) 432 | res.append(correct_k.mul_(100.0 / batch_size)) 433 | return res 434 | 435 | 436 | 437 | if __name__ == '__main__': 438 | main() 439 | -------------------------------------------------------------------------------- /main_lincls.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 3 | import argparse 4 | import builtins 5 | import os 6 | import random 7 | import shutil 8 | import time 9 | import warnings 10 | 11 | import torch 12 | import torch.nn as nn 13 | import torch.nn.parallel 14 | import torch.backends.cudnn as cudnn 15 | import torch.distributed as dist 16 | import torch.optim 17 | import torch.multiprocessing as mp 18 | import torch.utils.data 19 | import torch.utils.data.distributed 20 | import torchvision.transforms as transforms 21 | import torchvision.datasets as datasets 22 | import torchvision.models as models 23 | 24 | model_names = sorted(name for name in models.__dict__ 25 | if name.islower() and not name.startswith("__") 26 | and callable(models.__dict__[name])) 27 | 28 | parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') 29 | parser.add_argument('data', metavar='DIR', 30 | help='path to dataset') 31 | parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50', 32 | choices=model_names, 33 | help='model architecture: ' + 34 | ' | '.join(model_names) + 35 | ' (default: resnet50)') 36 | parser.add_argument('-j', '--workers', default=32, type=int, metavar='N', 37 | help='number of data loading workers (default: 32)') 38 | parser.add_argument('--epochs', default=100, type=int, metavar='N', 39 | help='number of total epochs to run') 40 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 41 | help='manual epoch number (useful on restarts)') 42 | parser.add_argument('-b', '--batch-size', default=256, type=int, 43 | metavar='N', 44 | help='mini-batch size (default: 256), this is the total ' 45 | 'batch size of all GPUs on the current node when ' 46 | 'using Data Parallel or Distributed Data Parallel') 47 | parser.add_argument('--lr', '--learning-rate', default=30., type=float, 48 | metavar='LR', help='initial learning rate', dest='lr') 49 | parser.add_argument('--schedule', default=[60, 80], nargs='*', type=int, 50 | help='learning rate schedule (when to drop lr by a ratio)') 51 | parser.add_argument('--momentum', default=0.9, type=float, metavar='M', 52 | help='momentum') 53 | parser.add_argument('--wd', '--weight-decay', default=0., type=float, 54 | metavar='W', help='weight decay (default: 0.)', 55 | dest='weight_decay') 56 | parser.add_argument('-p', '--print-freq', default=10, type=int, 57 | metavar='N', help='print frequency (default: 10)') 58 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 59 | help='path to latest checkpoint (default: none)') 60 | parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true', 61 | help='evaluate model on validation set') 62 | parser.add_argument('--world-size', default=-1, type=int, 63 | help='number of nodes for distributed training') 64 | parser.add_argument('--rank', default=-1, type=int, 65 | help='node rank for distributed training') 66 | parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str, 67 | help='url used to set up distributed training') 68 | parser.add_argument('--dist-backend', default='nccl', type=str, 69 | help='distributed backend') 70 | parser.add_argument('--seed', default=None, type=int, 71 | help='seed for initializing training. ') 72 | parser.add_argument('--gpu', default=None, type=int, 73 | help='GPU id to use.') 74 | parser.add_argument('--multiprocessing-distributed', action='store_true', 75 | help='Use multi-processing distributed training to launch ' 76 | 'N processes per node, which has N GPUs. This is the ' 77 | 'fastest way to use PyTorch for either single node or ' 78 | 'multi node data parallel training') 79 | 80 | parser.add_argument('--pretrained', default='', type=str, 81 | help='path to moco pretrained checkpoint') 82 | 83 | best_acc1 = 0 84 | 85 | 86 | def main(): 87 | args = parser.parse_args() 88 | 89 | if args.seed is not None: 90 | random.seed(args.seed) 91 | torch.manual_seed(args.seed) 92 | cudnn.deterministic = True 93 | warnings.warn('You have chosen to seed training. ' 94 | 'This will turn on the CUDNN deterministic setting, ' 95 | 'which can slow down your training considerably! ' 96 | 'You may see unexpected behavior when restarting ' 97 | 'from checkpoints.') 98 | 99 | if args.gpu is not None: 100 | warnings.warn('You have chosen a specific GPU. This will completely ' 101 | 'disable data parallelism.') 102 | 103 | if args.dist_url == "env://" and args.world_size == -1: 104 | args.world_size = int(os.environ["WORLD_SIZE"]) 105 | 106 | args.distributed = args.world_size > 1 or args.multiprocessing_distributed 107 | 108 | ngpus_per_node = torch.cuda.device_count() 109 | if args.multiprocessing_distributed: 110 | # Since we have ngpus_per_node processes per node, the total world_size 111 | # needs to be adjusted accordingly 112 | args.world_size = ngpus_per_node * args.world_size 113 | # Use torch.multiprocessing.spawn to launch distributed processes: the 114 | # main_worker process function 115 | mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args)) 116 | else: 117 | # Simply call main_worker function 118 | main_worker(args.gpu, ngpus_per_node, args) 119 | 120 | 121 | def main_worker(gpu, ngpus_per_node, args): 122 | global best_acc1 123 | args.gpu = gpu 124 | 125 | # suppress printing if not master 126 | if args.multiprocessing_distributed and args.gpu != 0: 127 | def print_pass(*args): 128 | pass 129 | builtins.print = print_pass 130 | 131 | if args.gpu is not None: 132 | print("Use GPU: {} for training".format(args.gpu)) 133 | 134 | if args.distributed: 135 | if args.dist_url == "env://" and args.rank == -1: 136 | args.rank = int(os.environ["RANK"]) 137 | if args.multiprocessing_distributed: 138 | # For multiprocessing distributed training, rank needs to be the 139 | # global rank among all the processes 140 | args.rank = args.rank * ngpus_per_node + gpu 141 | dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 142 | world_size=args.world_size, rank=args.rank) 143 | # create model 144 | print("=> creating model '{}'".format(args.arch)) 145 | model = models.__dict__[args.arch]() 146 | 147 | # freeze all layers but the last fc 148 | for name, param in model.named_parameters(): 149 | if name not in ['fc.weight', 'fc.bias']: 150 | param.requires_grad = False 151 | # init the fc layer 152 | model.fc.weight.data.normal_(mean=0.0, std=0.01) 153 | model.fc.bias.data.zero_() 154 | 155 | # load from pre-trained, before DistributedDataParallel constructor 156 | if args.pretrained: 157 | if os.path.isfile(args.pretrained): 158 | print("=> loading checkpoint '{}'".format(args.pretrained)) 159 | checkpoint = torch.load(args.pretrained, map_location="cpu") 160 | 161 | # rename moco pre-trained keys 162 | state_dict = checkpoint['state_dict'] 163 | for k in list(state_dict.keys()): 164 | # retain only encoder_q up to before the embedding layer 165 | if k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'): 166 | # remove prefix 167 | state_dict[k[len("module.encoder_q."):]] = state_dict[k] 168 | # delete renamed or unused k 169 | del state_dict[k] 170 | 171 | args.start_epoch = 0 172 | msg = model.load_state_dict(state_dict, strict=False) 173 | assert set(msg.missing_keys) == {"fc.weight", "fc.bias"} 174 | 175 | print("=> loaded pre-trained model '{}'".format(args.pretrained)) 176 | else: 177 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 178 | 179 | if args.distributed: 180 | # For multiprocessing distributed, DistributedDataParallel constructor 181 | # should always set the single device scope, otherwise, 182 | # DistributedDataParallel will use all available devices. 183 | if args.gpu is not None: 184 | torch.cuda.set_device(args.gpu) 185 | model.cuda(args.gpu) 186 | # When using a single GPU per process and per 187 | # DistributedDataParallel, we need to divide the batch size 188 | # ourselves based on the total number of GPUs we have 189 | args.batch_size = int(args.batch_size / ngpus_per_node) 190 | args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node) 191 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) 192 | else: 193 | model.cuda() 194 | # DistributedDataParallel will divide and allocate batch_size to all 195 | # available GPUs if device_ids are not set 196 | model = torch.nn.parallel.DistributedDataParallel(model) 197 | elif args.gpu is not None: 198 | torch.cuda.set_device(args.gpu) 199 | model = model.cuda(args.gpu) 200 | else: 201 | # DataParallel will divide and allocate batch_size to all available GPUs 202 | if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): 203 | model.features = torch.nn.DataParallel(model.features) 204 | model.cuda() 205 | else: 206 | model = torch.nn.DataParallel(model).cuda() 207 | 208 | # define loss function (criterion) and optimizer 209 | criterion = nn.CrossEntropyLoss().cuda(args.gpu) 210 | 211 | # optimize only the linear classifier 212 | parameters = list(filter(lambda p: p.requires_grad, model.parameters())) 213 | assert len(parameters) == 2 # fc.weight, fc.bias 214 | optimizer = torch.optim.SGD(parameters, args.lr, 215 | momentum=args.momentum, 216 | weight_decay=args.weight_decay) 217 | 218 | # optionally resume from a checkpoint 219 | if args.resume: 220 | if os.path.isfile(args.resume): 221 | print("=> loading checkpoint '{}'".format(args.resume)) 222 | if args.gpu is None: 223 | checkpoint = torch.load(args.resume) 224 | else: 225 | # Map model to be loaded to specified single gpu. 226 | loc = 'cuda:{}'.format(args.gpu) 227 | checkpoint = torch.load(args.resume, map_location=loc) 228 | args.start_epoch = checkpoint['epoch'] 229 | best_acc1 = checkpoint['best_acc1'] 230 | if args.gpu is not None: 231 | # best_acc1 may be from a checkpoint from a different GPU 232 | best_acc1 = best_acc1.to(args.gpu) 233 | model.load_state_dict(checkpoint['state_dict']) 234 | optimizer.load_state_dict(checkpoint['optimizer']) 235 | print("=> loaded checkpoint '{}' (epoch {})" 236 | .format(args.resume, checkpoint['epoch'])) 237 | else: 238 | print("=> no checkpoint found at '{}'".format(args.resume)) 239 | 240 | cudnn.benchmark = True 241 | 242 | # Data loading code 243 | traindir = os.path.join(args.data, 'train') 244 | valdir = os.path.join(args.data, 'val') 245 | normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 246 | std=[0.229, 0.224, 0.225]) 247 | 248 | train_dataset = datasets.ImageFolder( 249 | traindir, 250 | transforms.Compose([ 251 | transforms.RandomResizedCrop(224), 252 | transforms.RandomHorizontalFlip(), 253 | transforms.ToTensor(), 254 | normalize, 255 | ])) 256 | 257 | if args.distributed: 258 | train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) 259 | else: 260 | train_sampler = None 261 | 262 | train_loader = torch.utils.data.DataLoader( 263 | train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), 264 | num_workers=args.workers, pin_memory=True, sampler=train_sampler) 265 | 266 | val_loader = torch.utils.data.DataLoader( 267 | datasets.ImageFolder(valdir, transforms.Compose([ 268 | transforms.Resize(256), 269 | transforms.CenterCrop(224), 270 | transforms.ToTensor(), 271 | normalize, 272 | ])), 273 | batch_size=args.batch_size, shuffle=False, 274 | num_workers=args.workers, pin_memory=True) 275 | 276 | if args.evaluate: 277 | validate(val_loader, model, criterion, args) 278 | return 279 | 280 | for epoch in range(args.start_epoch, args.epochs): 281 | if args.distributed: 282 | train_sampler.set_epoch(epoch) 283 | adjust_learning_rate(optimizer, epoch, args) 284 | 285 | # train for one epoch 286 | train(train_loader, model, criterion, optimizer, epoch, args) 287 | 288 | # evaluate on validation set 289 | acc1 = validate(val_loader, model, criterion, args) 290 | 291 | # remember best acc@1 and save checkpoint 292 | is_best = acc1 > best_acc1 293 | best_acc1 = max(acc1, best_acc1) 294 | 295 | if not args.multiprocessing_distributed or (args.multiprocessing_distributed 296 | and args.rank % ngpus_per_node == 0): 297 | save_checkpoint({ 298 | 'epoch': epoch + 1, 299 | 'arch': args.arch, 300 | 'state_dict': model.state_dict(), 301 | 'best_acc1': best_acc1, 302 | 'optimizer' : optimizer.state_dict(), 303 | }, is_best) 304 | if epoch == args.start_epoch: 305 | sanity_check(model.state_dict(), args.pretrained) 306 | 307 | 308 | def train(train_loader, model, criterion, optimizer, epoch, args): 309 | batch_time = AverageMeter('Time', ':6.3f') 310 | data_time = AverageMeter('Data', ':6.3f') 311 | losses = AverageMeter('Loss', ':.4e') 312 | top1 = AverageMeter('Acc@1', ':6.2f') 313 | top5 = AverageMeter('Acc@5', ':6.2f') 314 | progress = ProgressMeter( 315 | len(train_loader), 316 | [batch_time, data_time, losses, top1, top5], 317 | prefix="Epoch: [{}]".format(epoch)) 318 | 319 | """ 320 | Switch to eval mode: 321 | Under the protocol of linear classification on frozen features/models, 322 | it is not legitimate to change any part of the pre-trained model. 323 | BatchNorm in train mode may revise running mean/std (even if it receives 324 | no gradient), which are part of the model parameters too. 325 | """ 326 | model.eval() 327 | 328 | end = time.time() 329 | for i, (images, target) in enumerate(train_loader): 330 | # measure data loading time 331 | data_time.update(time.time() - end) 332 | 333 | if args.gpu is not None: 334 | images = images.cuda(args.gpu, non_blocking=True) 335 | target = target.cuda(args.gpu, non_blocking=True) 336 | 337 | # compute output 338 | output = model(images) 339 | loss = criterion(output, target) 340 | 341 | # measure accuracy and record loss 342 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 343 | losses.update(loss.item(), images.size(0)) 344 | top1.update(acc1[0], images.size(0)) 345 | top5.update(acc5[0], images.size(0)) 346 | 347 | # compute gradient and do SGD step 348 | optimizer.zero_grad() 349 | loss.backward() 350 | optimizer.step() 351 | 352 | # measure elapsed time 353 | batch_time.update(time.time() - end) 354 | end = time.time() 355 | 356 | if i % args.print_freq == 0: 357 | progress.display(i) 358 | 359 | 360 | def validate(val_loader, model, criterion, args): 361 | batch_time = AverageMeter('Time', ':6.3f') 362 | losses = AverageMeter('Loss', ':.4e') 363 | top1 = AverageMeter('Acc@1', ':6.2f') 364 | top5 = AverageMeter('Acc@5', ':6.2f') 365 | progress = ProgressMeter( 366 | len(val_loader), 367 | [batch_time, losses, top1, top5], 368 | prefix='Test: ') 369 | 370 | # switch to evaluate mode 371 | model.eval() 372 | 373 | with torch.no_grad(): 374 | end = time.time() 375 | for i, (images, target) in enumerate(val_loader): 376 | if args.gpu is not None: 377 | images = images.cuda(args.gpu, non_blocking=True) 378 | target = target.cuda(args.gpu, non_blocking=True) 379 | 380 | # compute output 381 | output = model(images) 382 | loss = criterion(output, target) 383 | 384 | # measure accuracy and record loss 385 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 386 | losses.update(loss.item(), images.size(0)) 387 | top1.update(acc1[0], images.size(0)) 388 | top5.update(acc5[0], images.size(0)) 389 | 390 | # measure elapsed time 391 | batch_time.update(time.time() - end) 392 | end = time.time() 393 | 394 | if i % args.print_freq == 0: 395 | progress.display(i) 396 | 397 | # TODO: this should also be done with the ProgressMeter 398 | print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}' 399 | .format(top1=top1, top5=top5)) 400 | 401 | return top1.avg 402 | 403 | 404 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): 405 | torch.save(state, filename) 406 | if is_best: 407 | shutil.copyfile(filename, 'model_best.pth.tar') 408 | 409 | 410 | def sanity_check(state_dict, pretrained_weights): 411 | """ 412 | Linear classifier should not change any weights other than the linear layer. 413 | This sanity check asserts nothing wrong happens (e.g., BN stats updated). 414 | """ 415 | print("=> loading '{}' for sanity check".format(pretrained_weights)) 416 | checkpoint = torch.load(pretrained_weights, map_location="cpu") 417 | state_dict_pre = checkpoint['state_dict'] 418 | 419 | for k in list(state_dict.keys()): 420 | # only ignore fc layer 421 | if 'fc.weight' in k or 'fc.bias' in k: 422 | continue 423 | 424 | # name in pretrained model 425 | k_pre = 'module.encoder_q.' + k[len('module.'):] \ 426 | if k.startswith('module.') else 'module.encoder_q.' + k 427 | 428 | assert ((state_dict[k].cpu() == state_dict_pre[k_pre]).all()), \ 429 | '{} is changed in linear classifier training.'.format(k) 430 | 431 | print("=> sanity check passed.") 432 | 433 | 434 | class AverageMeter(object): 435 | """Computes and stores the average and current value""" 436 | def __init__(self, name, fmt=':f'): 437 | self.name = name 438 | self.fmt = fmt 439 | self.reset() 440 | 441 | def reset(self): 442 | self.val = 0 443 | self.avg = 0 444 | self.sum = 0 445 | self.count = 0 446 | 447 | def update(self, val, n=1): 448 | self.val = val 449 | self.sum += val * n 450 | self.count += n 451 | self.avg = self.sum / self.count 452 | 453 | def __str__(self): 454 | fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' 455 | return fmtstr.format(**self.__dict__) 456 | 457 | 458 | class ProgressMeter(object): 459 | def __init__(self, num_batches, meters, prefix=""): 460 | self.batch_fmtstr = self._get_batch_fmtstr(num_batches) 461 | self.meters = meters 462 | self.prefix = prefix 463 | 464 | def display(self, batch): 465 | entries = [self.prefix + self.batch_fmtstr.format(batch)] 466 | entries += [str(meter) for meter in self.meters] 467 | print('\t'.join(entries)) 468 | 469 | def _get_batch_fmtstr(self, num_batches): 470 | num_digits = len(str(num_batches // 1)) 471 | fmt = '{:' + str(num_digits) + 'd}' 472 | return '[' + fmt + '/' + fmt.format(num_batches) + ']' 473 | 474 | 475 | def adjust_learning_rate(optimizer, epoch, args): 476 | """Decay the learning rate based on schedule""" 477 | lr = args.lr 478 | for milestone in args.schedule: 479 | lr *= 0.1 if epoch >= milestone else 1. 480 | for param_group in optimizer.param_groups: 481 | param_group['lr'] = lr 482 | 483 | 484 | def accuracy(output, target, topk=(1,)): 485 | """Computes the accuracy over the k top predictions for the specified values of k""" 486 | with torch.no_grad(): 487 | maxk = max(topk) 488 | batch_size = target.size(0) 489 | 490 | _, pred = output.topk(maxk, 1, True, True) 491 | pred = pred.t() 492 | correct = pred.eq(target.reshape(1, -1).expand_as(pred)) 493 | 494 | res = [] 495 | for k in topk: 496 | correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) 497 | res.append(correct_k.mul_(100.0 / batch_size)) 498 | return res 499 | 500 | 501 | if __name__ == '__main__': 502 | main() 503 | --------------------------------------------------------------------------------