├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── illustration.png ├── requirements.txt └── src ├── data ├── __init__.py └── dataloader.py ├── inference.py ├── models ├── __init__.py ├── compressed │ ├── mask_r_cnn.pth │ ├── resnet18_large_blocks.pth │ ├── resnet18_small_blocks.pth │ ├── resnet50_large_blocks.pth │ ├── resnet50_semisup_small_blocks.pth │ └── resnet50_small_blocks.pth └── resnet.py ├── optim ├── __init__.py └── centroid_sgd.py ├── quantization ├── __init__.py ├── distance.py ├── em.py ├── pq.py └── solver.py ├── quantize.py └── utils ├── __init__.py ├── dynamic_sampling.py ├── reshape.py ├── statistics.py ├── training.py ├── utils.py └── watcher.py /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | Facebook has adopted a Code of Conduct that we expect project participants to adhere to. 4 | Please read the [full text](https://code.fb.com/codeofconduct/) 5 | so that you can understand what actions will and will not be tolerated. 6 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Pull Requests 4 | 5 | In order to accept your pull request, we need you to submit a CLA. You only need 6 | to do this once to work on any of Facebook's open source projects. 7 | 8 | Complete your CLA here: 9 | 10 | This repository is the implementation of a research paper. 11 | Therefore, we do not plan on accepting many pull requests for new features. 12 | We certainly welcome them for bug fixes. 13 | 14 | 15 | ## Issues 16 | 17 | We use GitHub issues to track public bugs. Please ensure your description is 18 | clear and has sufficient instructions to be able to reproduce the issue. 19 | 20 | 21 | ## License 22 | By contributing to this repository, you agree that your contributions will be licensed under the LICENSE file in the root directory of this source tree. 23 | -------------------------------------------------------------------------------- /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 | # And the bit goes down 2 | 3 | This repository contains the implementation of our paper: [And the bit goes down: Revisiting the quantization of neural networks](https://arxiv.org/abs/1907.05686) (ICLR 2020) as well as the compressed models we obtain (ResNets and Mask R-CNN). 4 | 5 | Our compression method is based on vector quantization. It takes as input an already trained neural network and, through a distillation procedure at all layers and a fine-tuning stage, optimizes the accuracy of the network. 6 | 7 | This approach outperforms the state-of-the-art w.r.t. compression/accuracy trade-off for standard networks like ResNet-18 and ResNet-50 (see [Compressed models](#Compressed-Models)). 8 | 9 |

10 | Illustration of our method. We approximate a binary classifier $\varphi$ that labels images $x$ as dogs or cats by quantizing its weights.
 11 |     \textbf{Standard method}: quantizing $\varphi$ with the standard objective function \eqref{eq:pq_obj} leads to a classifier $\widehat \varphi_{\text{bad}}$ that tries to approximate $\varphi$ over the entire input space and thus performs badly for in-domains inputs.
 12 |     \textbf{Our method}: quantizing $\varphi$ with our objective function \eqref{eq:ours_obj} leads to a classifier  $\widehat \varphi_{\text{good}}$ that performs well for in-domain inputs.
 13 |     \benjamin{Maybe move the $\widehat \varphi_{\text{bad}}$ and $\widehat \varphi_{\text{good}}$ labels from the top left corner into the image close to the respective lines. Then the $\phi(x)$ can come down a little. 14 |

15 | 16 | 17 | ## Installation 18 | 19 | Our code works with Python 3.6 and newest. To run the code, you must have the following packages installed: 20 | - [NumPy](http://www.numpy.org/) 21 | - [PyTorch](http://pytorch.org/) (version=1.0.1.post2) 22 | 23 | These dependencies can be installed with: 24 | ` 25 | pip install -r requirements.txt 26 | ` 27 | 28 | ## Compressed Models 29 | The compressed models (centroids + assignments) are available in the `models/compressed` folder. We provide code to evaluate those models on their standard benchmarks (ImageNet/COCO). Note that inference can be performed both on GPU or on CPU. Note also that we did not optimize this precise part of the code for speed. Indeed, the code for inference should rather be regarded as a proof of concept: based on the centroids and the assignments, we recover the accuracies mentioned in the table above by instantiating the full, non-compressed model. 30 | 31 | ### Vanilla ResNets 32 | We provide the vanilla compressed ResNet-18 and ResNet-50 models for 256 centroids in the low and high compression regimes. As mentioned in the paper, the low compression regime corresponds to a block size of 9 for standard 3x3 convolutions and to a block size of 4 for 1x1 pointwise convolutions. Similarly, the high compression regime corresponds to a block size of 18 for standard 3x3 convolutions and to a block size of 8 for 1x1 pointwise convolutions. 33 | 34 | |Model (non-compressed top-1) | Compression | Size ratio | Model size | Top-1 (%)| 35 | |:-:|:-:|:-:|:-:|:--:| 36 | ResNet-18 (69.76%) | Small blocks
Large blocks | 29x
43x |1.54 MB
1.03 MB|**65.81**
**61.18** 37 | ResNet-50 (76.15%) | Small blocks
Large blocks | 19x
31x |5.09 MB
3.19 MB|**73.79**
**68.21** 38 | 39 | To evaluate on the standard test set of ImageNet: clone the repo, `cd` into `src/` and run: 40 | ```bash 41 | python inference.py --model resnet18 --state-dict-compressed models/compressed/resnet18_small_blocks.pth --device cuda --data-path YOUR_IMAGENET_PATH 42 | ``` 43 | 44 | ### Semi-supervised ResNet50 45 | We provide the compressed [semi-supervised ResNet50](https://arxiv.org/abs/1905.00546) trained and open-sourced by Yalniz *et. al.* We use 256 centroids and the small blocks compression regime. 46 | 47 | 48 | |Model (non-compressed top-1) | Compression | Size ratio | Model size | Top-1 (%)| 49 | |:-:|:-:|:-:|:-:|:--:| 50 | Semi-Supervised ResNet-50 (79.30%) | Small blocks| 19x | 5.20 MB | **76.12** 51 | 52 | To evaluate on the standard test set of ImageNet: clone the repo, `cd` into `src/` and run: 53 | ```bash 54 | python inference.py --model resnet50_semisup --state-dict-compressed models/compressed/resnet50_semisup_small_blocks.pth --device cuda --data-path YOUR_IMAGENET_PATH 55 | ``` 56 | 57 | ### Mask R-CNN 58 | 59 | We provide the compressed Mask R-CNN (backbone ResNet50-FPN) available in the [PyTorch Model Zoo](https://pytorch.org/docs/stable/torchvision/models.html). As mentioned in the paper, we use 256 centroids and various block sizes to reach an interesting size/accuracy tradeoff (with a 26x compression factor). Note that you need [torchvision 0.3](https://pytorch.org/blog/torchvision03/) in order to run this part of the code. 60 | 61 | |Model | Size | Box AP| Mask AP | 62 | |:-:|:-:|:-:|:-:| 63 | |Non-compressed | 170 MB | 37.9 | 34.6| 64 | |Compressed | 6.65 MB | 33.9 | 30.8 | 65 | 66 | To evaluate on COCO: clone the repo, run `git checkout mask_r_cnn`, `cd` into `src/` and run: 67 | ```bash 68 | python inference.py --model maskrcnn_resnet50_fpn --state-dict-compressed models/compressed/mask_r_cnn.pth --device cuda --data-path YOUR_COCO_PATH 69 | ``` 70 | 71 | ## Results 72 | 73 | You can also compress the vanilla ResNet models and reproduce the results of our paper by `cd` into `src/` and by running the following commands: 74 | - For the *small blocks* compression regime: 75 | ```bash 76 | python quantize.py --model resnet18 --block-size-cv 9 --block-size-pw 4 --n-centroids-cv 256 --n-centroids-pw 256 --n-centroids-fc 2048 --data-path YOUR_IMAGENET_PATH 77 | python quantize.py --model resnet50 --block-size-cv 9 --block-size-pw 4 --n-centroids-cv 256 --n-centroids-pw 256 --n-centroids-fc 1024 --data-path YOUR_IMAGENET_PATH 78 | ``` 79 | - For the *large blocks* compression regime: 80 | ```bash 81 | python quantize.py --model resnet18 --block-size-cv 18 --block-size-pw 4 --n-centroids-cv 256 --n-centroids-pw 256 --n-centroids-fc 2048 --data-path YOUR_IMAGENET_PATH 82 | python quantize.py --model resnet50 --block-size-cv 18 --block-size-pw 8 --n-centroids-cv 256 --n-centroids-pw 256 --n-centroids-fc 1024 --data-path YOUR_IMAGENET_PATH 83 | ``` 84 | Note that the vanilla ResNet-18 and ResNet-50 teacher (non-compressed) models are taken from the PyTorch model zoo. Note also that we run our code on a single 16GB Volta V100 GPU. 85 | 86 | ## License 87 | This repository is released under Creative Commons Attribution 4.0 International (CC BY 4.0) license, as found in the LICENSE file. 88 | 89 | ## Bibliography 90 | Please consider citing [1] if you found the resources in this repository useful. 91 | 92 | [1] Stock, Pierre and Joulin, Armand and Gribonval, Rémi and Graham, Benjamin and Jégou, Hervé. [And the bit goes down: Revisiting the quantization of neural networks](https://arxiv.org/abs/1907.05686). 93 | ``` 94 | @inproceedings{stock2019killthebits, 95 | title = {And the bit goes down: Revisiting the quantization of neural networks}, 96 | author = {Stock, Pierre and Joulin, Armand and Gribonval, R{\'e}mi and Graham, Benjamin and J{\'e}gou, Herv{\'e}}, 97 | booktitle = {International Conference on Learning Representations (ICLR)}, 98 | year = {2020} 99 | } 100 | ``` 101 | -------------------------------------------------------------------------------- /illustration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/kill-the-bits/9ea70f1aef44f4ffb14d89fb304dcbcb93a31ec7/illustration.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | torch==1.0.1 3 | torchvision==0.2.2 4 | -------------------------------------------------------------------------------- /src/data/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | from .dataloader import load_data 9 | -------------------------------------------------------------------------------- /src/data/dataloader.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import os 9 | import torch 10 | import torchvision.transforms as transforms 11 | import torchvision.datasets as datasets 12 | 13 | 14 | def load_data(data_path='', batch_size=128, nb_workers=64): 15 | """ 16 | Loads data from ImageNet dataset. 17 | 18 | Args: 19 | - data_path: path to dataset 20 | - batch_size: train and test batch size 21 | - nb_workers: number of workers for dataloader 22 | """ 23 | 24 | # data path 25 | train_data_path = os.path.join(data_path, 'train') 26 | test_data_path = os.path.join(data_path, 'val') 27 | 28 | normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 29 | std=[0.229, 0.224, 0.225]) 30 | 31 | transf_train = transforms.Compose([ 32 | transforms.RandomResizedCrop(224), 33 | transforms.RandomHorizontalFlip(), 34 | transforms.ToTensor(), 35 | normalize]) 36 | transf_test = transforms.Compose([ 37 | transforms.Resize(256), 38 | transforms.CenterCrop(224), 39 | transforms.ToTensor(), 40 | normalize 41 | ]) 42 | 43 | train_set = datasets.ImageFolder( 44 | root=train_data_path, transform=transf_train) 45 | train_loader = torch.utils.data.DataLoader( 46 | train_set, batch_size=batch_size, shuffle=True, num_workers=nb_workers, pin_memory=True, drop_last=True) 47 | 48 | test_set = datasets.ImageFolder( 49 | root=test_data_path, transform=transf_test) 50 | test_loader = torch.utils.data.DataLoader( 51 | test_set, batch_size=batch_size, shuffle=False, num_workers=nb_workers, pin_memory=True) 52 | 53 | return train_loader, test_loader 54 | -------------------------------------------------------------------------------- /src/inference.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import argparse 9 | from operator import attrgetter 10 | 11 | import torch 12 | import torch.nn as nn 13 | 14 | import models as resnet_models 15 | import torchvision.models.detection as detection_models 16 | from data import load_data 17 | from utils.training import evaluate 18 | from utils.watcher import ActivationWatcher as ActivationWatcherResNet 19 | from utils.utils import weight_from_centroids 20 | 21 | 22 | parser = argparse.ArgumentParser(description='Inference for quantized networks') 23 | parser.add_argument('--model', default='resnet18', choices=['resnet18', 'resnet50', 'resnet50_semisup'], 24 | help='Model to use for inference') 25 | parser.add_argument('--state-dict-compressed', default='', type=str, 26 | help='Path to the compressed state dict of the model') 27 | parser.add_argument('--device', default='cuda', choices=['cpu', 'cuda'], 28 | help='For inference on CPU or on GPU') 29 | parser.add_argument('--data-path', default='/datasets01/imagenet_full_size/061417/', type=str, 30 | help='Path to ImageNet dataset') 31 | parser.add_argument('--batch-size', default=128, type=int, 32 | help='Batch size for fiuetuning steps') 33 | parser.add_argument('--n-workers', default=20, type=int, 34 | help='Number of workers for data loading') 35 | 36 | 37 | def main(): 38 | global args 39 | args = parser.parse_args() 40 | device = args.device 41 | state_dict_compressed = torch.load(args.state_dict_compressed) 42 | 43 | # instantiating model 44 | model = 'resnet50' if args.model == 'resnet50_semisup' else args.model 45 | model = resnet_models.__dict__[model](pretrained=False).to(device) 46 | criterion = nn.CrossEntropyLoss() 47 | _, test_loader = load_data(data_path=args.data_path, batch_size=args.batch_size, nb_workers=args.n_workers) 48 | watcher = ActivationWatcherResNet(model) 49 | 50 | # conv1 layer (non-compressed) 51 | layer = 'conv1' 52 | state_dict_layer = to_device(state_dict_compressed[layer], device) 53 | attrgetter(layer)(model).load_state_dict(state_dict_layer) 54 | attrgetter(layer)(model).float() 55 | 56 | # compressed layers 57 | compressed_layers = watcher.layers[1:] 58 | 59 | # 2 more layers non-compressed for semi-supervised ResNet50 60 | if args.model == 'resnet50_semisup': 61 | non_compressed_layers = ['layer1.0.conv3', 'layer1.0.downsample.0'] 62 | for layer in non_compressed_layers: 63 | compressed_layers.remove(layer) 64 | state_dict_layer = to_device(state_dict_compressed[layer], device) 65 | attrgetter(layer)(model).load_state_dict(state_dict_layer) 66 | attrgetter(layer)(model).float() 67 | 68 | for layer in compressed_layers: 69 | # recover centroids and assignments 70 | state_dict_layer = state_dict_compressed[layer] 71 | centroids = state_dict_layer['centroids'].float().to(device) 72 | assignments = state_dict_layer['assignments'].long().to(device) 73 | n_blocks = state_dict_layer['n_blocks'] 74 | is_conv = state_dict_layer['is_conv'] 75 | k = state_dict_layer['k'] 76 | 77 | # instantiate matrix 78 | M_hat = weight_from_centroids(centroids, assignments, n_blocks, k, is_conv) 79 | attrgetter(layer + '.weight')(model).data = M_hat 80 | 81 | # batch norms 82 | bn_layers = watcher._get_bn_layers() 83 | 84 | for layer in bn_layers: 85 | state_dict_layer = to_device(state_dict_compressed[layer], device) 86 | attrgetter(layer)(model).weight.data = state_dict_layer['weight'].float().to(device) 87 | attrgetter(layer)(model).bias.data = state_dict_layer['bias'].float().to(device) 88 | 89 | # classifier bias 90 | layer = 'fc' 91 | state_dict_layer = to_device(state_dict_compressed['fc_bias'], device) 92 | attrgetter(layer + '.bias')(model).data = state_dict_layer['bias'] 93 | 94 | # evaluate the model 95 | top_1 = evaluate(test_loader, model, criterion, device=device).item() 96 | print('Top-1 accuracy of quantized model: {:.2f}'.format(top_1)) 97 | 98 | 99 | def to_device(state_dict, device): 100 | return {k: v.to(device) for (k, v) in state_dict.items()} 101 | 102 | 103 | if __name__ == '__main__': 104 | main() 105 | -------------------------------------------------------------------------------- /src/models/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | from .resnet import * 9 | -------------------------------------------------------------------------------- /src/models/compressed/mask_r_cnn.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/kill-the-bits/9ea70f1aef44f4ffb14d89fb304dcbcb93a31ec7/src/models/compressed/mask_r_cnn.pth -------------------------------------------------------------------------------- /src/models/compressed/resnet18_large_blocks.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/kill-the-bits/9ea70f1aef44f4ffb14d89fb304dcbcb93a31ec7/src/models/compressed/resnet18_large_blocks.pth -------------------------------------------------------------------------------- /src/models/compressed/resnet18_small_blocks.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/kill-the-bits/9ea70f1aef44f4ffb14d89fb304dcbcb93a31ec7/src/models/compressed/resnet18_small_blocks.pth -------------------------------------------------------------------------------- /src/models/compressed/resnet50_large_blocks.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/kill-the-bits/9ea70f1aef44f4ffb14d89fb304dcbcb93a31ec7/src/models/compressed/resnet50_large_blocks.pth -------------------------------------------------------------------------------- /src/models/compressed/resnet50_semisup_small_blocks.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/kill-the-bits/9ea70f1aef44f4ffb14d89fb304dcbcb93a31ec7/src/models/compressed/resnet50_semisup_small_blocks.pth -------------------------------------------------------------------------------- /src/models/compressed/resnet50_small_blocks.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/kill-the-bits/9ea70f1aef44f4ffb14d89fb304dcbcb93a31ec7/src/models/compressed/resnet50_small_blocks.pth -------------------------------------------------------------------------------- /src/models/resnet.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import torch.nn as nn 9 | import torch.utils.model_zoo as model_zoo 10 | 11 | 12 | __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 13 | 'resnet152'] 14 | 15 | 16 | model_urls = { 17 | 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 18 | 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 19 | 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 20 | 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 21 | 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', 22 | } 23 | 24 | 25 | def conv3x3(in_planes, out_planes, stride=1): 26 | """3x3 convolution with padding""" 27 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 28 | padding=1, bias=False) 29 | 30 | 31 | def conv1x1(in_planes, out_planes, stride=1): 32 | """1x1 convolution""" 33 | return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) 34 | 35 | 36 | class BasicBlock(nn.Module): 37 | expansion = 1 38 | 39 | def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer=None): 40 | super(BasicBlock, self).__init__() 41 | if norm_layer is None: 42 | norm_layer = nn.BatchNorm2d 43 | # Both self.conv1 and self.downsample layers downsample the input when stride != 1 44 | self.conv1 = conv3x3(inplanes, planes, stride) 45 | self.bn1 = norm_layer(planes) 46 | self.relu = nn.ReLU(inplace=True) 47 | self.conv2 = conv3x3(planes, planes) 48 | self.bn2 = norm_layer(planes) 49 | self.downsample = downsample 50 | self.stride = stride 51 | 52 | def forward(self, x): 53 | identity = x 54 | 55 | out = self.conv1(x) 56 | out = self.bn1(out) 57 | out = self.relu(out) 58 | 59 | out = self.conv2(out) 60 | out = self.bn2(out) 61 | 62 | if self.downsample is not None: 63 | identity = self.downsample(x) 64 | 65 | out += identity 66 | out = self.relu(out) 67 | 68 | return out 69 | 70 | 71 | class Bottleneck(nn.Module): 72 | expansion = 4 73 | 74 | def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer=None): 75 | super(Bottleneck, self).__init__() 76 | if norm_layer is None: 77 | norm_layer = nn.BatchNorm2d 78 | # Both self.conv2 and self.downsample layers downsample the input when stride != 1 79 | self.conv1 = conv1x1(inplanes, planes) 80 | self.bn1 = norm_layer(planes) 81 | self.conv2 = conv3x3(planes, planes, stride) 82 | self.bn2 = norm_layer(planes) 83 | self.conv3 = conv1x1(planes, planes * self.expansion) 84 | self.bn3 = norm_layer(planes * self.expansion) 85 | self.relu = nn.ReLU(inplace=True) 86 | self.downsample = downsample 87 | self.stride = stride 88 | 89 | def forward(self, x): 90 | identity = x 91 | 92 | out = self.conv1(x) 93 | out = self.bn1(out) 94 | out = self.relu(out) 95 | 96 | out = self.conv2(out) 97 | out = self.bn2(out) 98 | out = self.relu(out) 99 | 100 | out = self.conv3(out) 101 | out = self.bn3(out) 102 | 103 | if self.downsample is not None: 104 | identity = self.downsample(x) 105 | 106 | out += identity 107 | out = self.relu(out) 108 | 109 | return out 110 | 111 | 112 | class ResNet(nn.Module): 113 | 114 | def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, norm_layer=None): 115 | super(ResNet, self).__init__() 116 | if norm_layer is None: 117 | norm_layer = nn.BatchNorm2d 118 | self.inplanes = 64 119 | self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, 120 | bias=False) 121 | self.bn1 = norm_layer(64) 122 | self.relu = nn.ReLU(inplace=True) 123 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 124 | self.layer1 = self._make_layer(block, 64, layers[0], norm_layer=norm_layer) 125 | self.layer2 = self._make_layer(block, 128, layers[1], stride=2, norm_layer=norm_layer) 126 | self.layer3 = self._make_layer(block, 256, layers[2], stride=2, norm_layer=norm_layer) 127 | self.layer4 = self._make_layer(block, 512, layers[3], stride=2, norm_layer=norm_layer) 128 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) 129 | self.fc = nn.Linear(512 * block.expansion, num_classes) 130 | 131 | for m in self.modules(): 132 | if isinstance(m, nn.Conv2d): 133 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 134 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): 135 | nn.init.constant_(m.weight, 1) 136 | nn.init.constant_(m.bias, 0) 137 | 138 | # Zero-initialize the last BN in each residual branch, 139 | # so that the residual branch starts with zeros, and each residual block behaves like an identity. 140 | # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 141 | if zero_init_residual: 142 | for m in self.modules(): 143 | if isinstance(m, Bottleneck): 144 | nn.init.constant_(m.bn3.weight, 0) 145 | elif isinstance(m, BasicBlock): 146 | nn.init.constant_(m.bn2.weight, 0) 147 | 148 | def _make_layer(self, block, planes, blocks, stride=1, norm_layer=None): 149 | if norm_layer is None: 150 | norm_layer = nn.BatchNorm2d 151 | downsample = None 152 | if stride != 1 or self.inplanes != planes * block.expansion: 153 | downsample = nn.Sequential( 154 | conv1x1(self.inplanes, planes * block.expansion, stride), 155 | norm_layer(planes * block.expansion), 156 | ) 157 | 158 | layers = [] 159 | layers.append(block(self.inplanes, planes, stride, downsample, norm_layer)) 160 | self.inplanes = planes * block.expansion 161 | for _ in range(1, blocks): 162 | layers.append(block(self.inplanes, planes, norm_layer=norm_layer)) 163 | 164 | return nn.Sequential(*layers) 165 | 166 | def forward(self, x): 167 | x = self.conv1(x) 168 | x = self.bn1(x) 169 | x = self.relu(x) 170 | x = self.maxpool(x) 171 | 172 | x = self.layer1(x) 173 | x = self.layer2(x) 174 | x = self.layer3(x) 175 | x = self.layer4(x) 176 | 177 | x = self.avgpool(x) 178 | x = x.view(x.size(0), -1) 179 | x = self.fc(x) 180 | 181 | return x 182 | 183 | 184 | def resnet18(pretrained=False, **kwargs): 185 | """Constructs a ResNet-18 model. 186 | 187 | Args: 188 | pretrained (bool): If True, returns a model pre-trained on ImageNet 189 | """ 190 | model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) 191 | if pretrained: 192 | model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) 193 | return model 194 | 195 | 196 | def resnet34(pretrained=False, **kwargs): 197 | """Constructs a ResNet-34 model. 198 | 199 | Args: 200 | pretrained (bool): If True, returns a model pre-trained on ImageNet 201 | """ 202 | model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) 203 | if pretrained: 204 | model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) 205 | return model 206 | 207 | 208 | def resnet50(pretrained=False, **kwargs): 209 | """Constructs a ResNet-50 model. 210 | 211 | Args: 212 | pretrained (bool): If True, returns a model pre-trained on ImageNet 213 | """ 214 | model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) 215 | if pretrained: 216 | model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) 217 | return model 218 | 219 | 220 | def resnet101(pretrained=False, **kwargs): 221 | """Constructs a ResNet-101 model. 222 | 223 | Args: 224 | pretrained (bool): If True, returns a model pre-trained on ImageNet 225 | """ 226 | model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) 227 | if pretrained: 228 | model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) 229 | return model 230 | 231 | 232 | def resnet152(pretrained=False, **kwargs): 233 | """Constructs a ResNet-152 model. 234 | 235 | Args: 236 | pretrained (bool): If True, returns a model pre-trained on ImageNet 237 | """ 238 | model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) 239 | if pretrained: 240 | model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) 241 | return model 242 | -------------------------------------------------------------------------------- /src/optim/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | from .centroid_sgd import CentroidSGD 9 | -------------------------------------------------------------------------------- /src/optim/centroid_sgd.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import torch 9 | from torch.optim.optimizer import Optimizer, required 10 | 11 | from utils.reshape import reshape_weight, reshape_back_weight 12 | 13 | 14 | class CentroidSGD(Optimizer): 15 | """ 16 | Performs centroids finetuning given the block assignments. 17 | 18 | Args: 19 | - params: model.parameters() 20 | - assignments: assignments of each block of size n_blocks 21 | in the reshaped + unrolled weight matrix of the layers 22 | - n_centroids: number of centroids used to quantized the layer 23 | - n_blocks: number of blocks in the reshaped weight matrix 24 | - lr, momentum, dampening, weight_decay, nesterov: classical 25 | optimizer parameters, see PyTorch's documentation 26 | 27 | Remarks: 28 | - After each iteration, the gradients corresponding to the blokcs 29 | assigned to centroid k are averaged and the same update using 30 | this averaged gradient is applied to all the corresponding blocks 31 | """ 32 | 33 | def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False): 34 | if lr is not required and lr < 0.0: 35 | raise ValueError("Invalid learning rate: {}".format(lr)) 36 | if momentum < 0.0: 37 | raise ValueError("Invalid momentum value: {}".format(momentum)) 38 | if weight_decay < 0.0: 39 | raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) 40 | 41 | defaults = dict(lr=lr, momentum=momentum, dampening=dampening, 42 | weight_decay=weight_decay, nesterov=nesterov) 43 | if nesterov and (momentum <= 0 or dampening != 0): 44 | raise ValueError("Nesterov momentum requires a momentum and zero dampening") 45 | super(CentroidSGD, self).__init__(params, defaults) 46 | 47 | def __setstate__(self, state): 48 | super(CentroidSGD, self).__setstate__(state) 49 | for group in self.param_groups: 50 | group.setdefault('nesterov', False) 51 | 52 | def step(self, closure=None): 53 | """ 54 | Performs a single optimization step on the centroids. 55 | 56 | Args: 57 | - closure (callable, optional): A closure that reevaluates the model 58 | and returns the loss. 59 | 60 | Remarks: 61 | - The "reduce gradients" step is equivalent to (but 2x faster than) the following lines: 62 | ``` 63 | for k in range(n_centroids): 64 | mean_k = d_p_unroll[:, assignments == k].mean(dim=1, keepdim=True) 65 | d_p_unroll[:, assignments == k] = mean_k 66 | ``` 67 | """ 68 | 69 | loss = None 70 | if closure is not None: 71 | loss = closure() 72 | 73 | for group in self.param_groups: 74 | weight_decay = group['weight_decay'] 75 | momentum = group['momentum'] 76 | dampening = group['dampening'] 77 | nesterov = group['nesterov'] 78 | assignments = group['assignments'] 79 | kernel_size = group['kernel_size'] 80 | n_centroids = group['n_centroids'] 81 | n_blocks = group['n_blocks'] 82 | 83 | for p in group['params']: 84 | # recover gradient 85 | if p.grad is None: 86 | continue 87 | 88 | # unroll gradients 89 | d_p = p.grad.data 90 | d_p_unroll = reshape_weight(d_p) 91 | d_p_unroll = torch.cat(d_p_unroll.chunk(n_blocks, dim=0), dim=1) 92 | 93 | # reduce gradients 94 | select = assignments[:, None] == torch.arange(int(n_centroids), device=p.device) 95 | select = select.float() / torch.bincount(assignments).float() 96 | d_p_unroll = d_p_unroll.mm(select)[:, assignments] 97 | 98 | # roll gradients back 99 | conv = len(p.size()) == 4 100 | d_p = torch.cat(d_p_unroll.chunk(n_blocks, dim=1), dim=0) 101 | d_p = reshape_back_weight(d_p, k=kernel_size, conv=conv) 102 | 103 | # handle weight decay and momentum 104 | if weight_decay != 0: 105 | d_p.add_(weight_decay, p.data) 106 | if momentum != 0: 107 | param_state = self.state[p] 108 | if 'momentum_buffer' not in param_state: 109 | buf = param_state['momentum_buffer'] = torch.clone(d_p).detach() 110 | else: 111 | buf = param_state['momentum_buffer'] 112 | buf.mul_(momentum).add_(1 - dampening, d_p) 113 | if nesterov: 114 | d_p = d_p.add(momentum, buf) 115 | else: 116 | d_p = buf 117 | 118 | # SGD update 119 | p.data.add_(-group['lr'], d_p) 120 | 121 | return loss 122 | -------------------------------------------------------------------------------- /src/quantization/__init__.py: -------------------------------------------------------------------------------- 1 | ## Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | from .pq import PQ 9 | -------------------------------------------------------------------------------- /src/quantization/distance.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | from functools import reduce 9 | 10 | import torch 11 | import torch.nn as nn 12 | 13 | 14 | class ComputeDistances(nn.Module): 15 | """ Computes distances as described in the file em.py using the map/reduce paradigm. 16 | 17 | Args: 18 | - M: weight matrix 19 | - centroids: centroids used to compute the distance 20 | 21 | Remarks: 22 | - We split the input activations into up to 8 GPUs by relying on DataParallel. 23 | - The computation of distances is done per GPU with its chunk of activations (map) 24 | - The distances are then aggregated (reduce) 25 | 26 | """ 27 | def __init__(self, M, centroids): 28 | super(ComputeDistances, self).__init__() 29 | self.distances = nn.parallel.DataParallel(Distances(M, centroids)).cuda() 30 | self.reduce = Reduce() 31 | 32 | def forward(self, in_activations): 33 | return self.reduce(self.distances(in_activations)) 34 | 35 | def update_centroids(self, centroids): 36 | self.distances.module.centroids.data = centroids 37 | 38 | 39 | class Distances(nn.Module): 40 | """ 41 | Computes distances using broadcasting (map step). This layer automatically chunks the 42 | centroids and the weight matrix M so that the computation fits into the GPU 43 | 44 | Remarks: 45 | - The dimensions of the centroids and the weight matrix must be "chunkable enough" since 46 | we divide them by two until ths computation fits on the GPU 47 | - For debuging purposes, we advise the programmer to use only one GPU by setting 48 | CUDA_VISIBLE_DEVICES=1 49 | """ 50 | 51 | def __init__(self, M, centroids): 52 | super(Distances, self).__init__() 53 | self.M = nn.Parameter(M, requires_grad=False) 54 | self.centroids = nn.Parameter(centroids, requires_grad=False) 55 | 56 | def forward(self, in_activations): 57 | # two cases 58 | nb_M_chunks = 1 59 | nb_centroids_chunks = 1 60 | 61 | while True: 62 | try: 63 | return torch.cat([ 64 | torch.cat([ 65 | torch.matmul( 66 | in_activations[None, :, :], 67 | M_c[None, :, :] - centroids_c[:, :, None] 68 | ).norm(p=2, dim=1).pow(2) 69 | for centroids_c in self.centroids.chunk(nb_centroids_chunks, dim=0) 70 | ], dim=0) 71 | for M_c in self.M.chunk(nb_M_chunks, dim=1) 72 | ], dim=1) 73 | except RuntimeError: 74 | nb_M_chunks *= 2 75 | nb_centroids_chunks *= 2 76 | 77 | 78 | class Reduce(nn.Module): 79 | """ 80 | Reduces the distances per GPU accordingly (reduce step) 81 | 82 | Remarks: 83 | - Reduction is performed on GPU0 by default, which may lead to memory errors with too large 84 | a mode or a batch size. For debuging purposes, we advise the programmer to use only one GPU by setting CUDA_VISIBLE_DEVICES=1 85 | """ 86 | 87 | def __init__(self): 88 | super(Reduce, self).__init__() 89 | self.n_gpus = torch.cuda.device_count() 90 | 91 | def forward(self, distances): 92 | return reduce(lambda x, y: x + y, distances.chunk(self.n_gpus, dim=0)).sqrt() 93 | -------------------------------------------------------------------------------- /src/quantization/em.py: -------------------------------------------------------------------------------- 1 | ## Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import os 9 | import random 10 | from collections import Counter 11 | 12 | import torch 13 | import numpy as np 14 | 15 | from .solver import solve_stack 16 | from .distance import ComputeDistances 17 | 18 | 19 | class EM(): 20 | """ 21 | EM-like algorithm used to quantize the columns of M to minimize 22 | 23 | ||in_activations.mm(M - M_hat)||^2 24 | 25 | Args: 26 | - n_iter: number of k-means iterations 27 | - n_centroids: number of centroids 28 | - eps: for cluster reassignment when an empty cluster is found 29 | - verbose: print error after each iteration 30 | 31 | Remarks: 32 | - If one cluster is empty, the most populated cluster is split into 33 | two clusters 34 | - All the relevant dimensions are specified in the code 35 | """ 36 | 37 | def __init__(self, n_centroids, M, n_samples=-1, n_iter=20, eps=1e-8, verbose=True): 38 | # attributes 39 | self.n_centroids = n_centroids 40 | self.n_samples = n_samples 41 | self.n_iter = n_iter 42 | self.eps = eps 43 | self.verbose = verbose 44 | self.centroids = torch.Tensor() 45 | self.assignments = torch.Tensor() 46 | self.objective = [] 47 | 48 | def initialize_centroids(self, M): 49 | """ 50 | Initializes the centroids by sample random columns from M. 51 | 52 | Args: 53 | - M: weight matrix of size (in_features x out_features) 54 | """ 55 | 56 | in_features, out_features = M.size() 57 | indices = torch.randint(low=0, high=out_features, size=(self.n_centroids,)).long() 58 | self.centroids = M[:, indices].t() # (n_centroids x in_features) 59 | 60 | def step(self, in_activations, in_activations_eval, M, i): 61 | """ 62 | There are two standard steps for each iteration: expectation (E) and 63 | minimization (M). The E-step (assignment) is performed with an exhaustive 64 | search and the M-step (centroid computation) is performed with a solver. 65 | 66 | Args: 67 | - in_activations: input activations of size (n_samples x in_features) 68 | - M: weight matrix of size (in_features x out_features) 69 | 70 | Remarks: 71 | - The E-step heavily uses PyTorch broadcasting to speed up computations 72 | and reduce the memory overhead 73 | - The M-step uses a solver with a pre-computed pseudo-inverse so its 74 | complexity is only one matrix multiplication 75 | - With the size constraints, we have out_activations = in_activations.mm(M) 76 | - Evaluation on a fixed batch of activations 77 | """ 78 | 79 | # network for parallelization of computations 80 | self.compute_distances_parallel = ComputeDistances(M, self.centroids) 81 | 82 | # pre-compute A_pinv to factorize computations, on CPU to avoid CUDA oom error 83 | A_pinv = torch.pinverse(in_activations) 84 | 85 | # assignments (E-step) 86 | distances = self.compute_distances(in_activations) # (n_centroids x out_features) 87 | self.assignments = torch.argmin(distances, dim=0) # (out_features) 88 | 89 | # empty clusters 90 | counts = Counter(map(lambda x: x.item(), self.assignments)) 91 | empty_clusters = set(range(self.n_centroids)) - set(counts.keys()) 92 | n_empty_clusters = len(empty_clusters) 93 | 94 | while len(empty_clusters) > 0: 95 | # given an empty cluster, find most populated cluster and split it into two 96 | k = random.choice(list(empty_clusters)) 97 | m = counts.most_common(1)[0][0] 98 | e = torch.randn_like(self.centroids[m]) * self.eps 99 | self.centroids[k] = self.centroids[m].clone() 100 | self.centroids[k] += e 101 | self.centroids[m] -= e 102 | print(k, len(empty_clusters)) 103 | 104 | # recompute assignments 105 | distances = self.compute_distances(in_activations) # (n_centroids x out_features) 106 | self.assignments = torch.argmin(distances, dim=0) # (out_features) 107 | 108 | # check for empty clusters 109 | counts = Counter(map(lambda x: x.item(), self.assignments)) 110 | empty_clusters = set(range(self.n_centroids)) - set(counts.keys()) 111 | 112 | # centroids (M-step) 113 | for k in range(self.n_centroids): 114 | M_k = M[:, self.assignments == k] # (in_features x size_of_cluster_k) 115 | B = in_activations.mm(M_k) 116 | self.centroids[k] = solve_stack(A=in_activations, B=B, A_pinv=A_pinv) # (in_features) 117 | 118 | # book-keeping 119 | n_samples_eval = 128 120 | in_activations_eval = in_activations_eval[:n_samples_eval] 121 | normalize = np.sqrt(n_samples_eval * len(self.assignments)) # np.sqrt(out_activations.numel()) 122 | obj = (in_activations_eval.mm(self.centroids[self.assignments].t() - M)).norm(p=2).div(normalize).item() # (n_samples x in_features).mm((out_features x in_features).t()) -> (n_samples x out_features) -> 1 123 | self.objective.append(obj) 124 | if self.verbose: print("Iteration: {},\t objective: {:.6f},\t resolved empty clusters: {}".format(i, obj, n_empty_clusters)) 125 | 126 | def compute_distances(self, in_activations): 127 | """ 128 | For every centroid m and every input activation in_activation, computes 129 | 130 | ||in_activations.mm(M - m[None, :])||_2 131 | 132 | Args: 133 | - in_activations: input activations of size (n_samples x in_features) 134 | - M: weight matrix of size (in_features x out_features) 135 | - centroids: centroids of size (n_centroids x in_features) 136 | 137 | Remarks: 138 | - We rely on PyTorch's broadcasting to speed up computations 139 | and reduce the memory overhead 140 | - Without chunking, the sizes in the broadcasting are modified as: 141 | (n_centroids x n_samples x out_features) -> (n_centroids x out_features) 142 | - The broadcasting computation is automatically chunked so that 143 | the tensors fit into the memory of the GPU 144 | """ 145 | 146 | self.compute_distances_parallel.update_centroids(self.centroids) 147 | return self.compute_distances_parallel(in_activations) 148 | 149 | def assign(self, in_activations, M): 150 | """ 151 | Assigns each column of M to its closest centroid, thus essentially 152 | performing the E-step in train(). 153 | 154 | Args: 155 | - in_activations: input activations of size (n_samples x in_features) 156 | - M: weight matrix of size (in_features x out_features) 157 | 158 | Remarks: 159 | - The function must be called after train() or after loading 160 | centroids using self.load(), otherwise it will return empty tensors 161 | - The assignments may differ from self.assignments when this function 162 | is called with distinct parameters in_activations and M 163 | """ 164 | 165 | # network for parallelization of computations 166 | self.compute_distances_parallel = ComputeDistances(M, self.centroids) 167 | 168 | distances = self.compute_distances(in_activations) # (n_centroids x out_features) 169 | assignments = torch.argmin(distances, dim=0) # (out_features) 170 | 171 | return assignments 172 | 173 | def save(self, path, layer): 174 | """ 175 | Saves centroids and assignments. 176 | 177 | Args: 178 | - path: folder used to save centroids and assignments 179 | """ 180 | 181 | torch.save(self.centroids, os.path.join(path, '{}_centroids.pth'.format(layer))) 182 | torch.save(self.assignments, os.path.join(path, '{}_assignments.pth'.format(layer))) 183 | torch.save(self.objective, os.path.join(path, '{}_objective.pth'.format(layer))) 184 | 185 | def load(self, path, layer): 186 | """ 187 | Loads centroids and assignments from a given path 188 | 189 | Args: 190 | - path: folder use to load centroids and assignments 191 | """ 192 | 193 | self.centroids = torch.load(os.path.join(path, '{}_centroids.pth'.format(layer))) 194 | self.assignments = torch.load(os.path.join(path, '{}_assignments.pth'.format(layer))) 195 | self.objective = torch.load(os.path.join(path, '{}_objective.pth'.format(layer))) 196 | -------------------------------------------------------------------------------- /src/quantization/pq.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import torch 9 | 10 | from .em import EM 11 | from utils.reshape import reshape_weight, reshape_back_weight, reshape_activations 12 | 13 | 14 | class PQ(EM): 15 | """ 16 | Quantizes the layer M by taking into account the input activations. 17 | The columns are split into n_blocks blocks and a *joint* quantizer 18 | is learnt for all the blocks. 19 | 20 | Args: 21 | - in_features: future size(0) of the weight matrix 22 | - n_centroids: number of centroids per subquantizer 23 | - n_iter: number of k-means iterations 24 | - n_blocks: number of subquantizers 25 | 26 | Remarks: 27 | - For efficiency, we subsample the input activations 28 | """ 29 | 30 | def __init__(self, in_activations, M, n_activations=100, n_samples=1000, eps=1e-8, sample=True, 31 | n_blocks=8, n_centroids=512, n_iter=20, k=3, stride=(1, 1), padding=(1, 1), groups=1): 32 | super(PQ, self).__init__(n_centroids, M, eps=eps) 33 | self.n_activations = n_activations 34 | self.n_samples = n_samples 35 | self.sample = sample 36 | self.n_blocks = n_blocks 37 | self.n_iter = n_iter 38 | self.k = k 39 | self.stride = stride 40 | self.padding = padding 41 | self.groups = groups 42 | # reshape activations and weight in the case of convolutions 43 | self.conv = len(M.size()) == 4 44 | self._reshape(in_activations, M) 45 | # sanity check 46 | assert self.M.size(0) % n_blocks == 0, "n_blocks must be a multiple of in_features" 47 | # initialize centroids 48 | M_reshaped = self.sample_weights() 49 | self.initialize_centroids(M_reshaped) 50 | 51 | def _reshape(self, in_activations, M): 52 | """ 53 | Rehshapes if conv or fully-connected. 54 | """ 55 | 56 | self.M = reshape_weight(M) 57 | self.in_activations = reshape_activations(in_activations, 58 | k=self.k, 59 | stride=self.stride, 60 | padding=self.padding, 61 | groups=self.groups) 62 | 63 | def unroll_activations(self, in_activations): 64 | """ 65 | Unroll activations. 66 | """ 67 | 68 | return torch.cat(in_activations.chunk(self.n_blocks, dim=1), dim=0) 69 | 70 | def unroll_weight(self, M): 71 | """ 72 | Unroll weights. 73 | """ 74 | 75 | return torch.cat(M.chunk(self.n_blocks, dim=0), dim=1) 76 | 77 | def sample_activations(self): 78 | """ 79 | Sample activations. 80 | """ 81 | 82 | # get indices 83 | in_features = self.M.size(1) 84 | indices = torch.randint(low=0, high=self.in_activations.size(0), size=(self.n_samples // in_features,)).long() 85 | 86 | # sample current in_activations 87 | in_activations = self.unroll_activations(self.in_activations[indices]) 88 | return in_activations.cuda() 89 | 90 | def sample_weights(self): 91 | """ 92 | Sample weights (no sampling done here, only the unrolling). 93 | """ 94 | 95 | return self.unroll_weight(self.M).cuda() 96 | 97 | def encode(self): 98 | """ 99 | Args: 100 | - in_activations: input activations of size (n_samples x in_features) 101 | - M: weight matrix of the layer, of size (in_features x out_features) 102 | """ 103 | 104 | # initialize sampling 105 | in_activations_reshaped_eval = self.sample_activations() 106 | in_activations_reshaped = self.sample_activations() 107 | M_reshaped = self.sample_weights() 108 | 109 | # perform EM training steps 110 | for i in range(self.n_iter): 111 | if self.sample: 112 | in_activations_reshaped = self.sample_activations() 113 | self.step(in_activations_reshaped, in_activations_reshaped_eval, M_reshaped, i) 114 | 115 | def decode(self, redo=False): 116 | """ 117 | Args: 118 | - in_activations: input activations of size (n_samples x in_features)d 119 | - M: weight matrix of the layer, of size (in_features x out_features) 120 | """ 121 | # use given activations to assign weightsgiven self.centroids 122 | if redo: 123 | in_activations_reshaped = self.sample_activations() 124 | M_reshaped = self.sample_weights() 125 | assignments = self.assign(in_activations_reshaped, M_reshaped) 126 | self.assignments = assignments 127 | else: 128 | assignments = self.assignments 129 | 130 | M_hat_reshaped = torch.cat(self.centroids[assignments].t().chunk(self.n_blocks, dim=1), dim=0) 131 | return reshape_back_weight(M_hat_reshaped, k=self.k, conv=self.conv) 132 | -------------------------------------------------------------------------------- /src/quantization/solver.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import torch 9 | 10 | 11 | def solve_stack(A, B, A_pinv=None): 12 | """ 13 | Finds the minimizer X of ||A[X, X, ..., X] - B||^2 14 | using the pseudo-inverse of A. 15 | 16 | Args: 17 | - A: weight matrix of size (n x p) 18 | - B: bias matrix of size (n x q) 19 | - A_pinv: the pseudo-inverse of A of size (p x n) (optional) 20 | 21 | Remarks: 22 | - The pseudo-inverse of A can be passed as an argument to factor 23 | computations when solve_stack is called many times with the same 24 | matrix A 25 | - The unknown X is of size (p x 1). Here, [X, X, ..., X] denotes the 26 | column vector X stacked q times horizontally 27 | """ 28 | 29 | A_pinv = torch.pinverse(A) if A_pinv is None else A_pinv 30 | return torch.matmul(A_pinv, B.sum(dim=1)) / B.size(1) 31 | -------------------------------------------------------------------------------- /src/quantize.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import os 9 | import time 10 | import math 11 | import argparse 12 | from operator import attrgetter 13 | from bisect import bisect_left 14 | 15 | import numpy as np 16 | 17 | import torch 18 | import torch.nn as nn 19 | import torch.optim 20 | import torch.backends.cudnn as cudnn 21 | 22 | import models 23 | from data import load_data 24 | from optim import CentroidSGD 25 | from quantization import PQ 26 | from utils.training import finetune_centroids, evaluate 27 | from utils.watcher import ActivationWatcher 28 | from utils.dynamic_sampling import dynamic_sampling 29 | from utils.statistics import compute_size 30 | from utils.utils import centroids_from_weights, weight_from_centroids 31 | 32 | 33 | parser = argparse.ArgumentParser(description='And the bit goes down: Revisiting the quantization of neural networks') 34 | 35 | parser.add_argument('--model', default='resnet18', choices=['resnet18', 'resnet50'], 36 | help='Pretrained model to quantize') 37 | parser.add_argument('--block', default='all', type=str, 38 | help='Block to quantize (if all, quantizes whole network)') 39 | 40 | parser.add_argument('--n-iter', default=100, type=int, 41 | help='Number of EM iterations for quantization') 42 | parser.add_argument('--n-activations', default=1024, type=int, 43 | help='Size of the batch of activations to sample from') 44 | 45 | parser.add_argument('--block-size-cv', default=9, type=int, 46 | help='Quantization block size for 3x3 standard convolutions') 47 | parser.add_argument('--block-size-pw', default=4, type=int, 48 | help='Quantization block size for 1x1 convolutions') 49 | parser.add_argument('--block-size-fc', default=4, type=int, 50 | help='Quantization block size for fully-connected layers') 51 | 52 | parser.add_argument('--n-centroids-cv', default=256, type=int, 53 | help='Number of centroids') 54 | parser.add_argument('--n-centroids-pw', default=256, type=int, 55 | help='Number of centroids for pointwise convolutions') 56 | parser.add_argument('--n-centroids-fc', default=2048, type=int, 57 | help='Number of centroids for classifier') 58 | 59 | parser.add_argument('--n-centroids-threshold', default=4, type=int, 60 | help='Threshold for reducing the number of centroids') 61 | parser.add_argument('--eps', default=1e-8, type=float, 62 | help='For empty cluster resolution') 63 | 64 | parser.add_argument('--data-path', default='/datasets01/imagenet_full_size/061417/', type=str, 65 | help='Path to ImageNet dataset') 66 | parser.add_argument('--batch-size', default=128, type=int, 67 | help='Batch size for fiuetuning steps') 68 | parser.add_argument('--n-workers', default=20, type=int, 69 | help='Number of workers for data loading') 70 | 71 | parser.add_argument('--finetune-centroids', default=2500, type=int, 72 | help='Number of iterations for layer-wise finetuning of the centroids') 73 | parser.add_argument('--lr-centroids', default=0.05, type=float, 74 | help='Learning rate to finetune centroids') 75 | parser.add_argument('--momentum-centroids', default=0.9, type=float, 76 | help='Momentum when using SGD') 77 | parser.add_argument('--weight-decay-centroids', default=1e-4, type=float, 78 | help='Weight decay') 79 | 80 | parser.add_argument('--finetune-whole', default=10000, type=int, 81 | help='Number of iterations for global finetuning of the centroids') 82 | parser.add_argument('--lr-whole', default=0.01, type=float, 83 | help='Learning rate to finetune classifier') 84 | parser.add_argument('--momentum-whole', default=0.9, type=float, 85 | help='Momentum when using SGD') 86 | parser.add_argument('--weight-decay-whole', default=1e-4, type=float, 87 | help='Weight decay') 88 | parser.add_argument('--finetune-whole-epochs', default=9, type=int, 89 | help='Number of epochs for global finetuning of the centroids') 90 | parser.add_argument('--finetune-whole-step-size', default=3, type=int, 91 | help='Learning rate schedule for global finetuning of the centroids') 92 | 93 | parser.add_argument('--restart', default='', type=str, 94 | help='Already stored centroids') 95 | parser.add_argument('--save', default='', type=str, 96 | help='Path to save the finetuned models') 97 | 98 | 99 | def main(): 100 | # get arguments 101 | global args 102 | args = parser.parse_args() 103 | args.block = '' if args.block == 'all' else args.block 104 | 105 | # student model to quantize 106 | student = models.__dict__[args.model](pretrained=True).cuda() 107 | student.eval() 108 | criterion = nn.CrossEntropyLoss().cuda() 109 | cudnn.benchmark = True 110 | 111 | # layers to quantize (we do not quantize the first 7x7 convolution layer) 112 | watcher = ActivationWatcher(student) 113 | layers = [layer for layer in watcher.layers[1:] if args.block in layer] 114 | 115 | # data loading code 116 | train_loader, test_loader = load_data(data_path=args.data_path, batch_size=args.batch_size, nb_workers=args.n_workers) 117 | 118 | # parameters for the centroids optimizer 119 | opt_centroids_params_all = [] 120 | 121 | # book-keeping for compression statistics (in MB) 122 | size_uncompressed = compute_size(student) 123 | size_index = 0 124 | size_centroids = 0 125 | size_other = size_uncompressed 126 | 127 | # teacher model 128 | teacher = models.__dict__[args.model](pretrained=True).cuda() 129 | teacher.eval() 130 | 131 | # Step 1: iteratively quantize the network layers (quantization + layer-wise centroids distillation) 132 | print('Step 1: Quantize network') 133 | t = time.time() 134 | top_1 = 0 135 | 136 | for layer in layers: 137 | # gather input activations 138 | n_iter_activations = math.ceil(args.n_activations / args.batch_size) 139 | watcher = ActivationWatcher(student, layer=layer) 140 | in_activations_current = watcher.watch(train_loader, criterion, n_iter_activations) 141 | in_activations_current = in_activations_current[layer] 142 | 143 | # get weight matrix and detach it from the computation graph (.data should be enough, adding .detach() as a safeguard) 144 | M = attrgetter(layer + '.weight.data')(student).detach() 145 | sizes = M.size() 146 | is_conv = len(sizes) == 4 147 | 148 | # get padding and stride attributes 149 | padding = attrgetter(layer)(student).padding if is_conv else 0 150 | stride = attrgetter(layer)(student).stride if is_conv else 1 151 | groups = attrgetter(layer)(student).groups if is_conv else 1 152 | 153 | # block size, distinguish between fully connected and convolutional case 154 | if is_conv: 155 | out_features, in_features, k, _ = sizes 156 | block_size = args.block_size_cv if k > 1 else args.block_size_pw 157 | n_centroids = args.n_centroids_cv if k > 1 else args.n_centroids_pw 158 | n_blocks = in_features * k * k // block_size 159 | else: 160 | k = 1 161 | out_features, in_features = sizes 162 | block_size = args.block_size_fc 163 | n_centroids = args.n_centroids_fc 164 | n_blocks = in_features // block_size 165 | 166 | # clamp number of centroids for stability 167 | powers = 2 ** np.arange(0, 16, 1) 168 | n_vectors = np.prod(sizes) / block_size 169 | idx_power = bisect_left(powers, n_vectors / args.n_centroids_threshold) 170 | n_centroids = min(n_centroids, powers[idx_power - 1]) 171 | 172 | # compression rations 173 | bits_per_weight = np.log2(n_centroids) / block_size 174 | 175 | # number of bits per weight 176 | size_index_layer = bits_per_weight * M.numel() / 8 / 1024 / 1024 177 | size_index += size_index_layer 178 | 179 | # centroids stored in float16 180 | size_centroids_layer = n_centroids * block_size * 2 / 1024 / 1024 181 | size_centroids += size_centroids_layer 182 | 183 | # size of non-compressed layers, e.g. BatchNorms or first 7x7 convolution 184 | size_uncompressed_layer = M.numel() * 4 / 1024 / 1024 185 | size_other -= size_uncompressed_layer 186 | 187 | # number of samples 188 | n_samples = dynamic_sampling(layer) 189 | 190 | # print layer size 191 | print('Quantizing layer: {}, size: {}, n_blocks: {}, block size: {}, ' \ 192 | 'centroids: {}, bits/weight: {:.2f}, compressed size: {:.2f} MB'.format( 193 | layer, list(sizes), n_blocks, block_size, n_centroids, 194 | bits_per_weight, size_index_layer + size_centroids_layer)) 195 | 196 | # quantizer 197 | quantizer = PQ(in_activations_current, M, n_activations=args.n_activations, 198 | n_samples=n_samples, eps=args.eps, n_centroids=n_centroids, 199 | n_iter=args.n_iter, n_blocks=n_blocks, k=k, 200 | stride=stride, padding=padding, groups=groups) 201 | 202 | if len(args.restart) > 0: 203 | # do not quantize already quantized layers 204 | try: 205 | # load centroids and assignments if already stored 206 | quantizer.load(args.restart, layer) 207 | centroids = quantizer.centroids 208 | assignments = quantizer.assignments 209 | 210 | # quantize weight matrix 211 | M_hat = weight_from_centroids(centroids, assignments, n_blocks, k, is_conv) 212 | attrgetter(layer + '.weight')(student).data = M_hat 213 | quantizer.save(args.save, layer) 214 | 215 | # optimizer for global finetuning 216 | parameters = [p for (n, p) in student.named_parameters() if layer in n and 'bias' not in n] 217 | centroids_params = {'params': parameters, 218 | 'assignments': assignments, 219 | 'kernel_size': k, 220 | 'n_centroids': n_centroids, 221 | 'n_blocks': n_blocks} 222 | opt_centroids_params_all.append(centroids_params) 223 | 224 | # proceed to next layer 225 | print('Layer already quantized, proceeding to next layer\n') 226 | continue 227 | 228 | # otherwise, quantize layer 229 | except FileNotFoundError: 230 | print('Quantizing layer') 231 | 232 | # quantize layer 233 | quantizer.encode() 234 | 235 | # assign quantized weight matrix 236 | M_hat = quantizer.decode() 237 | attrgetter(layer + '.weight')(student).data = M_hat 238 | 239 | # top1 240 | top_1 = evaluate(test_loader, student, criterion).item() 241 | 242 | # book-keeping 243 | print('Quantizing time: {:.0f}min, Top1 after quantization: {:.2f}\n'.format((time.time() - t) / 60, top_1)) 244 | t = time.time() 245 | 246 | # Step 2: finetune centroids 247 | print('Finetuning centroids') 248 | 249 | # optimizer for centroids 250 | parameters = [p for (n, p) in student.named_parameters() if layer in n and 'bias' not in n] 251 | assignments = quantizer.assignments 252 | centroids_params = {'params': parameters, 253 | 'assignments': assignments, 254 | 'kernel_size': k, 255 | 'n_centroids': n_centroids, 256 | 'n_blocks': n_blocks} 257 | 258 | # remember centroids parameters to finetuning at the end 259 | opt_centroids_params = [centroids_params] 260 | opt_centroids_params_all.append(centroids_params) 261 | 262 | # custom optimizer 263 | optimizer_centroids = CentroidSGD(opt_centroids_params, lr=args.lr_centroids, 264 | momentum=args.momentum_centroids, 265 | weight_decay=args.weight_decay_centroids) 266 | 267 | # standard training loop 268 | n_iter = args.finetune_centroids 269 | scheduler = torch.optim.lr_scheduler.StepLR(optimizer_centroids, step_size=1, gamma=0.1) 270 | 271 | for epoch in range(1): 272 | finetune_centroids(train_loader, student, teacher, criterion, optimizer_centroids, n_iter=n_iter) 273 | top_1 = evaluate(test_loader, student, criterion) 274 | scheduler.step() 275 | print('Epoch: {}, Top1: {:.2f}'.format(epoch, top_1)) 276 | 277 | print('After {} iterations with learning rate {}, Top1: {:.2f}'.format(n_iter, args.lr_centroids, top_1)) 278 | 279 | # book-keeping 280 | print('Finetuning centroids time: {:.0f}min, Top1 after finetuning centroids: {:.2f}\n'.format((time.time() - t) / 60, top_1)) 281 | t = time.time() 282 | 283 | # saving 284 | M_hat = attrgetter(layer + '.weight')(student).data 285 | centroids = centroids_from_weights(M_hat, assignments, n_centroids, n_blocks) 286 | quantizer.centroids = centroids 287 | quantizer.save(args.save, layer) 288 | 289 | # End of compression + finetuning of centroids 290 | size_compressed = size_index + size_centroids + size_other 291 | print('End of compression, non-compressed teacher model: {:.2f}MB, compressed student model ' \ 292 | '(indexing + centroids + other): {:.2f}MB + {:.2f}MB + {:.2f}MB = {:.2f}MB, compression ratio: {:.2f}x\n'.format( 293 | size_uncompressed, size_index, size_centroids, size_other, size_compressed, size_uncompressed / size_compressed)) 294 | 295 | # Step 3: finetune whole network 296 | print('Step 3: Finetune whole network') 297 | t = time.time() 298 | 299 | # custom optimizer 300 | optimizer_centroids_all = CentroidSGD(opt_centroids_params_all, lr=args.lr_whole, 301 | momentum=args.momentum_whole, 302 | weight_decay=args.weight_decay_whole) 303 | 304 | # standard training loop 305 | n_iter = args.finetune_whole 306 | scheduler = torch.optim.lr_scheduler.StepLR(optimizer_centroids_all, step_size=args.finetune_whole_step_size, gamma=0.1) 307 | 308 | for epoch in range(args.finetune_whole_epochs): 309 | student.train() 310 | finetune_centroids(train_loader, student, teacher, criterion, optimizer_centroids_all, n_iter=n_iter) 311 | top_1 = evaluate(test_loader, student, criterion) 312 | scheduler.step() 313 | print('Epoch: {}, Top1: {:.2f}'.format(epoch, top_1)) 314 | 315 | # state dict pf compressed model 316 | state_dict_compressed = {} 317 | 318 | # save conv1 (not quantized) 319 | state_dict_compressed['conv1'] = student.conv1.state_dict() 320 | 321 | # save biases of the classifier 322 | state_dict_compressed['fc_bias'] = {'bias': student.fc.bias} 323 | 324 | # save batch norms 325 | bn_layers = watcher._get_bn_layers() 326 | 327 | for bn_layer in bn_layers: 328 | state_dict_compressed[bn_layer] = attrgetter(bn_layer)(student).state_dict() 329 | 330 | # save quantized layers 331 | for layer in layers: 332 | 333 | # stats 334 | M = attrgetter(layer + '.weight.data')(student).detach() 335 | sizes = M.size() 336 | is_conv = len(sizes) == 4 337 | 338 | # get padding and stride attributes 339 | padding = attrgetter(layer)(student).padding if is_conv else 0 340 | stride = attrgetter(layer)(student).stride if is_conv else 1 341 | groups = attrgetter(layer)(student).groups if is_conv else 1 342 | 343 | # block size, distinguish between fully connected and convolutional case 344 | if is_conv: 345 | out_features, in_features, k, _ = sizes 346 | block_size = args.block_size_cv if k > 1 else args.block_size_pw 347 | n_centroids = args.n_centroids_cv 348 | n_blocks = in_features * k * k // block_size 349 | else: 350 | k = 1 351 | out_features, in_features = sizes 352 | block_size = args.block_size_fc 353 | n_centroids = args.n_centroids_fc 354 | n_blocks = in_features // block_size 355 | 356 | # clamp number of centroids for stability 357 | powers = 2 ** np.arange(0, 16, 1) 358 | n_vectors = np.prod(sizes) / block_size 359 | idx_power = bisect_left(powers, n_vectors / args.n_centroids_threshold) 360 | n_centroids = min(n_centroids, powers[idx_power - 1]) 361 | 362 | # save 363 | quantizer.load(args.save, layer) 364 | assignments = quantizer.assignments 365 | M_hat = attrgetter(layer + '.weight')(student).data 366 | centroids = centroids_from_weights(M_hat, assignments, n_centroids, n_blocks) 367 | quantizer.centroids = centroids 368 | quantizer.save(args.save, layer) 369 | state_dict_layer = { 370 | 'centroids': centroids.half(), 371 | 'assignments': assignments.short() if 'fc' in layer else assignments.byte(), 372 | 'n_blocks': n_blocks, 373 | 'is_conv': is_conv, 374 | 'k': k 375 | } 376 | state_dict_compressed[layer] = state_dict_layer 377 | 378 | # save model 379 | torch.save(state_dict_compressed, os.path.join(args.save, 'state_dict_compressed.pth')) 380 | 381 | # book-keeping 382 | print('Finetuning whole network time: {:.0f}min, Top1 after finetuning centroids: {:.2f}\n'.format((time.time() - t) / 60, top_1)) 383 | 384 | 385 | if __name__ == '__main__': 386 | main() 387 | -------------------------------------------------------------------------------- /src/utils/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | -------------------------------------------------------------------------------- /src/utils/dynamic_sampling.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | def dynamic_sampling(layer): 9 | """ 10 | Number of activations (after reshaping) to sample from a given layer (see ) 11 | """ 12 | 13 | if 'layer1' in layer or 'layer2' in layer: 14 | return 1000 15 | elif 'layer3' in layer or 'layer4' in layer: 16 | return 25000 17 | elif 'fc' in layer or 'classifier' in layer: 18 | return 5000 19 | else: 20 | return ValueError(layer) 21 | -------------------------------------------------------------------------------- /src/utils/reshape.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import torch 9 | import torch.nn.functional as F 10 | 11 | 12 | def reshape_weight(weight): 13 | """ 14 | C_out x C_in x k x k -> (C_in x k x k) x C_out. 15 | """ 16 | 17 | if len(weight.size()) == 4: 18 | C_out, C_in, k, k = weight.size() 19 | return weight.view(C_out, C_in * k * k).t() 20 | else: 21 | return weight.t() 22 | 23 | 24 | def reshape_back_weight(weight, k=3, conv=True): 25 | """ 26 | (C_in x k x k) x C_out -> C_out x C_in x k x k. 27 | """ 28 | 29 | if conv: 30 | C_in_, C_out = weight.size() 31 | C_in = C_in_ // (k * k) 32 | return weight.t().view(C_out, C_in, k, k) 33 | else: 34 | return weight.t() 35 | 36 | 37 | def reshape_activations(activations, k=3, stride=(1, 1), padding=(1, 1), groups=1): 38 | """ 39 | N x C_in x H x W -> (N x H x W) x C_in. 40 | """ 41 | 42 | if len(activations.size()) == 4: 43 | # gather activations 44 | a_padded = F.pad(activations, (padding[1], padding[1], padding[0], padding[0])) 45 | N, C, H, W = a_padded.size() 46 | a_stacked = [] 47 | 48 | for i in range(0, H - k + 1, stride[0]): 49 | for j in range(0, W - k + 1, stride[1]): 50 | a_stacked.append(a_padded[:, :, i:i + k, j:j + k]) 51 | 52 | # reshape according to weight 53 | a_reshaped = reshape_weight(torch.cat(a_stacked, dim=0)).t() 54 | 55 | # group convolutions (e.g. depthwise convolutions) 56 | a_reshaped_groups = torch.cat(a_reshaped.chunk(groups, dim=1), dim=0) 57 | 58 | return a_reshaped_groups 59 | 60 | else: 61 | return activations 62 | -------------------------------------------------------------------------------- /src/utils/statistics.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | def compute_size(model): 9 | """ 10 | Size of model (in MB). 11 | """ 12 | 13 | res = 0 14 | for n, p in model.named_parameters(): 15 | res += p.numel() 16 | 17 | return res * 4 / 1024 / 1024 18 | -------------------------------------------------------------------------------- /src/utils/training.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import time 9 | 10 | import torch 11 | import torch.nn.functional as F 12 | 13 | 14 | def finetune_centroids(train_loader, student, teacher, criterion, optimizer, epoch=0, n_iter=-1, verbose=False): 15 | """ 16 | Student/teacher distillation training loop. 17 | 18 | Remarks: 19 | - The student has to be in train() mode as this function will not 20 | automatically switch to it for finetuning purposes 21 | """ 22 | 23 | n_iter = len(train_loader) if n_iter == -1 else n_iter 24 | modulo = 0 if verbose else -1 25 | batch_time = AverageMeter('Time', ':6.3f') 26 | data_time = AverageMeter('Data', ':6.3f') 27 | losses = AverageMeter('Loss', ':.4e') 28 | top1 = AverageMeter('Acc@1', ':6.2f') 29 | top5 = AverageMeter('Acc@5', ':6.2f') 30 | progress = ProgressMeter(len(train_loader), batch_time, data_time, losses, top1, 31 | top5, prefix="Epoch: [{}]".format(epoch)) 32 | 33 | end = time.time() 34 | for i, (input, target) in enumerate(train_loader): 35 | # early stop 36 | if i >= n_iter: break 37 | 38 | # measure data oading time 39 | data_time.update(time.time() - end) 40 | 41 | # cuda 42 | input = input.cuda() 43 | target = target.cuda() 44 | 45 | # compute output 46 | output = student(input) 47 | 48 | # measure accuracy and record loss 49 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 50 | top1.update(acc1[0], input.size(0)) 51 | top5.update(acc5[0], input.size(0)) 52 | 53 | # compute loss, see KL Divergence documentation of PyTorch 54 | student_logits = F.log_softmax(output, dim=1) 55 | with torch.no_grad(): teacher_probs = F.softmax(teacher(input), dim=1) 56 | loss = F.kl_div(student_logits, teacher_probs, reduction='batchmean') 57 | losses.update(loss.item(), input.size(0)) 58 | 59 | # compute gradient and do SGD step 60 | optimizer.zero_grad() 61 | loss.backward() 62 | optimizer.step() 63 | 64 | # measure elapsed time 65 | batch_time.update(time.time() - end) 66 | end = time.time() 67 | 68 | if i % 10 == modulo: 69 | progress.print(i) 70 | 71 | return top1.avg 72 | 73 | 74 | def evaluate(test_loader, model, criterion, n_iter=-1, verbose=False, device='cuda'): 75 | """ 76 | Standard evaluation loop. 77 | """ 78 | 79 | n_iter = len(test_loader) if n_iter == -1 else n_iter 80 | modulo = 0 if verbose else -1 81 | batch_time = AverageMeter('Time', ':6.3f') 82 | losses = AverageMeter('Loss', ':.4e') 83 | top1 = AverageMeter('Acc@1', ':6.2f') 84 | top5 = AverageMeter('Acc@5', ':6.2f') 85 | progress = ProgressMeter(len(test_loader), batch_time, losses, top1, top5, prefix='Test: ') 86 | 87 | # switch to evaluate mode 88 | model.eval() 89 | 90 | with torch.no_grad(): 91 | end = time.time() 92 | for i, (input, target) in enumerate(test_loader): 93 | # early stop 94 | if i >= n_iter: break 95 | 96 | # cuda 97 | input = input.cuda() if device == 'cuda' else input 98 | target = target.cuda() if device == 'cuda' else target 99 | 100 | # compute output 101 | output = model(input) 102 | loss = criterion(output, target) 103 | 104 | # measure accuracy and record loss 105 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 106 | losses.update(loss.item(), input.size(0)) 107 | top1.update(acc1[0], input.size(0)) 108 | top5.update(acc5[0], input.size(0)) 109 | 110 | # measure elapsed time 111 | batch_time.update(time.time() - end) 112 | end = time.time() 113 | 114 | if i % 10 == modulo: 115 | progress.print(i) 116 | 117 | return top1.avg 118 | 119 | 120 | class AverageMeter(object): 121 | """ 122 | Computes and stores the average and current value. 123 | """ 124 | 125 | def __init__(self, name, fmt=':f'): 126 | self.name = name 127 | self.fmt = fmt 128 | self.reset() 129 | 130 | def reset(self): 131 | self.val = 0 132 | self.avg = 0 133 | self.sum = 0 134 | self.count = 0 135 | 136 | def update(self, val, n=1): 137 | self.val = val 138 | self.sum += val * n 139 | self.count += n 140 | self.avg = self.sum / self.count 141 | 142 | def __str__(self): 143 | fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' 144 | return fmtstr.format(**self.__dict__) 145 | 146 | 147 | class ProgressMeter(object): 148 | """ 149 | Pretty and compact metric printer. 150 | """ 151 | 152 | def __init__(self, num_batches, *meters, prefix=""): 153 | self.batch_fmtstr = self._get_batch_fmtstr(num_batches) 154 | self.meters = meters 155 | self.prefix = prefix 156 | 157 | def print(self, batch): 158 | entries = [self.prefix + self.batch_fmtstr.format(batch)] 159 | entries += [str(meter) for meter in self.meters] 160 | print('\t'.join(entries)) 161 | 162 | def _get_batch_fmtstr(self, num_batches): 163 | num_digits = len(str(num_batches // 1)) 164 | fmt = '{:' + str(num_digits) + 'd}' 165 | return '[' + fmt + '/' + fmt.format(num_batches) + ']' 166 | 167 | 168 | def accuracy(output, target, topk=(1,)): 169 | """ 170 | Computes the accuracy over the k top predictions for the specified values of k. 171 | """ 172 | 173 | with torch.no_grad(): 174 | maxk = max(topk) 175 | batch_size = target.size(0) 176 | 177 | _, pred = output.topk(maxk, 1, True, True) 178 | pred = pred.t() 179 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 180 | 181 | res = [] 182 | for k in topk: 183 | correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) 184 | res.append(correct_k.mul_(100.0 / batch_size)) 185 | return res 186 | -------------------------------------------------------------------------------- /src/utils/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import torch 9 | from .reshape import reshape_weight, reshape_back_weight 10 | 11 | 12 | def centroids_from_weights(M, assignments, n_centroids, n_blocks): 13 | """ 14 | Recovers the centroids from an already quantized matrix M. 15 | 16 | Args: 17 | - M: already quantized matrix 18 | - assignments: size (n_vectors) 19 | - n_centroids: number of centroids 20 | - n_blocks: niumber of blocks per column 21 | 22 | Remarks: 23 | - This function assumes that all the clusters are non-empty 24 | - This function consists in two steps: 25 | (1) reshape the 2D/4D matrix (whether fully-connected or convolutional) into a 2D matrix 26 | (2) unroll the obtained 2D matrix according to the number of blocks 27 | """ 28 | 29 | M_reshaped = reshape_weight(M) 30 | M_unrolled = torch.cat(M_reshaped.chunk(n_blocks, dim=0), dim=1) 31 | size_block = M_unrolled.size(0) 32 | centroids = torch.zeros(n_centroids, size_block, device=M.device) 33 | for k in range(n_centroids): 34 | centroids[k] = M_unrolled[:, assignments == k][:, 0] 35 | 36 | return centroids 37 | 38 | 39 | def weight_from_centroids(centroids, assignments, n_blocks, k, conv): 40 | """ 41 | Constructs the 2D matrix from its centroids. 42 | 43 | Args: 44 | - centroids: size (block_size x n_centroids) 45 | - assignments: size (n_vectors) 46 | _ n_blocks: numnber of blocks per column 47 | - k: kernel size (set to 1 if not is_conv) 48 | - is_conv: convolutional or linear layer 49 | 50 | Remarks: 51 | - This function consists in two steps: 52 | (1) get the 2D unrolled weight matrix 53 | (2) reshape it in the case of fully-connected of convolutional layer 54 | """ 55 | 56 | M_hat_unrolled = torch.cat(centroids[assignments].t().chunk(n_blocks, dim=1), dim=0) 57 | M_hat_reshaped = reshape_back_weight(M_hat_unrolled, k=k, conv=conv) 58 | 59 | return M_hat_reshaped 60 | -------------------------------------------------------------------------------- /src/utils/watcher.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import torch 9 | import torch.nn as nn 10 | 11 | from operator import attrgetter 12 | 13 | from .training import evaluate 14 | 15 | 16 | class ActivationWatcher: 17 | """ 18 | Monitors and stores *input* activations in all the layers of the network. 19 | 20 | Args: 21 | - model: the model to monitor, should be `nn.module` 22 | - n_activations: number of activations to store 23 | - layer: if None, monitors all layers except BN, otherwise single 24 | layers to monitor 25 | 26 | Remarks: 27 | - Do NOT use layers with inplace operations, otherwise 28 | the activations will not be monitored correctly 29 | - Memory to store activations is pre-allocated for efficiency 30 | """ 31 | 32 | def __init__(self, model, layer=''): 33 | self.model = model 34 | # layers to monitor 35 | all_layers = self._get_layers() 36 | if len(layer) == 0: 37 | self.layers = all_layers 38 | else: 39 | assert layer in all_layers 40 | self.layers = [layer] 41 | # initialization 42 | self.modules_to_layers = {attrgetter(layer)(self.model): layer for layer in self.layers} 43 | self._register_hooks() 44 | self._watch = False 45 | 46 | def _get_layers(self): 47 | # get proper layer names 48 | keys = self.model.state_dict().keys() 49 | layers = [k[:k.rfind(".")] for k in keys if 'bias' not in k] 50 | # remove BN layers 51 | layers = [layer for layer in layers if not isinstance(attrgetter(layer)(self.model), nn.BatchNorm2d)] 52 | 53 | return layers 54 | 55 | def _get_bn_layers(self): 56 | # get proper layer names 57 | keys = self.model.state_dict().keys() 58 | layers = [k[:k.rfind(".")] for k in keys if 'weight' in k] 59 | # only keep BN layers 60 | layers = [layer for layer in layers if isinstance(attrgetter(layer)(self.model), nn.BatchNorm2d)] 61 | 62 | return layers 63 | 64 | def _get_bias_layers(self): 65 | # get proper layer names 66 | keys = self.model.state_dict().keys() 67 | layers = [k[:k.rfind(".")] for k in keys if 'bias' in k] 68 | # only keep BN layers 69 | layers = [layer for layer in layers if not isinstance(attrgetter(layer)(self.model), nn.BatchNorm2d)] 70 | 71 | return layers 72 | 73 | def _register_hooks(self): 74 | # define hook to save output after each layer 75 | def fwd_hook(module, input, output): 76 | layer = self.modules_to_layers[module] 77 | if self._watch: 78 | # retrieve activations 79 | activations = input[0].data.cpu() 80 | # store activations 81 | self.activations[layer].append(activations) 82 | # register hooks 83 | self.handles = [] 84 | for layer in self.layers: 85 | handle = attrgetter(layer)(self.model).register_forward_hook(fwd_hook) 86 | self.handles.append(handle) 87 | 88 | def watch(self, loader, criterion, n_iter): 89 | # watch 90 | self._watch = True 91 | # initialize activations storage 92 | self.activations = {layer: [] for layer in self.layers} 93 | # gather activations 94 | evaluate(loader, self.model, criterion, n_iter=n_iter) 95 | # unwatch 96 | self._watch = False 97 | # treat activations 98 | self.activations = {k: torch.cat(v, dim=0) for (k, v) in self.activations.items()} 99 | # remove hooks from model 100 | for handle in self.handles: 101 | handle.remove() 102 | # return activations 103 | return self.activations 104 | 105 | def save(self, path): 106 | torch.save(self.activations, path) 107 | --------------------------------------------------------------------------------