├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── examples ├── __init__.py ├── channel_pruning │ ├── __init__.py │ ├── prune_train.py │ └── vgg_pruner.py └── deep_compression │ ├── __init__.py │ ├── decode.py │ ├── encode.py │ ├── prune_train.py │ ├── quantize_train.py │ ├── rules │ ├── inception_v3 │ │ ├── coding.rule │ │ ├── prune_autogenerate.rule │ │ └── quantize.rule │ └── resnet50 │ │ ├── coding.rule │ │ ├── prune_manual.rule │ │ └── quantize.rule │ └── sensitivity_scan.py ├── slender ├── __init__.py ├── coding │ ├── __init__.py │ ├── codec.py │ └── encode.py ├── prune │ ├── __init__.py │ ├── channel.py │ └── vanilla.py ├── quantize │ ├── __init__.py │ ├── fixed_point.py │ ├── kmeans.py │ ├── linear.py │ └── quantizer.py ├── replicate.py └── utils.py └── test ├── __init__.py ├── test_coding.py ├── test_quantize.py └── test_vanilla_prune.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # pycharm 107 | .idea/ 108 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | NN Compression Toolkit 633 | Copyright (C) 2018 Xavier Lin 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nn-compression 2 | A Pytorch implementation of Neural Network Compression (pruning, quantization, encoding/decoding) 3 | 4 | Most work of this repo is better done in [distiller](https://github.com/NervanaSystems/distiller). However, they have not implement channel pruning and coding yet. With coding in this repo, you can save the model with actually much smaller memory size. 5 | 6 | ## Pruning 7 | 8 | Neural Network Pruning reduces the number of nonzero parameters and thus computation amount (FLOPs). 9 | 10 | ### Vanilla Pruning 11 | 12 | Deep Compression uses vanilla pruning method. It prunes the parameters with the least importance. 13 | 14 | * **_Elementwise_** Pruning: prune those with the smallest magnitude 15 | 16 | * **_Kernelwise_** Pruning: prune 2D kernels with the smallest L1(default)/L2 norm 17 | 18 | * **_Filterwise_** Pruning: prune 3D filters with the smallest L1(default)/L2 norm 19 | 20 | ```python 21 | # vanilla pruner usage 22 | 23 | from modules.prune import VanillaPruner 24 | 25 | rule = [ 26 | ('0.weight', 'element', [0.3, 0.5], 'abs'), 27 | ('1.weight', 'kernel', [0.4, 0.6], 'default') 28 | ('2.weight', 'filter', [0.5, 0.7], 'l2norm') 29 | ] 30 | 31 | pruner = VanillaPruner(rule=rule) 32 | """ 33 | :param rule: str, path to the rule file, each line formats 34 | 'param_name granularity sparsity_stage_0, sparstiy_stage_1, ...' 35 | list of tuple, [(param_name(str), granularity(str), 36 | sparsity(float) or [sparsity_stage_0(float), sparstiy_stage_1,], 37 | fn_importance(optional, str or function))] 38 | 'granularity': str, choose from ['element', 'kernel', 'filter'] 39 | 'fn_importance': str, choose from ['abs', 'l1norm', 'l2norm', 'default'] 40 | """ 41 | 42 | stage = 0 43 | 44 | for epoch in range(0, 90): 45 | if epoch == 0: 46 | pruner.prune(model=model, stage=stage, update_masks=True) 47 | best_prec1 = validate(val_loader, model, criterion, epoch) 48 | 49 | # in train function 50 | for i, (input, target) in enumerate(train_loader): 51 | output = model(input) 52 | loss = criterion(output, target) 53 | optimizer.zero_grad() 54 | loss.backward() 55 | optimizer.step() 56 | 57 | pruner.prune(model=model, stage=stage, update_masks=False) 58 | ``` 59 | 60 | ### Channel Pruning 61 | 62 | Channel Pruning is another set of neural network pruning methods. It reduces the number of output channels 63 | in every convolution or fully-connected layers. Therefore, it can directly speed up the inference. 64 | 65 | Channel Pruning takes 2 steps: 66 | 67 | 1. Channel Selection: select channels with least impact to prune 68 | 2. Parameter Reconstruction: reconstruct the parameter values to optimize the output feature of the next 69 | layer to the pruned one 70 | 71 | These two steps are conducted layer by layer. 72 | 73 | ```python 74 | # channel pruning usage 75 | 76 | def prune_channel(sparsity, module, next_module, fn_next_input_feature, input_feature, 77 | method='greedy', cpu=True): 78 | """ 79 | channel pruning core function 80 | :param sparsity: float, pruning sparsity 81 | :param module: torch.nn.module, module of the layer being pruned 82 | :param next_module: torch.nn.module, module of the next layer to the one being pruned 83 | :param fn_next_input_feature: function, function to calculate the input feature map for next_module 84 | :param input_feature: torch.(cuda.)Tensor, input feature map of the layer being pruned 85 | :param method: str 86 | 'greedy': select one contributed to the smallest next feature after another 87 | 'lasso': pruned channels by lasso regression 88 | 'random': randomly select 89 | :param cpu: bool, whether done in cpu for larger reconstruction batch size 90 | :return: 91 | void 92 | """ 93 | ``` 94 | 95 | Detailed example shows in [here](examples/channel_pruning). 96 | 97 | ## Quantization 98 | 99 | Neural Network Quantization is to represent the parameters with fewer bits. 100 | 101 | ### Vanilla Quantization 102 | 103 | There are several ways to quantize neural network parameters: 104 | 105 | * **_Fixed-point_** Quantization: the most common way, uses (*i*+*f*)-bits to represent the number, 106 | where *i*-bits for integer and *f*-bits for fraction. 107 | 108 | * **_Uniform/Linear_** Quantization: quantization centroids lies uniformly in the range of parameter values, 109 | i.e., the quantization step equals $(max - min) / k$, where *k* is the quantization levels 110 | 111 | * **_K-Means_** Quantization: quantization centroids calculated by K-Means clustering 112 | 113 | ```python 114 | # vanilla quantizer usage 115 | 116 | from modules.quantize import Quantizer 117 | 118 | rule = [ 119 | ('0.weight', 'k-means', 4, 'k-means++'), 120 | ('1.weight', 'fixed_point', 6, 1), 121 | ] 122 | 123 | quantizer = Quantizer(rule=rule, fix_zeros=True) 124 | """ 125 | :param rule: str, path to the rule file, each line formats 126 | 'param_name method bit_length initial_guess_or_bit_length_of_integer' 127 | list of tuple, 128 | [(param_name(str), method(str), bit_length(int), 129 | initial_guess(str)_or_bit_length_of_integer(int))] 130 | :param fix_zeros: whether to fix zeros when quantizing 131 | """ 132 | 133 | for epoch in range(0, 90): 134 | # in the train loop 135 | 136 | # in train function 137 | for i, (input, target) in enumerate(train_loader): 138 | output = model(input) 139 | loss = criterion(output, target) 140 | optimizer.zero_grad() 141 | loss.backward() 142 | optimizer.step() 143 | 144 | quantizer.quantize(model=model, update_labels=True, re_quantize=False) 145 | """ 146 | :param update_labels: bool, whether to re-allocate the param elements 147 | to the latest centroids when using k-means 148 | :param re_quantize: bool, whether to re-quantize the param when using k-means 149 | """ 150 | ``` 151 | 152 | ## Coding 153 | 154 | Coding is the last step to compress the neural network in Deep Compression: 155 | 156 | * **_Fixed-point_** Coding: it actually is not a coding method, 157 | just in case if we want to actually save the model in fixed-point style. 158 | 159 | * **_Vanilla (Linear)_** Coding: it uses $log_2 (N)$-bits to represent *N* float number in the codebook, 160 | i.e., there are only *N* possible values in a parameter matrix 161 | 162 | * **_Huffman_** Coding: it uses huffman coding to represent *N* float number in the codebook 163 | 164 | ```python 165 | # coding codec usage (encode) 166 | 167 | import torch 168 | from modules.coding import Codec 169 | 170 | rule = [ 171 | ('0.weight', 'huffman', 0, 0, 4), 172 | ('1.weight', 'fixed_point', 6, 1, 4) 173 | ] 174 | 175 | codec = Codec(rule=rule) 176 | """ 177 | :param rule: str, path to the rule file, each line formats 178 | 'param_name coding_method bit_length_fixed_point bit_length_fixed_point_of_integer_part 179 | bit_length_of_zero_run_length' 180 | list of tuple, 181 | [(param_name(str), coding_method(str), bit_length_fixed_point(int), 182 | bit_length_fixed_point_of_integer_part(int), bit_length_of_zero_run_length(int))] 183 | """ 184 | 185 | encoded_model = codec.encode(model=model) 186 | 187 | torch.save({'state_dict': encoded_model.state_dict()}, 'encode.pth.tar', pickle_protocol=4) 188 | ``` 189 | 190 | ```python 191 | # coding codec usage (decode) 192 | 193 | import torch 194 | from modules.coding import Codec 195 | 196 | checkpoint = torch.load('encode.pth.tar') 197 | 198 | model = Codec.decode(model=model, state_dict=checkpoint['state_dict']) # initial model is created before 199 | 200 | torch.save({'state_dict': model.state_dict()}, 'decode.pth.tar') 201 | ``` 202 | 203 | ## Rerference 204 | 205 | ```text 206 | @article{han2015deep, 207 | title={Deep compression: Compressing deep neural networks with pruning, trained quantization and huffman coding}, 208 | author={Han, Song and Mao, Huizi and Dally, William J}, 209 | journal={arXiv preprint arXiv:1510.00149}, 210 | year={2015} 211 | } 212 | ``` 213 | 214 | ```text 215 | @inproceedings{han2015learning, 216 | title={Learning both weights and connections for efficient neural network}, 217 | author={Han, Song and Pool, Jeff and Tran, John and Dally, William}, 218 | booktitle={Advances in neural information processing systems}, 219 | pages={1135--1143}, 220 | year={2015} 221 | } 222 | ``` 223 | 224 | ```text 225 | @article{luo2017thinet, 226 | title={Thinet: A filter level pruning method for deep neural network compression}, 227 | author={Luo, Jian-Hao and Wu, Jianxin and Lin, Weiyao}, 228 | journal={arXiv preprint arXiv:1707.06342}, 229 | year={2017} 230 | } 231 | ``` 232 | 233 | ```text 234 | @inproceedings{he2017channel, 235 | title={Channel pruning for accelerating very deep neural networks}, 236 | author={He, Yihui and Zhang, Xiangyu and Sun, Jian}, 237 | booktitle={International Conference on Computer Vision (ICCV)}, 238 | volume={2}, 239 | number={6}, 240 | year={2017} 241 | } 242 | ``` 243 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synxlin/nn-compression/34918a4ed2bbe44a483a6e81a740ae5fe3ffc065/__init__.py -------------------------------------------------------------------------------- /examples/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synxlin/nn-compression/34918a4ed2bbe44a483a6e81a740ae5fe3ffc065/examples/__init__.py -------------------------------------------------------------------------------- /examples/channel_pruning/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synxlin/nn-compression/34918a4ed2bbe44a483a6e81a740ae5fe3ffc065/examples/channel_pruning/__init__.py -------------------------------------------------------------------------------- /examples/channel_pruning/prune_train.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import datetime 3 | import os 4 | import shutil 5 | import time 6 | 7 | import torch 8 | import torch.nn as nn 9 | import torch.nn.parallel 10 | import torch.backends.cudnn as cudnn 11 | import torch.optim 12 | import torch.utils.data 13 | import torchvision.transforms as transforms 14 | import torchvision.datasets as datasets 15 | import torchvision.models as models 16 | 17 | from slender.utils import AverageMeter, Logger 18 | from .vgg_pruner import VGGPruner 19 | 20 | model_names = sorted(name for name in models.__dict__ 21 | if name.islower() and not name.startswith("__") 22 | and name.startswith("vgg") 23 | and callable(models.__dict__[name])) 24 | 25 | parser = argparse.ArgumentParser(description='PyTorch ThiNet/Channel Pruning') 26 | parser.add_argument('data', metavar='DIR', 27 | help='path to dataset') 28 | parser.add_argument('--arch', '-a', metavar='ARCH', default='vgg16', 29 | choices=model_names, 30 | help='model architecture: ' + 31 | ' | '.join(model_names) + 32 | ' (default: vgg16)') 33 | parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', 34 | help='number of data loading workers (default: 4)') 35 | parser.add_argument('--epochs', default=90, type=int, metavar='N', 36 | help='number of total epochs to run') 37 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 38 | help='manual epoch number (useful on restarts)') 39 | parser.add_argument('-b', '--batch-size', default=256, type=int, 40 | metavar='N', help='mini-batch size (default: 256)') 41 | parser.add_argument('--lr', '--learning-rate', default=0.1, type=float, 42 | metavar='LR', help='initial learning rate') 43 | parser.add_argument('--lr-decay-step', default=4, type=int, metavar='N', 44 | help='every N epochs lr decays by 0.1 (default:4)') 45 | parser.add_argument('--momentum', default=0.9, type=float, metavar='M', 46 | help='momentum') 47 | parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float, 48 | metavar='W', help='weight decay (default: 1e-4)') 49 | parser.add_argument('--print-freq', '-p', default=10, type=int, 50 | metavar='N', help='print frequency (default: 10)') 51 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 52 | help='path to latest checkpoint (default: none)') 53 | 54 | parser.add_argument('--pretrained', default='', type=str, metavar='PATH', 55 | help='use pre-trained model: ' 56 | 'pytorch: use pytorch official | ' 57 | 'path to self-trained moel') 58 | parser.add_argument('--pretrained-parallel', dest='pretrained_parallel', 59 | action='store_true', 60 | help='self-trained model starts with torch.nn.DataParallel') 61 | 62 | parser.add_argument('--pruning-rule', default='', 63 | help='path to quantization rule file') 64 | parser.add_argument('--method', default='greedy', type=str, metavar='METHOD', 65 | help='channel selection method in ThiNet Pruning:' + 66 | ' | '.join(['greedy', 'lasso', 'random']) + 67 | ' (default: greedy)') 68 | parser.add_argument('--rb', '--reconstruction-batch-size', default=128, 69 | type=int, metavar='N', dest='rcn_batch_size', 70 | help='mini-batch size for ThiNet Pruning ' 71 | 'Reconstruction (default: 128)') 72 | parser.add_argument('--rcn-gpu', dest='rcn_gpu', action='store_true', 73 | help='use gpu to perform ThiNet Weight Reconstruction') 74 | 75 | best_prec1 = 0 76 | 77 | 78 | def main(): 79 | global args, best_prec1, train_log, test_log 80 | args = parser.parse_args() 81 | 82 | dir_name = args.arch + '_' + datetime.datetime.now().strftime('%m%d_%H%M') 83 | log_dir = os.path.join('logs', os.path.join('prune', dir_name)) 84 | checkpoint_dir = os.path.join('checkpoints', os.path.join('prune', dir_name)) 85 | os.makedirs(log_dir) 86 | os.makedirs(checkpoint_dir) 87 | train_log = Logger(os.path.join(log_dir, 'train.log')) 88 | test_log = Logger(os.path.join(log_dir, 'test.log')) 89 | config_log = Logger(os.path.join(log_dir, 'config.log')) 90 | 91 | for k, v in vars(args).items(): 92 | config_log.write(content="{k} : {v}".format(k=k, v=v), wrap=True, flush=True) 93 | config_log.close() 94 | 95 | # create model 96 | print("=" * 89) 97 | print("=> creating model '{}'".format(args.arch)) 98 | 99 | if args.resume: 100 | if os.path.isfile(args.resume): 101 | print("=> loading checkpoint '{}'".format(args.resume)) 102 | checkpoint = torch.load(args.resume) 103 | args.start_epoch = checkpoint['epoch'] 104 | best_prec1 = checkpoint['best_prec1'] 105 | 106 | vgg_cfg, batch_norm = checkpoint['cfg'] 107 | from torchvision.models.vgg import VGG, make_layers 108 | model = VGG(make_layers(cfg=vgg_cfg, batch_norm=batch_norm), init_weights=False) 109 | model.features = torch.nn.DataParallel(model.features) 110 | model.cuda() 111 | model.load_state_dict(checkpoint['state_dict']) 112 | 113 | optimizer = torch.optim.SGD(model.parameters(), args.lr, 114 | momentum=args.momentum, 115 | weight_decay=args.weight_decay) 116 | optimizer.load_state_dict(checkpoint['optimizer']) 117 | print("=> loaded checkpoint '{}' (epoch {})" 118 | .format(args.resume, checkpoint['epoch'])) 119 | else: 120 | print("=> no checkpoint found at '{}'".format(args.resume)) 121 | return 122 | 123 | elif args.pretrained: 124 | if args.pretrained == 'pytorch': 125 | print("=> using pre-trained model from model zoo") 126 | model = models.__dict__[args.arch](pretrained=True) 127 | args.pretrained_parallel = False 128 | else: 129 | model = models.__dict__[args.arch]() 130 | if args.pretrained_parallel: 131 | model.features = torch.nn.DataParallel(model.features) 132 | model.cuda() 133 | if os.path.isfile(args.pretrained): 134 | print("=> using pre-trained model '{}'".format(args.pretrained)) 135 | checkpoint = torch.load(args.pretrained) 136 | model.load_state_dict(checkpoint['state_dict']) 137 | if not args.pretrained_parallel: 138 | model.features = torch.nn.DataParallel(model.features) 139 | model.cuda() 140 | else: 141 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 142 | return 143 | else: 144 | model = models.__dict__[args.arch]() 145 | model.features = torch.nn.DataParallel(model.features) 146 | model.cuda() 147 | 148 | # define loss function (criterion) 149 | criterion = nn.CrossEntropyLoss().cuda() 150 | 151 | cudnn.benchmark = True 152 | 153 | # Data loading code 154 | traindir = os.path.join(args.data, 'train') 155 | valdir = os.path.join(args.data, 'val') 156 | normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 157 | std=[0.229, 0.224, 0.225]) 158 | 159 | train_dataset = datasets.ImageFolder( 160 | traindir, 161 | transforms.Compose([ 162 | transforms.RandomResizedCrop(224), 163 | transforms.RandomHorizontalFlip(), 164 | transforms.ToTensor(), 165 | normalize, 166 | ])) 167 | 168 | train_loader = torch.utils.data.DataLoader( 169 | train_dataset, batch_size=args.batch_size, shuffle=True, 170 | num_workers=args.workers, pin_memory=True) 171 | 172 | val_loader = torch.utils.data.DataLoader( 173 | datasets.ImageFolder(valdir, transforms.Compose([ 174 | transforms.Resize(256), 175 | transforms.CenterCrop(224), 176 | transforms.ToTensor(), 177 | normalize, 178 | ])), 179 | batch_size=args.batch_size, shuffle=False, 180 | num_workers=args.workers, pin_memory=True) 181 | 182 | if not args.resume: 183 | rcn_loader = torch.utils.data.DataLoader( 184 | datasets.ImageFolder(valdir, transforms.Compose([ 185 | transforms.Resize(256), 186 | transforms.CenterCrop(224), 187 | transforms.ToTensor(), 188 | normalize, 189 | ])), 190 | batch_size=args.rcn_batch_size, shuffle=True, 191 | num_workers=args.workers, pin_memory=True) 192 | 193 | prune(train_loader=train_loader, val_loader=val_loader, rcn_loader=rcn_loader, 194 | model=model, criterion=criterion) 195 | 196 | optimizer = torch.optim.SGD(model.parameters(), args.lr, 197 | momentum=args.momentum, 198 | weight_decay=args.weight_decay) 199 | 200 | for epoch in range(args.start_epoch, args.epochs): 201 | adjust_learning_rate(lr_decay_step=args.lr_decay_step, 202 | optimizer=optimizer, epoch=epoch) 203 | 204 | # train for one epoch 205 | train(train_loader=train_loader, model=model, criterion=criterion, 206 | optimizer=optimizer, epoch=epoch, log=True) 207 | 208 | # evaluate on validation set 209 | prec1 = validate(val_loader=val_loader, model=model, 210 | criterion=criterion, epoch=epoch, log=True) 211 | 212 | # remember best prec@1 and save checkpoint 213 | is_best = prec1 > best_prec1 214 | best_prec1 = max(prec1, best_prec1) 215 | save_checkpoint({ 216 | 'epoch': epoch + 1, 217 | 'arch': args.arch, 218 | 'state_dict': model.state_dict(), 219 | 'cfg': get_vgg_cfg(model), 220 | 'best_prec1': best_prec1, 221 | 'optimizer': optimizer.state_dict(), 222 | }, is_best=is_best, checkpoint_dir=checkpoint_dir) 223 | 224 | 225 | def train(train_loader, model, criterion, optimizer, epoch, log=False): 226 | batch_time = AverageMeter() 227 | data_time = AverageMeter() 228 | losses = AverageMeter() 229 | top1 = AverageMeter() 230 | top5 = AverageMeter() 231 | 232 | # switch to train mode 233 | model.train() 234 | 235 | end = time.time() 236 | for i, (input, target) in enumerate(train_loader): 237 | # measure data loading time 238 | data_time.update(time.time() - end) 239 | 240 | target = target.cuda(non_blocking=True) 241 | 242 | # compute output 243 | output = model(input) 244 | loss = criterion(output, target) 245 | 246 | # measure accuracy and record loss 247 | prec1, prec5 = accuracy(output, target, topk=(1, 5)) 248 | losses.update(loss.item(), input.size(0)) 249 | top1.update(prec1[0], input.size(0)) 250 | top5.update(prec5[0], input.size(0)) 251 | 252 | # compute gradient and do SGD step 253 | optimizer.zero_grad() 254 | loss.backward() 255 | optimizer.step() 256 | 257 | # measure elapsed time 258 | batch_time.update(time.time() - end) 259 | end = time.time() 260 | 261 | if i % args.print_freq == 0: 262 | print('Epoch: [{0}][{1}/{2}]\t' 263 | 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 264 | 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 265 | 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 266 | 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 267 | 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format( 268 | epoch, i, len(train_loader), batch_time=batch_time, 269 | data_time=data_time, loss=losses, top1=top1, top5=top5)) 270 | print("=" * 89) 271 | print(' * Train Epoch: {epoch:3d} | Prec@1: {top1.avg:.3f} | Prec@5: {top5.avg:.3f}' 272 | .format(epoch=epoch, top1=top1, top5=top5)) 273 | print("=" * 89) 274 | if log: 275 | train_log.write(content="{epoch}\t" 276 | "{top1.avg:.4e}\t" 277 | "{top5.avg:.4e}\t" 278 | "{loss.avg:.4e}" 279 | .format(epoch=epoch, top1=top1, top5=top5, loss=losses), wrap=True, flush=True) 280 | 281 | 282 | def validate(val_loader, model, criterion, epoch, log=False): 283 | batch_time = AverageMeter() 284 | losses = AverageMeter() 285 | top1 = AverageMeter() 286 | top5 = AverageMeter() 287 | 288 | # switch to evaluate mode 289 | model.eval() 290 | 291 | with torch.no_grad(): 292 | end = time.time() 293 | for i, (input, target) in enumerate(val_loader): 294 | target = target.cuda(non_blocking=True) 295 | 296 | # compute output 297 | output = model(input) 298 | loss = criterion(output, target) 299 | 300 | # measure accuracy and record loss 301 | prec1, prec5 = accuracy(output, target, topk=(1, 5)) 302 | losses.update(loss.item(), input.size(0)) 303 | top1.update(prec1[0], input.size(0)) 304 | top5.update(prec5[0], input.size(0)) 305 | 306 | # measure elapsed time 307 | batch_time.update(time.time() - end) 308 | end = time.time() 309 | 310 | if i % args.print_freq == 0: 311 | print('Test: [{0}/{1}]\t' 312 | 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 313 | 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 314 | 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 315 | 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format( 316 | i, len(val_loader), batch_time=batch_time, loss=losses, 317 | top1=top1, top5=top5)) 318 | 319 | print("=" * 89) 320 | print(' * Test Epoch: {epoch:3d} | Prec@1: {top1.avg:.3f} | Prec@5: {top5.avg:.3f}' 321 | .format(epoch=epoch, top1=top1, top5=top5)) 322 | print("=" * 89) 323 | if log: 324 | test_log.write(content="{epoch}\t" 325 | "{top1.avg:.4e}\t" 326 | "{top5.avg:.4e}\t" 327 | .format(epoch=epoch, top1=top1, top5=top5), wrap=True, flush=True) 328 | 329 | return top1.avg 330 | 331 | 332 | def prune(train_loader, val_loader, rcn_loader, model, criterion): 333 | print("=" * 89) 334 | origin_prec1 = validate(val_loader=val_loader, model=model, criterion=criterion, epoch=0) 335 | 336 | input_iter = iter(rcn_loader) 337 | 338 | print("=" * 89) 339 | print("start ThiNet Pruning") 340 | pruner = VGGPruner(rule=args.pruning_rule) 341 | prune_inputs = pruner.get_prune_inputs(model=model) 342 | for (module_name, module, next_module, 343 | fn_input_feature, fn_next_input_feature) in prune_inputs: 344 | input, _ = input_iter.__next__() 345 | pruner.prune_module(module_name=module_name, module=module, 346 | next_module=next_module, fn_input_feature=fn_input_feature, 347 | fn_next_input_feature=fn_next_input_feature, 348 | input=input, method=args.method, cpu=(not args.rcn_gpu), 349 | verbose=True) 350 | prec1 = validate(val_loader=val_loader, model=model, criterion=criterion, epoch=0) 351 | if prec1 > origin_prec1: 352 | continue 353 | print("=" * 89) 354 | print("Fine-tuning") 355 | print("=" * 89) 356 | 357 | optimizer = torch.optim.SGD(model.parameters(), args.lr, 358 | momentum=args.momentum, 359 | weight_decay=args.weight_decay) 360 | train(train_loader=train_loader, model=model, 361 | criterion=criterion, optimizer=optimizer, epoch=0) 362 | adjust_learning_rate(lr_decay_step=1, optimizer=optimizer, epoch=1) 363 | train(train_loader=train_loader, model=model, 364 | criterion=criterion, optimizer=optimizer, epoch=1) 365 | del optimizer 366 | validate(val_loader=val_loader, model=model, 367 | criterion=criterion, epoch=0) 368 | print("=" * 89) 369 | print("stop ThiNet Pruning") 370 | 371 | 372 | def get_vgg_cfg(model): 373 | """ 374 | return config list to generate VGG instance 375 | :param model: class VGG (torch.nn.Module), model to prune 376 | :return: 377 | list, config list to generate VGG instance 378 | """ 379 | assert isinstance(model, models.VGG) 380 | features = model.features 381 | if isinstance(features, torch.nn.DataParallel): 382 | features = features.module 383 | 384 | cfg = [] 385 | batch_norm = False 386 | for m in features: 387 | if isinstance(m, torch.nn.modules.conv._ConvNd): 388 | cfg.append(m.out_channels) 389 | elif isinstance(m, torch.nn.modules.pooling._MaxPoolNd): 390 | cfg.append('M') 391 | elif isinstance(m, torch.nn.modules.batchnorm._BatchNorm): 392 | batch_norm = True 393 | 394 | return cfg, batch_norm 395 | 396 | 397 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar', checkpoint_dir='.'): 398 | filename = os.path.join(checkpoint_dir, filename) 399 | torch.save(state, filename, pickle_protocol=4) 400 | if is_best: 401 | shutil.copyfile(filename, os.path.join(checkpoint_dir, 'model_best.pth.tar')) 402 | 403 | 404 | def adjust_learning_rate(lr_decay_step, optimizer, epoch): 405 | """Sets the learning rate to the initial LR decayed by 10 every lr_decay_step epochs""" 406 | lr = args.lr * (0.1 ** (epoch // lr_decay_step)) 407 | for param_group in optimizer.param_groups: 408 | param_group['lr'] = lr 409 | 410 | 411 | def accuracy(output, target, topk=(1,)): 412 | """Computes the precision@k for the specified values of k""" 413 | with torch.no_grad(): 414 | maxk = max(topk) 415 | batch_size = target.size(0) 416 | 417 | _, pred = output.topk(maxk, 1, True, True) 418 | pred = pred.t() 419 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 420 | 421 | res = [] 422 | for k in topk: 423 | correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) 424 | res.append(correct_k.mul_(100.0 / batch_size)) 425 | return res 426 | 427 | 428 | if __name__ == '__main__': 429 | main() 430 | -------------------------------------------------------------------------------- /examples/channel_pruning/vgg_pruner.py: -------------------------------------------------------------------------------- 1 | import re 2 | import torch 3 | from torchvision.models import VGG 4 | 5 | from slender.prune import prune_channel 6 | 7 | 8 | class VGGPruner(object): 9 | 10 | def __init__(self, rule): 11 | """ 12 | Channel Pruner for VGG 13 | :param rule: str, path to the rule file, each line formats 'module_name sparsity' 14 | list of tuple, [(module_name(str), sparsity(float))] 15 | """ 16 | if isinstance(rule, str): 17 | content = map(lambda x: x.split(), open(rule).readlines()) 18 | content = filter(lambda x: len(x) == 2, content) 19 | rule = list(map(lambda x: (x[0], float(x[1])), content)) 20 | assert isinstance(rule, list) or isinstance(rule, tuple) 21 | 22 | self.rule = rule 23 | 24 | def get_param_sparsity(self, module_name): 25 | """ 26 | get sparsity based on the name of module 27 | :param module_name: str, name of the module to prune 28 | :return: 29 | float, sparsity 30 | """ 31 | rule_id = -1 32 | for idx, x in enumerate(self.rule): 33 | m = re.match(x[0], module_name) 34 | if m is not None and len(module_name) == m.span()[1]: 35 | rule_id = idx 36 | break 37 | if rule_id > -1: 38 | sparsity = self.rule[rule_id][1] 39 | return sparsity 40 | else: 41 | return 1.0 42 | 43 | @staticmethod 44 | def get_prune_inputs(model): 45 | """ 46 | get input args for prune() method of VGGPruner Class 47 | :param model: class VGG (torch.nn.Module), model to prune 48 | :return: 49 | list of tuple, [(module_name, module, next_module, fn_input_feature, fn_next_input_feature), ...] 50 | """ 51 | assert isinstance(model, VGG) 52 | features = model.features 53 | if isinstance(features, torch.nn.DataParallel): 54 | features = features.module 55 | classifier = model.classifier 56 | 57 | module_name_dict = dict() 58 | for n, m in model.named_modules(): 59 | module_name_dict[m] = n 60 | 61 | conv_indices = [] 62 | conv_modules = [] 63 | conv_names = [] 64 | for i, m in enumerate(features): 65 | if isinstance(m, torch.nn.modules.conv._ConvNd): 66 | conv_indices.append(i) 67 | conv_modules.append(m) 68 | conv_names.append(module_name_dict[m]) 69 | 70 | fc_indices = [] 71 | fc_modules = [] 72 | fc_names = [] 73 | for i, m in enumerate(classifier): 74 | if isinstance(m, torch.nn.Linear): 75 | fc_indices.append(i) 76 | fc_modules.append(m) 77 | fc_names.append(module_name_dict[m]) 78 | 79 | def get_fn_conv_input_feature(idx): 80 | def fn(x): 81 | for seq_i in range(conv_indices[idx]): 82 | x = features[seq_i](x) 83 | return x 84 | return fn 85 | 86 | def get_fn_next_input_feature(idx, module_indices, module_seq): 87 | def fn(x): 88 | for seq_i in range(module_indices[idx]+1, module_indices[idx+1]): 89 | x = module_seq[seq_i](x) 90 | return x 91 | return fn 92 | 93 | prune_modules = [] 94 | prune_module_names = [] 95 | prune_module_fn = [] 96 | prune_module_fn_next = [] 97 | 98 | for i in range(len(conv_indices) - 1): 99 | prune_modules.append(conv_modules[i]) 100 | prune_module_names.append(conv_names[i]) 101 | prune_module_fn.append(get_fn_conv_input_feature(i)) 102 | prune_module_fn_next.append(get_fn_next_input_feature(i, conv_indices, features)) 103 | 104 | prune_modules.append(conv_modules[-1]) 105 | prune_module_names.append(conv_names[-1]) 106 | prune_module_fn.append(get_fn_conv_input_feature(-1)) 107 | 108 | def fn_next_input_feature(x): 109 | for seq_i in range(conv_indices[-1]+1, len(features)): 110 | x = features[seq_i](x) 111 | x = x.view(x.size(0), -1) 112 | return x 113 | prune_module_fn_next.append(fn_next_input_feature) 114 | 115 | def get_fn_fc_input_feature(idx): 116 | def fn(x): 117 | x = features(x) 118 | x = x.view(x.size(0), -1) 119 | for seq_i in range(fc_indices[idx]): 120 | x = classifier[seq_i](x) 121 | return x 122 | return fn 123 | 124 | for i in range(len(fc_indices) - 1): 125 | prune_modules.append(fc_modules[i]) 126 | prune_module_names.append(fc_names[i]) 127 | prune_module_fn.append(get_fn_fc_input_feature(i)) 128 | prune_module_fn_next.append(get_fn_next_input_feature(i, fc_indices, classifier)) 129 | 130 | prune_modules.append(fc_modules[-1]) 131 | 132 | prune_inputs = [] 133 | for i in range(len(prune_module_names)): 134 | prune_inputs.append((prune_module_names[i], prune_modules[i], prune_modules[i+1], 135 | prune_module_fn[i], prune_module_fn_next[i])) 136 | 137 | return prune_inputs 138 | 139 | def prune_module(self, module_name, module, next_module, fn_input_feature, fn_next_input_feature, 140 | input, method='greedy', cpu=True, verbose=False): 141 | """ 142 | 143 | :param module_name: str, the name of the module to prune 144 | :param module: torch.nn.Module, usually _ConvNd or Linear 145 | :param next_module: torch.nn.Module, the next _ConvNd or Linear module to "module" 146 | :param fn_input_feature: function, calculate input feature of "module" from the image 147 | :param fn_next_input_feature: function, calculate input feature of "next_module" 148 | from the output feature of "module" 149 | :param input: torch.tensor, input image of VGG, (batch_size, 3, 224, 224) 150 | :param method: str 151 | 'greedy': select one contributed to the smallest next feature after another 152 | 'lasso': select pruned channels by lasso regression 153 | 'random': randomly select 154 | :param cpu: bool, whether done in cpu for larger reconstruction batch size 155 | :return: 156 | void 157 | """ 158 | sparsity = self.get_param_sparsity(module_name=module_name) 159 | if verbose: 160 | print("=" * 89) 161 | print("{param_name:^30} : {spars:.3f}".format(param_name=module_name, spars=sparsity)) 162 | input_feature = fn_input_feature(input) 163 | prune_channel(sparsity=sparsity, module=module, next_module=next_module, 164 | fn_next_input_feature=fn_next_input_feature, 165 | input_feature=input_feature, method=method, cpu=cpu) 166 | -------------------------------------------------------------------------------- /examples/deep_compression/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synxlin/nn-compression/34918a4ed2bbe44a483a6e81a740ae5fe3ffc065/examples/deep_compression/__init__.py -------------------------------------------------------------------------------- /examples/deep_compression/decode.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import datetime 4 | 5 | import torch 6 | import torchvision.models as models 7 | 8 | from slender.coding import Codec 9 | 10 | model_names = sorted(name for name in models.__dict__ 11 | if name.islower() and not name.startswith("__") 12 | and callable(models.__dict__[name])) 13 | 14 | parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') 15 | parser.add_argument('--arch', '-a', metavar='ARCH', default='resnet50', 16 | choices=model_names, 17 | help='model architecture: ' + 18 | ' | '.join(model_names) + 19 | ' (default: resnet50)') 20 | parser.add_argument('--pretrained', dest='pretrained', default='', 21 | help='use pre-trained encoded model') 22 | 23 | 24 | def main(): 25 | args = parser.parse_args() 26 | 27 | dir_name = args.arch + '_' + datetime.datetime.now().strftime('%m%d_%H%M') 28 | checkpoint_dir = os.path.join('checkpoints', os.path.join('coding', dir_name)) 29 | os.makedirs(checkpoint_dir) 30 | 31 | print("=" * 89) 32 | print("=> creating model '{}'".format(args.arch)) 33 | 34 | if args.arch.startswith('inception'): 35 | model = models.__dict__[args.arch](transform_input=True) 36 | else: 37 | model = models.__dict__[args.arch]() 38 | 39 | if args.pretrained: 40 | if os.path.isfile(args.pretrained): 41 | print("=> using pre-trained model '{}'".format(args.pretrained)) 42 | checkpoint = torch.load(args.pretrained) 43 | 44 | model = Codec.decode(model=model, state_dict=checkpoint['state_dict']) 45 | 46 | torch.save({ 47 | 'state_dict': model.state_dict(), 48 | }, os.path.join(checkpoint_dir, 'decode.pth.tar'), pickle_protocol=4) 49 | else: 50 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 51 | else: 52 | print("=> no checkpoint") 53 | 54 | print("=" * 89) 55 | 56 | 57 | if __name__ == '__main__': 58 | main() 59 | -------------------------------------------------------------------------------- /examples/deep_compression/encode.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import datetime 4 | 5 | import torch 6 | import torchvision.models as models 7 | 8 | from slender.coding import Codec 9 | from slender.utils import Logger 10 | 11 | model_names = sorted(name for name in models.__dict__ 12 | if name.islower() and not name.startswith("__") 13 | and callable(models.__dict__[name])) 14 | 15 | parser = argparse.ArgumentParser(description='PyTorch Encoding') 16 | parser.add_argument('--arch', '-a', metavar='ARCH', default='resnet50', 17 | choices=model_names, 18 | help='model architecture: ' + 19 | ' | '.join(model_names) + 20 | ' (default: resnet50)') 21 | parser.add_argument('--pretrained', default='', type=str, metavar='PATH', 22 | help='path to self-trained moel') 23 | parser.add_argument('--pretrained-parallel', dest='pretrained_parallel', 24 | action='store_true', 25 | help='self-trained model starts with torch.nn.DataParallel') 26 | parser.add_argument('--coding-rule', default='', 27 | help='path to coding rule file') 28 | 29 | 30 | def main(): 31 | args = parser.parse_args() 32 | 33 | dir_name = args.arch + '_' + datetime.datetime.now().strftime('%m%d_%H%M') 34 | log_dir = os.path.join('logs', os.path.join('coding', dir_name)) 35 | checkpoint_dir = os.path.join('checkpoints', os.path.join('coding', dir_name)) 36 | os.makedirs(log_dir) 37 | os.makedirs(checkpoint_dir) 38 | 39 | config_log = Logger(os.path.join(log_dir, 'config.log')) 40 | 41 | for k, v in vars(args).items(): 42 | config_log.write(content="{k} : {v}".format(k=k, v=v), wrap=True, flush=True) 43 | config_log.close() 44 | 45 | print("=" * 89) 46 | print("=> creating model '{}'".format(args.arch)) 47 | 48 | if args.arch.startswith('inception'): 49 | model = models.__dict__[args.arch](transform_input=True) 50 | else: 51 | model = models.__dict__[args.arch]() 52 | 53 | if args.pretrained: 54 | if args.pretrained_parallel: 55 | if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): 56 | model.features = torch.nn.DataParallel(model.features).cuda() 57 | else: 58 | model = torch.nn.DataParallel(model).cuda() 59 | 60 | if os.path.isfile(args.pretrained): 61 | print("=> loading checkpoint '{}'".format(args.pretrained)) 62 | checkpoint = torch.load(args.pretrained) 63 | model.load_state_dict(checkpoint['state_dict']) 64 | print("=> loaded checkpoint") 65 | else: 66 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 67 | 68 | if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): 69 | model.features = model.features.module 70 | else: 71 | model = model.module 72 | 73 | model = model.cpu() 74 | else: 75 | if os.path.isfile(args.pretrained): 76 | print("=> using pre-trained model '{}'".format(args.pretrained)) 77 | checkpoint = torch.load(args.pretrained) 78 | model.load_state_dict(checkpoint['state_dict']) 79 | else: 80 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 81 | 82 | codec = Codec(rule=args.coding_rule) 83 | 84 | encoded_model = codec.encode(model=model) 85 | 86 | torch.save({ 87 | 'state_dict': encoded_model.state_dict(), 88 | }, os.path.join(checkpoint_dir, 'encode.pth.tar'), pickle_protocol=4) 89 | 90 | else: 91 | print("=> no checkpoint") 92 | 93 | print("=" * 89) 94 | 95 | 96 | if __name__ == '__main__': 97 | main() 98 | -------------------------------------------------------------------------------- /examples/deep_compression/prune_train.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import datetime 3 | import os 4 | import shutil 5 | import time 6 | 7 | import torch 8 | import torch.backends.cudnn as cudnn 9 | import torch.nn as nn 10 | import torch.nn.parallel 11 | import torch.optim 12 | import torch.utils.data 13 | import torchvision.datasets as datasets 14 | import torchvision.models as models 15 | import torchvision.transforms as transforms 16 | 17 | from slender.prune import VanillaPruner 18 | from slender.utils import AverageMeter, Logger 19 | 20 | model_names = sorted(name for name in models.__dict__ 21 | if name.islower() and not name.startswith("__") 22 | and callable(models.__dict__[name])) 23 | 24 | parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') 25 | parser.add_argument('data', metavar='DIR', 26 | help='path to dataset') 27 | parser.add_argument('--arch', '-a', metavar='ARCH', default='resnet50', 28 | choices=model_names, 29 | help='model architecture: ' + 30 | ' | '.join(model_names) + 31 | ' (default: resnet50)') 32 | parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', 33 | help='number of data loading workers (default: 4)') 34 | parser.add_argument('--nGPU', type=int, default=4, 35 | help='the number of gpus for training') 36 | 37 | parser.add_argument('--epochs', default=45, type=int, metavar='N', 38 | help='number of total epochs to run') 39 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 40 | help='manual epoch number (useful on restarts)') 41 | parser.add_argument('-b', '--batch-size', default=256, type=int, 42 | metavar='N', help='mini-batch size (default: 256)') 43 | parser.add_argument('--lr', '--learning-rate', default=0.001, type=float, 44 | metavar='LR', 45 | help='initial learning rate (default: 0.001 |' 46 | ' for inception recommend 0.0256)') 47 | parser.add_argument('--lr-decay-step', default=15, type=int, metavar='N', 48 | help='every N epochs learning rate decays (default:15)') 49 | parser.add_argument('--lr-decay', default=0.1, type=float, metavar='LD', 50 | help='every lr-decay-step epochs learning rate decays ' 51 | 'by LD (default:0.1 | for inception recommend 0.16)') 52 | parser.add_argument('--momentum', default=0.9, type=float, metavar='M', 53 | help='momentum (default: 0.9)') 54 | parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float, 55 | metavar='WD', help='weight decay for sgd (default: 1e-4)') 56 | parser.add_argument('--alpha', default=0.9, type=float, 57 | metavar='ALPHA', help='alpha for RMSprop (default: 0.9)') 58 | parser.add_argument('--eps', '--epsilon', default=1.0, type=float, 59 | metavar='EPS', help='epsilon for RMSprop (default: 1.0)') 60 | parser.add_argument('--print-freq', '-p', default=10, type=int, 61 | metavar='N', help='print frequency (default: 10)') 62 | 63 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 64 | help='path to latest checkpoint (default: none)') 65 | parser.add_argument('--pretrained', default='', type=str, metavar='PATH', 66 | help='use pre-trained model: ' 67 | 'pytorch: use pytorch official | ' 68 | 'path to self-trained moel') 69 | parser.add_argument('--pretrained-parallel', dest='pretrained_parallel', 70 | action='store_true', 71 | help='self-trained model starts with torch.nn.DataParallel') 72 | 73 | parser.add_argument('--prune-rule', default='', 74 | help='path to prune rule file') 75 | parser.add_argument('--prune-stage', default=0, type=int, metavar='N', 76 | help='pruning stage') 77 | 78 | 79 | best_prec1 = 0 80 | 81 | 82 | def main(): 83 | global args, best_prec1, train_log, test_log 84 | args = parser.parse_args() 85 | 86 | dir_name = args.arch + '_' + datetime.datetime.now().strftime('%m%d_%H%M') 87 | log_dir = os.path.join('logs', os.path.join('prune', dir_name)) 88 | checkpoint_dir = os.path.join('checkpoints', os.path.join('prune', dir_name)) 89 | os.makedirs(log_dir) 90 | os.makedirs(checkpoint_dir) 91 | train_log = Logger(os.path.join(log_dir, 'train.log')) 92 | test_log = Logger(os.path.join(log_dir, 'test.log')) 93 | config_log = Logger(os.path.join(log_dir, 'config.log')) 94 | 95 | for k, v in vars(args).items(): 96 | config_log.write(content="{k} : {v}".format(k=k, v=v), wrap=True, flush=True) 97 | config_log.close() 98 | 99 | # create model 100 | print("=" * 89) 101 | print("=> creating model '{}'".format(args.arch)) 102 | 103 | if args.pretrained == 'pytorch': 104 | print("=> using pre-trained model from model zoo") 105 | model = models.__dict__[args.arch](pretrained=True) 106 | args.pretrained_parallel = False 107 | else: 108 | if args.arch.startswith('inception'): 109 | model = models.__dict__[args.arch](transform_input=True) 110 | else: 111 | model = models.__dict__[args.arch]() 112 | if args.pretrained and not args.pretrained_parallel: 113 | if os.path.isfile(args.pretrained): 114 | print("=> using pre-trained model '{}'".format(args.pretrained)) 115 | checkpoint = torch.load(args.pretrained) 116 | model.load_state_dict(checkpoint['state_dict']) 117 | else: 118 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 119 | 120 | if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): 121 | model.features = torch.nn.DataParallel(model.features, device_ids=list(range(args.nGPU))) 122 | model.cuda() 123 | else: 124 | model = torch.nn.DataParallel(model, device_ids=list(range(args.nGPU))).cuda() 125 | 126 | if args.pretrained and args.pretrained_parallel: 127 | if os.path.isfile(args.pretrained): 128 | print("=> loading checkpoint '{}'".format(args.pretrained)) 129 | checkpoint = torch.load(args.pretrained) 130 | model.load_state_dict(checkpoint['state_dict']) 131 | print("=> loaded checkpoint") 132 | else: 133 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 134 | 135 | # define loss function (criterion) and optimizer 136 | criterion = nn.CrossEntropyLoss().cuda() 137 | 138 | if args.arch.startswith('inception'): 139 | optimizer = torch.optim.RMSprop(model.parameters(), args.lr, 140 | alpha=args.alpha, eps=args.eps, 141 | momentum=args.momentum) 142 | else: 143 | optimizer = torch.optim.SGD(model.parameters(), args.lr, 144 | momentum=args.momentum, 145 | weight_decay=args.weight_decay) 146 | 147 | pruner = VanillaPruner(rule=args.prune_rule) 148 | 149 | # optionally resume from a checkpoint 150 | if args.resume: 151 | if os.path.isfile(args.resume): 152 | print("=> loading checkpoint '{}'".format(args.resume)) 153 | checkpoint = torch.load(args.resume) 154 | args.start_epoch = checkpoint['epoch'] 155 | model.load_state_dict(checkpoint['state_dict']) 156 | best_prec1 = checkpoint['best_prec1'] 157 | optimizer.load_state_dict(checkpoint['optimizer']) 158 | optimizer.zero_grad() 159 | pruner.load_state_dict(checkpoint['pruner'], replace_rule=False) 160 | print("=> loaded checkpoint (epoch {:3d}, best_prec1 {:.3f})" 161 | .format(args.start_epoch, best_prec1)) 162 | else: 163 | print("=> no checkpoint found at '{}'".format(args.resume)) 164 | 165 | print("=" * 89) 166 | 167 | cudnn.benchmark = True 168 | 169 | # Data loading code 170 | traindir = os.path.join(args.data, 'train') 171 | valdir = os.path.join(args.data, 'val') 172 | normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 173 | std=[0.229, 0.224, 0.225]) 174 | 175 | if args.arch.startswith('inception'): 176 | input_size = 299 177 | else: 178 | input_size = 224 179 | 180 | train_loader = torch.utils.data.DataLoader( 181 | datasets.ImageFolder(traindir, transforms.Compose([ 182 | transforms.RandomSizedCrop(input_size), 183 | transforms.RandomHorizontalFlip(), 184 | transforms.ToTensor(), 185 | normalize, 186 | ])), 187 | batch_size=args.batch_size, shuffle=True, 188 | num_workers=args.workers, pin_memory=True) 189 | 190 | val_loader = torch.utils.data.DataLoader( 191 | datasets.ImageFolder(valdir, transforms.Compose([ 192 | transforms.Scale(int(input_size / 0.875)), 193 | transforms.CenterCrop(input_size), 194 | transforms.ToTensor(), 195 | normalize, 196 | ])), 197 | batch_size=args.batch_size, shuffle=False, 198 | num_workers=args.workers, pin_memory=True) 199 | 200 | for epoch in range(args.start_epoch, args.epochs): 201 | if epoch == 0: 202 | pruner.prune(model=model, stage=args.prune_stage, update_masks=True) 203 | best_prec1 = validate(val_loader, model, criterion, epoch) 204 | 205 | adjust_learning_rate(optimizer, epoch=epoch) 206 | 207 | # train for one epoch 208 | train(train_loader=train_loader, model=model, criterion=criterion, optimizer=optimizer, 209 | pruner=pruner, epoch=epoch) 210 | 211 | # evaluate on validation set 212 | prec1 = validate(val_loader=val_loader, model=model, criterion=criterion, epoch=epoch) 213 | 214 | # remember best prec@1 and save checkpoint 215 | is_best = prec1 > best_prec1 216 | best_prec1 = max(prec1, best_prec1) 217 | save_checkpoint({ 218 | 'epoch': epoch + 1, 219 | 'arch': args.arch, 220 | 'state_dict': model.state_dict(), 221 | 'best_prec1': best_prec1, 222 | 'optimizer': optimizer.state_dict(), 223 | 'pruner': pruner.state_dict(), 224 | }, is_best=is_best, checkpoint_dir=checkpoint_dir) 225 | if (epoch + 1) in args.prune_step: 226 | save_checkpoint({ 227 | 'epoch': epoch + 1, 228 | 'arch': args.arch, 229 | 'state_dict': model.state_dict(), 230 | 'prec1': prec1, 231 | 'pruner': pruner.state_dict(), 232 | }, is_best=False, filename='stage_{}.pth.tar'.format(stage_id), 233 | checkpoint_dir=checkpoint_dir) 234 | 235 | train_log.close() 236 | test_log.close() 237 | 238 | 239 | def train(train_loader, model, criterion, optimizer, pruner, epoch): 240 | batch_time = AverageMeter() 241 | data_time = AverageMeter() 242 | losses = AverageMeter() 243 | top1 = AverageMeter() 244 | top5 = AverageMeter() 245 | 246 | # switch to train mode 247 | model.train() 248 | print("=" * 89) 249 | 250 | end = time.time() 251 | for i, (input, target) in enumerate(train_loader): 252 | # measure data loading time 253 | data_time.update(time.time() - end) 254 | 255 | target = target.cuda(non_blocking=True) 256 | 257 | # compute output 258 | if args.arch.startswith('inception'): 259 | output, aux_output = model(input) 260 | loss = criterion(output, target) + criterion(aux_output, target) 261 | 262 | else: 263 | output = model(input) 264 | loss = criterion(output, target) 265 | 266 | # measure accuracy and record loss 267 | prec1, prec5 = accuracy(output, target, topk=(1, 5)) 268 | losses.update(loss.item(), input.size(0)) 269 | top1.update(prec1[0], input.size(0)) 270 | top5.update(prec5[0], input.size(0)) 271 | 272 | # compute gradient and do SGD step 273 | optimizer.zero_grad() 274 | loss.backward() 275 | optimizer.step() 276 | 277 | # pruning 278 | pruner.prune(model=model, stage=args.prune_stage, update_masks=False) 279 | 280 | # measure elapsed time 281 | batch_time.update(time.time() - end) 282 | end = time.time() 283 | 284 | if i % args.print_freq == 0: 285 | print("Epoch: [{0}][{1}/{2}]\t" 286 | "Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t" 287 | "Data {data_time.val:.3f} ({data_time.avg:.3f})\t" 288 | "Loss {loss.val:.4f} ({loss.avg:.4f})\t" 289 | "Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t" 290 | "Prec@5 {top5.val:.3f} ({top5.avg:.3f})".format( 291 | epoch, i, len(train_loader), batch_time=batch_time, 292 | data_time=data_time, loss=losses, top1=top1, top5=top5)) 293 | print("=" * 89) 294 | print(' * Train Epoch: {epoch:3d} | Prec@1: {top1.avg:.3f} | Prec@5: {top5.avg:.3f}' 295 | .format(epoch=epoch, top1=top1, top5=top5)) 296 | print("=" * 89) 297 | train_log.write(content="{epoch}\t" 298 | "{top1.avg:.4e}\t" 299 | "{top5.avg:.4e}\t" 300 | "{loss.avg:.4e}" 301 | .format(epoch=epoch, top1=top1, top5=top5, loss=losses), wrap=True, flush=True) 302 | 303 | 304 | def validate(val_loader, model, criterion, epoch): 305 | batch_time = AverageMeter() 306 | losses = AverageMeter() 307 | top1 = AverageMeter() 308 | top5 = AverageMeter() 309 | 310 | # switch to evaluate mode 311 | model.eval() 312 | print("=" * 89) 313 | 314 | with torch.no_grad(): 315 | end = time.time() 316 | for i, (input, target) in enumerate(val_loader): 317 | target = target.cuda(non_blocking=True) 318 | 319 | # compute output 320 | output = model(input) 321 | loss = criterion(output, target) 322 | 323 | # measure accuracy and record loss 324 | prec1, prec5 = accuracy(output, target, topk=(1, 5)) 325 | losses.update(loss.item(), input.size(0)) 326 | top1.update(prec1[0], input.size(0)) 327 | top5.update(prec5[0], input.size(0)) 328 | 329 | # measure elapsed time 330 | batch_time.update(time.time() - end) 331 | end = time.time() 332 | 333 | if i % args.print_freq == 0: 334 | print('Test: [{0}/{1}]\t' 335 | 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 336 | 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 337 | 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 338 | 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format( 339 | i, len(val_loader), batch_time=batch_time, loss=losses, 340 | top1=top1, top5=top5)) 341 | print("=" * 89) 342 | print(' * Test Epoch: {epoch:3d} | Prec@1: {top1.avg:.3f} | Prec@5: {top5.avg:.3f}' 343 | .format(epoch=epoch, top1=top1, top5=top5)) 344 | print("=" * 89) 345 | test_log.write(content="{epoch}\t" 346 | "{top1.avg:.4e}\t" 347 | "{top5.avg:.4e}\t" 348 | .format(epoch=epoch, top1=top1, top5=top5), wrap=True, flush=True) 349 | 350 | return top1.avg 351 | 352 | 353 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar', checkpoint_dir='.'): 354 | filename = os.path.join(checkpoint_dir, filename) 355 | torch.save(state, filename, pickle_protocol=4) 356 | if is_best: 357 | shutil.copyfile(filename, os.path.join(checkpoint_dir, 'model_best.pth.tar')) 358 | 359 | 360 | def adjust_learning_rate(optimizer, epoch=0): 361 | """ 362 | Sets the learning rate to the initial LR decayed by args.lr_decay every lr_decay_step epochs 363 | :param optimizer: 364 | :param epoch: 365 | :param stage: 366 | :return: 367 | """ 368 | decay = epoch // args.lr_decay_step 369 | lr = args.lr * (args.lr_decay ** decay) 370 | print("Stage: {stage:2d} Epoch: {epoch:3d} | " 371 | "learning rate = {lr:.6f} = origin x ({lr_decay:.2f} ** {decay:2d})" 372 | .format(stage=args.prune_stage, epoch=epoch, lr=lr, lr_decay=args.lr_decay, decay=decay)) 373 | 374 | for param_group in optimizer.param_groups: 375 | param_group['lr'] = lr 376 | 377 | 378 | def accuracy(output, target, topk=(1,)): 379 | """Computes the precision@k for the specified values of k""" 380 | with torch.no_grad(): 381 | maxk = max(topk) 382 | batch_size = target.size(0) 383 | 384 | _, pred = output.topk(maxk, 1, True, True) 385 | pred = pred.t() 386 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 387 | 388 | res = [] 389 | for k in topk: 390 | correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) 391 | res.append(correct_k.mul_(100.0 / batch_size)) 392 | return res 393 | 394 | 395 | if __name__ == '__main__': 396 | main() 397 | -------------------------------------------------------------------------------- /examples/deep_compression/quantize_train.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import datetime 3 | import os 4 | import shutil 5 | import time 6 | 7 | import torch 8 | import torch.backends.cudnn as cudnn 9 | import torch.nn as nn 10 | import torch.nn.parallel 11 | import torch.optim 12 | import torch.utils.data 13 | import torchvision.datasets as datasets 14 | import torchvision.models as models 15 | import torchvision.transforms as transforms 16 | 17 | from slender.quantize import Quantizer 18 | from slender.utils import AverageMeter, Logger 19 | 20 | model_names = sorted(name for name in models.__dict__ 21 | if name.islower() and not name.startswith("__") 22 | and callable(models.__dict__[name])) 23 | 24 | parser = argparse.ArgumentParser(description='PyTorch Quantized Training') 25 | parser.add_argument('data', metavar='DIR', 26 | help='path to dataset') 27 | parser.add_argument('--arch', '-a', metavar='ARCH', default='resnet50', 28 | choices=model_names, 29 | help='model architecture: ' + 30 | ' | '.join(model_names) + 31 | ' (default: resnet50)') 32 | parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', 33 | help='number of data loading workers (default: 4)') 34 | parser.add_argument('--nGPU', type=int, default=4, 35 | help='the number of gpus for training') 36 | 37 | parser.add_argument('--epochs', default=20, type=int, metavar='N', 38 | help='number of total epochs to run') 39 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 40 | help='manual epoch number (useful on restarts)') 41 | parser.add_argument('-b', '--batch-size', default=256, type=int, 42 | metavar='N', help='mini-batch size (default: 256)') 43 | parser.add_argument('--lr', '--learning-rate', default=0.001, type=float, 44 | metavar='LR', 45 | help='initial learning rate (default: 0.001 |' 46 | ' for inception recommend 0.0256)') 47 | parser.add_argument('--lr-decay', default=0.1, type=float, metavar='LD', 48 | help='every N1,N2,... epochs learning rate decays by LD ' 49 | '(default:0.1 | for inception recommend 0.16)') 50 | parser.add_argument('--lr-decay-step', default=5, metavar='N', type=int, 51 | help='every N epochs learning rate decays (default: 5)') 52 | parser.add_argument('--momentum', default=0.9, type=float, metavar='M', 53 | help='momentum (default: 0.9)') 54 | parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float, 55 | metavar='WD', help='weight decay for sgd (default: 1e-4)') 56 | parser.add_argument('--alpha', default=0.9, type=float, 57 | metavar='ALPHA', help='alpha for RMSprop (default: 0.9)') 58 | parser.add_argument('--eps', '--epsilon', default=1.0, type=float, 59 | metavar='EPS', help='epsilon for RMSprop (default: 1.0)') 60 | parser.add_argument('--print-freq', '-p', default=10, type=int, 61 | metavar='N', help='print frequency (default: 10)') 62 | 63 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 64 | help='path to latest checkpoint (default: none)') 65 | parser.add_argument('--pretrained', default='', type=str, metavar='PATH', 66 | help='use pre-trained model: ' 67 | 'pytorch: use pytorch official | ' 68 | 'path to self-trained moel') 69 | parser.add_argument('--pretrained-parallel', dest='pretrained_parallel', 70 | action='store_true', 71 | help='self-trained model starts with torch.nn.DataParallel') 72 | 73 | parser.add_argument('--quantize-rule', default='', 74 | help='path to quantization rule file') 75 | parser.add_argument('-z', '--not-fix-zeros', dest='not_fix_zeros', 76 | action="store_true", help='not fix zeros in quantization') 77 | parser.add_argument('-l', '--update-labels', dest='update_labels', action="store_true", 78 | help='update centers of codebook and labels per iteration') 79 | parser.add_argument('-r', '--re-quantize', dest='re_quantize', action="store_true", 80 | help='re-quantize (re-kmeans) per iteration') 81 | 82 | 83 | best_prec1 = 0 84 | 85 | 86 | def main(): 87 | global args, best_prec1, train_log, test_log 88 | args = parser.parse_args() 89 | 90 | dir_name = args.arch + '_' + datetime.datetime.now().strftime('%m%d_%H%M') 91 | log_dir = os.path.join('logs', os.path.join('quantize', dir_name)) 92 | checkpoint_dir = os.path.join('checkpoints', os.path.join('quantize', dir_name)) 93 | os.makedirs(log_dir) 94 | os.makedirs(checkpoint_dir) 95 | train_log = Logger(os.path.join(log_dir, 'train.log')) 96 | test_log = Logger(os.path.join(log_dir, 'test.log')) 97 | config_log = Logger(os.path.join(log_dir, 'config.log')) 98 | 99 | for k, v in vars(args).items(): 100 | config_log.write(content="{k} : {v}".format(k=k, v=v), wrap=True, flush=True) 101 | config_log.close() 102 | 103 | # create model 104 | print("=" * 89) 105 | print("=> creating model '{}'".format(args.arch)) 106 | 107 | if args.pretrained == 'pytorch': 108 | print("=> using pre-trained model from pytorch model zoo") 109 | model = models.__dict__[args.arch](pretrained=True) 110 | args.pretrained_parallel = False 111 | else: 112 | if args.arch.startswith('inception'): 113 | model = models.__dict__[args.arch](transform_input=True) 114 | else: 115 | model = models.__dict__[args.arch]() 116 | if args.pretrained and not args.pretrained_parallel: 117 | if os.path.isfile(args.pretrained): 118 | print("=> using pre-trained model '{}'".format(args.pretrained)) 119 | checkpoint = torch.load(args.pretrained) 120 | model.load_state_dict(checkpoint['state_dict']) 121 | else: 122 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 123 | 124 | if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): 125 | model.features = torch.nn.DataParallel(model.features, device_ids=list(range(args.nGPU))) 126 | model.cuda() 127 | else: 128 | model = torch.nn.DataParallel(model, device_ids=list(range(args.nGPU))).cuda() 129 | 130 | if args.pretrained and args.pretrained_parallel: 131 | if os.path.isfile(args.pretrained): 132 | print("=> loading checkpoint '{}'".format(args.pretrained)) 133 | checkpoint = torch.load(args.pretrained) 134 | model.load_state_dict(checkpoint['state_dict']) 135 | print("=> loaded checkpoint") 136 | else: 137 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 138 | 139 | # define loss function (criterion) and optimizer 140 | criterion = nn.CrossEntropyLoss().cuda() 141 | 142 | if args.arch.startswith('inception'): 143 | optimizer = torch.optim.RMSprop(model.parameters(), args.lr, 144 | alpha=args.alpha, eps=args.eps, 145 | momentum=args.momentum) 146 | else: 147 | optimizer = torch.optim.SGD(model.parameters(), args.lr, 148 | momentum=args.momentum, 149 | weight_decay=args.weight_decay) 150 | 151 | # quantize 152 | quantizer = Quantizer(rule=args.quantize_rule, fix_zeros=(not args.not_fix_zeros)) 153 | 154 | # optionally resume from a checkpoint 155 | if args.resume: 156 | if os.path.isfile(args.resume): 157 | print("=> loading checkpoint '{}'".format(args.resume)) 158 | checkpoint = torch.load(args.resume) 159 | args.start_epoch = checkpoint['epoch'] 160 | model.load_state_dict(checkpoint['state_dict']) 161 | best_prec1 = checkpoint['best_prec1'] 162 | optimizer.load_state_dict(checkpoint['optimizer']) 163 | optimizer.zero_grad() 164 | quantizer.load_state_dict(checkpoint['quantizer']) 165 | print("=> loaded checkpoint (epoch {:3d}, best_prec1 {:.3f})" 166 | .format(args.start_epoch, best_prec1)) 167 | else: 168 | print("=> no checkpoint found at '{}'".format(args.resume)) 169 | 170 | cudnn.benchmark = True 171 | 172 | # Data loading code 173 | traindir = os.path.join(args.data, 'train') 174 | valdir = os.path.join(args.data, 'val') 175 | normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 176 | std=[0.229, 0.224, 0.225]) 177 | 178 | if args.arch.startswith('inception'): 179 | input_size = 299 180 | else: 181 | input_size = 224 182 | 183 | train_loader = torch.utils.data.DataLoader( 184 | datasets.ImageFolder(traindir, transforms.Compose([ 185 | transforms.RandomSizedCrop(input_size), 186 | transforms.RandomHorizontalFlip(), 187 | transforms.ToTensor(), 188 | normalize, 189 | ])), 190 | batch_size=args.batch_size, shuffle=True, 191 | num_workers=args.workers, pin_memory=True) 192 | 193 | val_loader = torch.utils.data.DataLoader( 194 | datasets.ImageFolder(valdir, transforms.Compose([ 195 | transforms.Scale(int(input_size / 0.875)), 196 | transforms.CenterCrop(input_size), 197 | transforms.ToTensor(), 198 | normalize, 199 | ])), 200 | batch_size=args.batch_size, shuffle=False, 201 | num_workers=args.workers, pin_memory=True) 202 | 203 | for epoch in range(args.start_epoch, args.epochs): 204 | adjust_learning_rate(optimizer, epoch) 205 | 206 | # train for one epoch 207 | train(train_loader=train_loader, model=model, criterion=criterion, optimizer=optimizer, 208 | quantizer=quantizer, epoch=epoch) 209 | 210 | # evaluate on validation set 211 | prec1 = validate(val_loader, model, criterion, epoch) 212 | 213 | # remember best prec@1 and save checkpoint 214 | is_best = prec1 > best_prec1 215 | best_prec1 = max(prec1, best_prec1) 216 | save_checkpoint({ 217 | 'epoch': epoch + 1, 218 | 'arch': args.arch, 219 | 'state_dict': model.state_dict(), 220 | 'best_prec1': best_prec1, 221 | 'optimizer': optimizer.state_dict(), 222 | 'quantizer': quantizer.state_dict(), 223 | }, is_best=is_best, checkpoint_dir=checkpoint_dir) 224 | 225 | train_log.close() 226 | test_log.close() 227 | 228 | 229 | def train(train_loader, model, criterion, optimizer, quantizer, epoch): 230 | batch_time = AverageMeter() 231 | data_time = AverageMeter() 232 | losses = AverageMeter() 233 | top1 = AverageMeter() 234 | top5 = AverageMeter() 235 | 236 | # switch to train mode 237 | model.train() 238 | print("=" * 89) 239 | 240 | end = time.time() 241 | for i, (input, target) in enumerate(train_loader): 242 | # measure data loading time 243 | data_time.update(time.time() - end) 244 | 245 | target = target.cuda(non_blocking=True) 246 | 247 | # compute output 248 | if args.arch.startswith('inception'): 249 | output, aux_output = model(input) 250 | loss = criterion(output, target) + criterion(aux_output, target) 251 | 252 | else: 253 | output = model(input) 254 | loss = criterion(output, target) 255 | 256 | # measure accuracy and record loss 257 | prec1, prec5 = accuracy(output, target, topk=(1, 5)) 258 | losses.update(loss.item(), input.size(0)) 259 | top1.update(prec1[0], input.size(0)) 260 | top5.update(prec5[0], input.size(0)) 261 | 262 | # compute gradient and do SGD step 263 | optimizer.zero_grad() 264 | loss.backward() 265 | optimizer.step() 266 | 267 | # quantize 268 | quantizer.quantize(model=model, update_labels=args.update_labels, re_quantize=args.re_quantize) 269 | 270 | # measure elapsed time 271 | batch_time.update(time.time() - end) 272 | end = time.time() 273 | 274 | if i % args.print_freq == 0: 275 | print('Epoch: [{0}][{1}/{2}]\t' 276 | 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 277 | 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 278 | 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 279 | 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 280 | 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format( 281 | epoch, i, len(train_loader), batch_time=batch_time, 282 | data_time=data_time, loss=losses, top1=top1, top5=top5)) 283 | print("=" * 89) 284 | print(' * Train Epoch: {epoch:3d} | Prec@1: {top1.avg:.3f} | Prec@5: {top5.avg:.3f}' 285 | .format(epoch=epoch, top1=top1, top5=top5)) 286 | print("=" * 89) 287 | train_log.write(content="{epoch}\t" 288 | "{top1.avg:.4e}\t" 289 | "{top5.avg:.4e}\t" 290 | "{loss.avg:.4e}" 291 | .format(epoch=epoch, top1=top1, top5=top5, loss=losses), wrap=True, flush=True) 292 | 293 | 294 | def validate(val_loader, model, criterion, epoch): 295 | batch_time = AverageMeter() 296 | losses = AverageMeter() 297 | top1 = AverageMeter() 298 | top5 = AverageMeter() 299 | 300 | # switch to evaluate mode 301 | model.eval() 302 | print("=" * 89) 303 | 304 | end = time.time() 305 | for i, (input, target) in enumerate(val_loader): 306 | target = target.cuda(non_blocking=True) 307 | 308 | # compute output 309 | output = model(input) 310 | loss = criterion(output, target) 311 | 312 | # measure accuracy and record loss 313 | prec1, prec5 = accuracy(output, target, topk=(1, 5)) 314 | losses.update(loss.item(), input.size(0)) 315 | top1.update(prec1[0], input.size(0)) 316 | top5.update(prec5[0], input.size(0)) 317 | 318 | # measure elapsed time 319 | batch_time.update(time.time() - end) 320 | end = time.time() 321 | 322 | if i % args.print_freq == 0: 323 | print('Test: [{0}/{1}]\t' 324 | 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 325 | 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 326 | 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 327 | 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format( 328 | i, len(val_loader), batch_time=batch_time, loss=losses, 329 | top1=top1, top5=top5)) 330 | 331 | print("=" * 89) 332 | print(' * Test Epoch: {epoch:3d} | Prec@1: {top1.avg:.3f} | Prec@5: {top5.avg:.3f}' 333 | .format(epoch=epoch, top1=top1, top5=top5)) 334 | print("=" * 89) 335 | test_log.write(content="{epoch}\t" 336 | "{top1.avg:.4e}\t" 337 | "{top5.avg:.4e}\t" 338 | .format(epoch=epoch, top1=top1, top5=top5), wrap=True, flush=True) 339 | 340 | return top1.avg 341 | 342 | 343 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar', checkpoint_dir='.'): 344 | filename = os.path.join(checkpoint_dir, filename) 345 | torch.save(state, filename, pickle_protocol=4) 346 | if is_best: 347 | shutil.copyfile(filename, os.path.join(checkpoint_dir, 'model_best.pth.tar')) 348 | 349 | 350 | def adjust_learning_rate(optimizer, epoch): 351 | """ 352 | Sets the learning rate to the initial LR decayed by args.lr_decay every lr_decay_step epochs 353 | :param optimizer: 354 | :param epoch: 355 | :return: 356 | """ 357 | decay = epoch // args.lr_decay_step 358 | lr = args.lr * (args.lr_decay ** decay) 359 | print("Epoch: {epoch:3d} | learning rate = {lr:.6f} = origin x ({lr_decay:.2f} ** {decay:2d})" 360 | .format(epoch=epoch, lr=lr, lr_decay=args.lr_decay, decay=decay)) 361 | for param_group in optimizer.param_groups: 362 | param_group['lr'] = lr 363 | 364 | 365 | def accuracy(output, target, topk=(1,)): 366 | """Computes the precision@k for the specified values of k""" 367 | with torch.no_grad(): 368 | maxk = max(topk) 369 | batch_size = target.size(0) 370 | 371 | _, pred = output.topk(maxk, 1, True, True) 372 | pred = pred.t() 373 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 374 | 375 | res = [] 376 | for k in topk: 377 | correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) 378 | res.append(correct_k.mul_(100.0 / batch_size)) 379 | return res 380 | 381 | 382 | if __name__ == '__main__': 383 | main() 384 | -------------------------------------------------------------------------------- /examples/deep_compression/rules/inception_v3/coding.rule: -------------------------------------------------------------------------------- 1 | Conv2d_1a_3x3.conv.weight huffman 0 0 4 2 | Conv2d_2a_3x3.conv.weight huffman 0 0 4 3 | Conv2d_2b_3x3.conv.weight huffman 0 0 4 4 | Conv2d_3b_1x1.conv.weight huffman 0 0 4 5 | Conv2d_4a_3x3.conv.weight huffman 0 0 4 6 | Mixed_5b.branch1x1.conv.weight huffman 0 0 4 7 | Mixed_5b.branch5x5_1.conv.weight huffman 0 0 4 8 | Mixed_5b.branch5x5_2.conv.weight huffman 0 0 4 9 | Mixed_5b.branch3x3dbl_1.conv.weight huffman 0 0 4 10 | Mixed_5b.branch3x3dbl_2.conv.weight huffman 0 0 4 11 | Mixed_5b.branch3x3dbl_3.conv.weight huffman 0 0 4 12 | Mixed_5b.branch_pool.conv.weight huffman 0 0 4 13 | Mixed_5c.branch1x1.conv.weight huffman 0 0 4 14 | Mixed_5c.branch5x5_1.conv.weight huffman 0 0 4 15 | Mixed_5c.branch5x5_2.conv.weight huffman 0 0 4 16 | Mixed_5c.branch3x3dbl_1.conv.weight huffman 0 0 4 17 | Mixed_5c.branch3x3dbl_2.conv.weight huffman 0 0 4 18 | Mixed_5c.branch3x3dbl_3.conv.weight huffman 0 0 4 19 | Mixed_5c.branch_pool.conv.weight huffman 0 0 4 20 | Mixed_5d.branch1x1.conv.weight huffman 0 0 4 21 | Mixed_5d.branch5x5_1.conv.weight huffman 0 0 4 22 | Mixed_5d.branch5x5_2.conv.weight huffman 0 0 4 23 | Mixed_5d.branch3x3dbl_1.conv.weight huffman 0 0 4 24 | Mixed_5d.branch3x3dbl_2.conv.weight huffman 0 0 4 25 | Mixed_5d.branch3x3dbl_3.conv.weight huffman 0 0 4 26 | Mixed_5d.branch_pool.conv.weight huffman 0 0 4 27 | Mixed_6a.branch3x3.conv.weight huffman 0 0 4 28 | Mixed_6a.branch3x3dbl_1.conv.weight huffman 0 0 4 29 | Mixed_6a.branch3x3dbl_2.conv.weight huffman 0 0 4 30 | Mixed_6a.branch3x3dbl_3.conv.weight huffman 0 0 4 31 | Mixed_6b.branch1x1.conv.weight huffman 0 0 4 32 | Mixed_6b.branch7x7_1.conv.weight huffman 0 0 4 33 | Mixed_6b.branch7x7_2.conv.weight huffman 0 0 4 34 | Mixed_6b.branch7x7_3.conv.weight huffman 0 0 4 35 | Mixed_6b.branch7x7dbl_1.conv.weight huffman 0 0 4 36 | Mixed_6b.branch7x7dbl_2.conv.weight huffman 0 0 4 37 | Mixed_6b.branch7x7dbl_3.conv.weight huffman 0 0 4 38 | Mixed_6b.branch7x7dbl_4.conv.weight huffman 0 0 4 39 | Mixed_6b.branch7x7dbl_5.conv.weight huffman 0 0 4 40 | Mixed_6b.branch_pool.conv.weight huffman 0 0 4 41 | Mixed_6c.branch1x1.conv.weight huffman 0 0 4 42 | Mixed_6c.branch7x7_1.conv.weight huffman 0 0 4 43 | Mixed_6c.branch7x7_2.conv.weight huffman 0 0 4 44 | Mixed_6c.branch7x7_3.conv.weight huffman 0 0 4 45 | Mixed_6c.branch7x7dbl_1.conv.weight huffman 0 0 4 46 | Mixed_6c.branch7x7dbl_2.conv.weight huffman 0 0 4 47 | Mixed_6c.branch7x7dbl_3.conv.weight huffman 0 0 4 48 | Mixed_6c.branch7x7dbl_4.conv.weight huffman 0 0 4 49 | Mixed_6c.branch7x7dbl_5.conv.weight huffman 0 0 4 50 | Mixed_6c.branch_pool.conv.weight huffman 0 0 4 51 | Mixed_6d.branch1x1.conv.weight huffman 0 0 4 52 | Mixed_6d.branch7x7_1.conv.weight huffman 0 0 4 53 | Mixed_6d.branch7x7_2.conv.weight huffman 0 0 4 54 | Mixed_6d.branch7x7_3.conv.weight huffman 0 0 4 55 | Mixed_6d.branch7x7dbl_1.conv.weight huffman 0 0 4 56 | Mixed_6d.branch7x7dbl_2.conv.weight huffman 0 0 4 57 | Mixed_6d.branch7x7dbl_3.conv.weight huffman 0 0 4 58 | Mixed_6d.branch7x7dbl_4.conv.weight huffman 0 0 4 59 | Mixed_6d.branch7x7dbl_5.conv.weight huffman 0 0 4 60 | Mixed_6d.branch_pool.conv.weight huffman 0 0 4 61 | Mixed_6e.branch1x1.conv.weight huffman 0 0 4 62 | Mixed_6e.branch7x7_1.conv.weight huffman 0 0 4 63 | Mixed_6e.branch7x7_2.conv.weight huffman 0 0 4 64 | Mixed_6e.branch7x7_3.conv.weight huffman 0 0 4 65 | Mixed_6e.branch7x7dbl_1.conv.weight huffman 0 0 4 66 | Mixed_6e.branch7x7dbl_2.conv.weight huffman 0 0 4 67 | Mixed_6e.branch7x7dbl_3.conv.weight huffman 0 0 4 68 | Mixed_6e.branch7x7dbl_4.conv.weight huffman 0 0 4 69 | Mixed_6e.branch7x7dbl_5.conv.weight huffman 0 0 4 70 | Mixed_6e.branch_pool.conv.weight huffman 0 0 4 71 | Mixed_7a.branch3x3_1.conv.weight huffman 0 0 4 72 | Mixed_7a.branch3x3_2.conv.weight huffman 0 0 4 73 | Mixed_7a.branch7x7x3_1.conv.weight huffman 0 0 4 74 | Mixed_7a.branch7x7x3_2.conv.weight huffman 0 0 4 75 | Mixed_7a.branch7x7x3_3.conv.weight huffman 0 0 4 76 | Mixed_7a.branch7x7x3_4.conv.weight huffman 0 0 4 77 | Mixed_7b.branch1x1.conv.weight huffman 0 0 4 78 | Mixed_7b.branch3x3_1.conv.weight huffman 0 0 4 79 | Mixed_7b.branch3x3_2a.conv.weight huffman 0 0 4 80 | Mixed_7b.branch3x3_2b.conv.weight huffman 0 0 4 81 | Mixed_7b.branch3x3dbl_1.conv.weight huffman 0 0 4 82 | Mixed_7b.branch3x3dbl_2.conv.weight huffman 0 0 4 83 | Mixed_7b.branch3x3dbl_3a.conv.weight huffman 0 0 4 84 | Mixed_7b.branch3x3dbl_3b.conv.weight huffman 0 0 4 85 | Mixed_7b.branch_pool.conv.weight huffman 0 0 4 86 | Mixed_7c.branch1x1.conv.weight huffman 0 0 4 87 | Mixed_7c.branch3x3_1.conv.weight huffman 0 0 4 88 | Mixed_7c.branch3x3_2a.conv.weight huffman 0 0 4 89 | Mixed_7c.branch3x3_2b.conv.weight huffman 0 0 4 90 | Mixed_7c.branch3x3dbl_1.conv.weight huffman 0 0 4 91 | Mixed_7c.branch3x3dbl_2.conv.weight huffman 0 0 4 92 | Mixed_7c.branch3x3dbl_3a.conv.weight huffman 0 0 4 93 | Mixed_7c.branch3x3dbl_3b.conv.weight huffman 0 0 4 94 | Mixed_7c.branch_pool.conv.weight huffman 0 0 4 95 | fc.weight huffman 0 0 4 96 | -------------------------------------------------------------------------------- /examples/deep_compression/rules/inception_v3/prune_autogenerate.rule: -------------------------------------------------------------------------------- 1 | module.Conv2d_1a_3x3.conv.weight element 0.4,0.6 2 | module.Conv2d_2a_3x3.conv.weight element 0.3,0.4 3 | module.Conv2d_2b_3x3.conv.weight element 0.2,0.5 4 | module.Conv2d_3b_1x1.conv.weight element 0.2,0.4 5 | module.Conv2d_4a_3x3.conv.weight element 0.3,0.5 6 | module.Mixed_5b.branch1x1.conv.weight element 0.2,0.4 7 | module.Mixed_5b.branch5x5_1.conv.weight element 0.5,0.7 8 | module.Mixed_5b.branch5x5_2.conv.weight element 0.6,0.8 9 | module.Mixed_5b.branch3x3dbl_1.conv.weight element 0.5,0.7 10 | module.Mixed_5b.branch3x3dbl_2.conv.weight element 0.6,0.7 11 | module.Mixed_5b.branch3x3dbl_3.conv.weight element 0.7,0.8 12 | module.Mixed_5b.branch_pool.conv.weight element 0.4,0.6 13 | module.Mixed_5c.branch1x1.conv.weight element 0.3,0.5 14 | module.Mixed_5c.branch5x5_1.conv.weight element 0.5,0.9 15 | module.Mixed_5c.branch5x5_2.conv.weight element 0.7,0.8 16 | module.Mixed_5c.branch3x3dbl_1.conv.weight element 0.5,0.8 17 | module.Mixed_5c.branch3x3dbl_2.conv.weight element 0.7,0.8 18 | module.Mixed_5c.branch3x3dbl_3.conv.weight element 0.7,0.8 19 | module.Mixed_5c.branch_pool.conv.weight element 0.4,0.7 20 | module.Mixed_5d.branch1x1.conv.weight element 0.4,0.6 21 | module.Mixed_5d.branch5x5_1.conv.weight element 0.6,0.8 22 | module.Mixed_5d.branch5x5_2.conv.weight element 0.7,0.8 23 | module.Mixed_5d.branch3x3dbl_1.conv.weight element 0.7,0.9 24 | module.Mixed_5d.branch3x3dbl_2.conv.weight element 0.6,0.7 25 | module.Mixed_5d.branch3x3dbl_3.conv.weight element 0.7,0.8 26 | module.Mixed_5d.branch_pool.conv.weight element 0.5,0.7 27 | module.Mixed_6a.branch3x3.conv.weight element 0.6,0.8 28 | module.Mixed_6a.branch3x3dbl_1.conv.weight element 0.6,0.9 29 | module.Mixed_6a.branch3x3dbl_2.conv.weight element 0.7,0.8 30 | module.Mixed_6a.branch3x3dbl_3.conv.weight element 0.8,0.9 31 | module.Mixed_6b.branch1x1.conv.weight element 0.4,0.5 32 | module.Mixed_6b.branch7x7_1.conv.weight element 0.6,0.8 33 | module.Mixed_6b.branch7x7_2.conv.weight element 0.8,0.9 34 | module.Mixed_6b.branch7x7_3.conv.weight element 0.7,0.8 35 | module.Mixed_6b.branch7x7dbl_1.conv.weight element 0.6,0.8 36 | module.Mixed_6b.branch7x7dbl_2.conv.weight element 0.8,0.9 37 | module.Mixed_6b.branch7x7dbl_3.conv.weight element 0.7,0.8 38 | module.Mixed_6b.branch7x7dbl_4.conv.weight element 0.8,0.9 39 | module.Mixed_6b.branch7x7dbl_5.conv.weight element 0.7,0.9 40 | module.Mixed_6b.branch_pool.conv.weight element 0.5,0.6 41 | module.Mixed_6c.branch1x1.conv.weight element 0.4,0.8 42 | module.Mixed_6c.branch7x7_1.conv.weight element 0.7,0.9 43 | module.Mixed_6c.branch7x7_2.conv.weight element 0.8,0.9 44 | module.Mixed_6c.branch7x7_3.conv.weight element 0.7,0.9 45 | module.Mixed_6c.branch7x7dbl_1.conv.weight element 0.8,0.9 46 | module.Mixed_6c.branch7x7dbl_2.conv.weight element 0.8,0.9 47 | module.Mixed_6c.branch7x7dbl_3.conv.weight element 0.8,0.9 48 | module.Mixed_6c.branch7x7dbl_4.conv.weight element 0.8,0.9 49 | module.Mixed_6c.branch7x7dbl_5.conv.weight element 0.8,0.9 50 | module.Mixed_6c.branch_pool.conv.weight element 0.5,0.7 51 | module.Mixed_6d.branch1x1.conv.weight element 0.5,0.7 52 | module.Mixed_6d.branch7x7_1.conv.weight element 0.7,0.8 53 | module.Mixed_6d.branch7x7_2.conv.weight element 0.8,0.9 54 | module.Mixed_6d.branch7x7_3.conv.weight element 0.7,0.9 55 | module.Mixed_6d.branch7x7dbl_1.conv.weight element 0.6,0.8 56 | module.Mixed_6d.branch7x7dbl_2.conv.weight element 0.7,0.9 57 | module.Mixed_6d.branch7x7dbl_3.conv.weight element 0.7,0.8 58 | module.Mixed_6d.branch7x7dbl_4.conv.weight element 0.6,0.8 59 | module.Mixed_6d.branch7x7dbl_5.conv.weight element 0.6,0.8 60 | module.Mixed_6d.branch_pool.conv.weight element 0.5,0.7 61 | module.Mixed_6e.branch1x1.conv.weight element 0.5,0.8 62 | module.Mixed_6e.branch7x7_1.conv.weight element 0.5,0.8 63 | module.Mixed_6e.branch7x7_2.conv.weight element 0.7,0.9 64 | module.Mixed_6e.branch7x7_3.conv.weight element 0.6,0.8 65 | module.Mixed_6e.branch7x7dbl_1.conv.weight element 0.6,0.8 66 | module.Mixed_6e.branch7x7dbl_2.conv.weight element 0.6,0.8 67 | module.Mixed_6e.branch7x7dbl_3.conv.weight element 0.6,0.8 68 | module.Mixed_6e.branch7x7dbl_4.conv.weight element 0.6,0.8 69 | module.Mixed_6e.branch7x7dbl_5.conv.weight element 0.6,0.7 70 | module.Mixed_6e.branch_pool.conv.weight element 0.5,0.7 71 | module.Mixed_7a.branch3x3_1.conv.weight element 0.5,0.8 72 | module.Mixed_7a.branch3x3_2.conv.weight element 0.7,0.8 73 | module.Mixed_7a.branch7x7x3_1.conv.weight element 0.6,0.8 74 | module.Mixed_7a.branch7x7x3_2.conv.weight element 0.7,0.9 75 | module.Mixed_7a.branch7x7x3_3.conv.weight element 0.7,0.9 76 | module.Mixed_7a.branch7x7x3_4.conv.weight element 0.8,0.9 77 | module.Mixed_7b.branch1x1.conv.weight element 0.6,0.8 78 | module.Mixed_7b.branch3x3_1.conv.weight element 0.6,0.7 79 | module.Mixed_7b.branch3x3_2a.conv.weight element 0.6,0.8 80 | module.Mixed_7b.branch3x3_2b.conv.weight element 0.7,0.8 81 | module.Mixed_7b.branch3x3dbl_1.conv.weight element 0.5,0.7 82 | module.Mixed_7b.branch3x3dbl_2.conv.weight element 0.6,0.7 83 | module.Mixed_7b.branch3x3dbl_3a.conv.weight element 0.5,0.7 84 | module.Mixed_7b.branch3x3dbl_3b.conv.weight element 0.5,0.7 85 | module.Mixed_7b.branch_pool.conv.weight element 0.5,0.8 86 | module.Mixed_7c.branch1x1.conv.weight element 0.9,0.9 87 | module.Mixed_7c.branch3x3_1.conv.weight element 0.5,0.7 88 | module.Mixed_7c.branch3x3_2a.conv.weight element 0.9,0.9 89 | module.Mixed_7c.branch3x3_2b.conv.weight element 0.9,0.9 90 | module.Mixed_7c.branch3x3dbl_1.conv.weight element 0.4,0.7 91 | module.Mixed_7c.branch3x3dbl_2.conv.weight element 0.7,0.8 92 | module.Mixed_7c.branch3x3dbl_3a.conv.weight element 0.6,0.8 93 | module.Mixed_7c.branch3x3dbl_3b.conv.weight element 0.6,0.8 94 | module.Mixed_7c.branch_pool.conv.weight element 0.8,0.9 95 | module.fc.weight element 0.6,0.8 96 | -------------------------------------------------------------------------------- /examples/deep_compression/rules/inception_v3/quantize.rule: -------------------------------------------------------------------------------- 1 | module.Conv2d_1a_3x3.conv.weight k-means 6 k-means++ 2 | module.Conv2d_2a_3x3.conv.weight k-means 6 k-means++ 3 | module.Conv2d_2b_3x3.conv.weight k-means 6 k-means++ 4 | module.Conv2d_3b_1x1.conv.weight k-means 6 k-means++ 5 | module.Conv2d_4a_3x3.conv.weight k-means 6 k-means++ 6 | module.Mixed_5b.branch1x1.conv.weight k-means 6 k-means++ 7 | module.Mixed_5b.branch5x5_1.conv.weight k-means 4 k-means++ 8 | module.Mixed_5b.branch5x5_2.conv.weight k-means 4 k-means++ 9 | module.Mixed_5b.branch3x3dbl_1.conv.weight k-means 4 k-means++ 10 | module.Mixed_5b.branch3x3dbl_2.conv.weight k-means 4 k-means++ 11 | module.Mixed_5b.branch3x3dbl_3.conv.weight k-means 4 k-means++ 12 | module.Mixed_5b.branch_pool.conv.weight k-means 6 k-means++ 13 | module.Mixed_5c.branch1x1.conv.weight k-means 6 k-means++ 14 | module.Mixed_5c.branch5x5_1.conv.weight k-means 4 k-means++ 15 | module.Mixed_5c.branch5x5_2.conv.weight k-means 4 k-means++ 16 | module.Mixed_5c.branch3x3dbl_1.conv.weight k-means 4 k-means++ 17 | module.Mixed_5c.branch3x3dbl_2.conv.weight k-means 4 k-means++ 18 | module.Mixed_5c.branch3x3dbl_3.conv.weight k-means 4 k-means++ 19 | module.Mixed_5c.branch_pool.conv.weight k-means 4 k-means++ 20 | module.Mixed_5d.branch1x1.conv.weight k-means 6 k-means++ 21 | module.Mixed_5d.branch5x5_1.conv.weight k-means 4 k-means++ 22 | module.Mixed_5d.branch5x5_2.conv.weight k-means 4 k-means++ 23 | module.Mixed_5d.branch3x3dbl_1.conv.weight k-means 4 k-means++ 24 | module.Mixed_5d.branch3x3dbl_2.conv.weight k-means 4 k-means++ 25 | module.Mixed_5d.branch3x3dbl_3.conv.weight k-means 4 k-means++ 26 | module.Mixed_5d.branch_pool.conv.weight k-means 4 k-means++ 27 | module.Mixed_6a.branch3x3.conv.weight k-means 4 k-means++ 28 | module.Mixed_6a.branch3x3dbl_1.conv.weight k-means 4 k-means++ 29 | module.Mixed_6a.branch3x3dbl_2.conv.weight k-means 4 k-means++ 30 | module.Mixed_6a.branch3x3dbl_3.conv.weight k-means 4 k-means++ 31 | module.Mixed_6b.branch1x1.conv.weight k-means 6 k-means++ 32 | module.Mixed_6b.branch7x7_1.conv.weight k-means 4 k-means++ 33 | module.Mixed_6b.branch7x7_2.conv.weight k-means 4 k-means++ 34 | module.Mixed_6b.branch7x7_3.conv.weight k-means 4 k-means++ 35 | module.Mixed_6b.branch7x7dbl_1.conv.weight k-means 4 k-means++ 36 | module.Mixed_6b.branch7x7dbl_2.conv.weight k-means 4 k-means++ 37 | module.Mixed_6b.branch7x7dbl_3.conv.weight k-means 4 k-means++ 38 | module.Mixed_6b.branch7x7dbl_4.conv.weight k-means 4 k-means++ 39 | module.Mixed_6b.branch7x7dbl_5.conv.weight k-means 4 k-means++ 40 | module.Mixed_6b.branch_pool.conv.weight k-means 6 k-means++ 41 | module.Mixed_6c.branch1x1.conv.weight k-means 4 k-means++ 42 | module.Mixed_6c.branch7x7_1.conv.weight k-means 4 k-means++ 43 | module.Mixed_6c.branch7x7_2.conv.weight k-means 4 k-means++ 44 | module.Mixed_6c.branch7x7_3.conv.weight k-means 4 k-means++ 45 | module.Mixed_6c.branch7x7dbl_1.conv.weight k-means 4 k-means++ 46 | module.Mixed_6c.branch7x7dbl_2.conv.weight k-means 4 k-means++ 47 | module.Mixed_6c.branch7x7dbl_3.conv.weight k-means 4 k-means++ 48 | module.Mixed_6c.branch7x7dbl_4.conv.weight k-means 4 k-means++ 49 | module.Mixed_6c.branch7x7dbl_5.conv.weight k-means 4 k-means++ 50 | module.Mixed_6c.branch_pool.conv.weight k-means 4 k-means++ 51 | module.Mixed_6d.branch1x1.conv.weight k-means 4 k-means++ 52 | module.Mixed_6d.branch7x7_1.conv.weight k-means 4 k-means++ 53 | module.Mixed_6d.branch7x7_2.conv.weight k-means 4 k-means++ 54 | module.Mixed_6d.branch7x7_3.conv.weight k-means 4 k-means++ 55 | module.Mixed_6d.branch7x7dbl_1.conv.weight k-means 4 k-means++ 56 | module.Mixed_6d.branch7x7dbl_2.conv.weight k-means 4 k-means++ 57 | module.Mixed_6d.branch7x7dbl_3.conv.weight k-means 4 k-means++ 58 | module.Mixed_6d.branch7x7dbl_4.conv.weight k-means 4 k-means++ 59 | module.Mixed_6d.branch7x7dbl_5.conv.weight k-means 4 k-means++ 60 | module.Mixed_6d.branch_pool.conv.weight k-means 4 k-means++ 61 | module.Mixed_6e.branch1x1.conv.weight k-means 4 k-means++ 62 | module.Mixed_6e.branch7x7_1.conv.weight k-means 4 k-means++ 63 | module.Mixed_6e.branch7x7_2.conv.weight k-means 4 k-means++ 64 | module.Mixed_6e.branch7x7_3.conv.weight k-means 4 k-means++ 65 | module.Mixed_6e.branch7x7dbl_1.conv.weight k-means 4 k-means++ 66 | module.Mixed_6e.branch7x7dbl_2.conv.weight k-means 4 k-means++ 67 | module.Mixed_6e.branch7x7dbl_3.conv.weight k-means 4 k-means++ 68 | module.Mixed_6e.branch7x7dbl_4.conv.weight k-means 4 k-means++ 69 | module.Mixed_6e.branch7x7dbl_5.conv.weight k-means 4 k-means++ 70 | module.Mixed_6e.branch_pool.conv.weight k-means 4 k-means++ 71 | module.Mixed_7a.branch3x3_1.conv.weight k-means 4 k-means++ 72 | module.Mixed_7a.branch3x3_2.conv.weight k-means 4 k-means++ 73 | module.Mixed_7a.branch7x7x3_1.conv.weight k-means 4 k-means++ 74 | module.Mixed_7a.branch7x7x3_2.conv.weight k-means 4 k-means++ 75 | module.Mixed_7a.branch7x7x3_3.conv.weight k-means 4 k-means++ 76 | module.Mixed_7a.branch7x7x3_4.conv.weight k-means 4 k-means++ 77 | module.Mixed_7b.branch1x1.conv.weight k-means 4 k-means++ 78 | module.Mixed_7b.branch3x3_1.conv.weight k-means 4 k-means++ 79 | module.Mixed_7b.branch3x3_2a.conv.weight k-means 4 k-means++ 80 | module.Mixed_7b.branch3x3_2b.conv.weight k-means 4 k-means++ 81 | module.Mixed_7b.branch3x3dbl_1.conv.weight k-means 4 k-means++ 82 | module.Mixed_7b.branch3x3dbl_2.conv.weight k-means 4 k-means++ 83 | module.Mixed_7b.branch3x3dbl_3a.conv.weight k-means 4 k-means++ 84 | module.Mixed_7b.branch3x3dbl_3b.conv.weight k-means 4 k-means++ 85 | module.Mixed_7b.branch_pool.conv.weight k-means 4 k-means++ 86 | module.Mixed_7c.branch1x1.conv.weight k-means 4 k-means++ 87 | module.Mixed_7c.branch3x3_1.conv.weight k-means 4 k-means++ 88 | module.Mixed_7c.branch3x3_2a.conv.weight k-means 4 k-means++ 89 | module.Mixed_7c.branch3x3_2b.conv.weight k-means 4 k-means++ 90 | module.Mixed_7c.branch3x3dbl_1.conv.weight k-means 4 k-means++ 91 | module.Mixed_7c.branch3x3dbl_2.conv.weight k-means 4 k-means++ 92 | module.Mixed_7c.branch3x3dbl_3a.conv.weight k-means 4 k-means++ 93 | module.Mixed_7c.branch3x3dbl_3b.conv.weight k-means 4 k-means++ 94 | module.Mixed_7c.branch_pool.conv.weight k-means 4 k-means++ 95 | module.fc.weight k-means 4 k-means++ 96 | -------------------------------------------------------------------------------- /examples/deep_compression/rules/resnet50/coding.rule: -------------------------------------------------------------------------------- 1 | (layer[0-5\.]+)*(conv[1-3]|downsample\.0)\.weight huffman 0 0 4 2 | fc\.weight huffman 0 0 4 3 | -------------------------------------------------------------------------------- /examples/deep_compression/rules/resnet50/prune_manual.rule: -------------------------------------------------------------------------------- 1 | module\.conv1\.weight element 0.4,0.4,0.5 2 | module\.layer[1-3]\.0\.conv1\.weight element 0.5,0.5,0.6 3 | module\.layer1\.0\.downsample\.0\.weight element 0.5,0.5,0.6 4 | module\.layer2\.0\.conv2\.weight element 0.5,0.6,0.667 5 | module\.layer4\.[0-9a-z\.]+ 0.5,0.667,0.7 6 | module\.layer[0-5\.]+conv[1-3]\.weight element 0.5,0.7 7 | module\.layer[0-4\.]+downsample\.0\.weight element 0.5,0.7 8 | module\.fc.weight element 0.5,0.75,0.8 9 | -------------------------------------------------------------------------------- /examples/deep_compression/rules/resnet50/quantize.rule: -------------------------------------------------------------------------------- 1 | module\.layer[1-3]\.0\.conv1\.weight k-means 6 k-means++ 2 | module\.layer1\.0\.downsample\.0\.weight k-means 6 k-means++ 3 | module\.layer2\.0\.conv2\.weight kmeans 6 k-means++ 4 | module\.layer4\.[0-9a-z\.]+ k-means 4 k-means++ 5 | module\.layer[0-5\.]+conv[1-3]\.weight k-means 4 k-means++ 6 | module\.layer[0-4\.]+downsample\.0\.weight k-means 4 k-means++ 7 | module\.fc.weight k-means 4 k-means++ 8 | -------------------------------------------------------------------------------- /examples/deep_compression/sensitivity_scan.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import datetime 3 | import os 4 | 5 | import numpy as np 6 | import torch 7 | import torch.backends.cudnn as cudnn 8 | import torch.nn.parallel 9 | import torch.utils.data 10 | import torchvision.datasets as datasets 11 | import torchvision.models as models 12 | import torchvision.transforms as transforms 13 | 14 | from slender.prune import prune_vanilla_elementwise 15 | from slender.utils import get_sparsity, AverageMeter, Logger 16 | 17 | model_names = sorted(name for name in models.__dict__ 18 | if name.islower() and not name.startswith("__") 19 | and callable(models.__dict__[name])) 20 | 21 | parser = argparse.ArgumentParser(description='PyTorch Pruning Sensitivity Scan') 22 | parser.add_argument('data', metavar='DIR', 23 | help='path to dataset') 24 | parser.add_argument('--arch', '-a', metavar='ARCH', default='resnet50', 25 | choices=model_names, 26 | help='model architecture: ' + 27 | ' | '.join(model_names) + 28 | ' (default: resnet50)') 29 | parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', 30 | help='number of data loading workers (default: 4)') 31 | parser.add_argument('--nGPU', type=int, default=4, 32 | help='the number of gpus for training') 33 | parser.add_argument('-b', '--batch-size', default=256, type=int, 34 | metavar='N', help='mini-batch size (default: 256)') 35 | 36 | parser.add_argument('--pretrained', default='', type=str, metavar='PATH', 37 | help='use pre-trained model: ' 38 | 'pytorch: use pytorch official | ' 39 | 'path to self-trained moel') 40 | parser.add_argument('--pretrained-parallel', dest='pretrained_parallel', 41 | action='store_true', 42 | help='self-trained model starts with torch.nn.DataParallel') 43 | 44 | parser.add_argument('--relatively-prune', dest='relatively', action='store_true', 45 | help='relatively prune') 46 | 47 | 48 | def main(): 49 | global scan_log, rule_log 50 | args = parser.parse_args() 51 | 52 | dir_name = args.arch + '_' + datetime.datetime.now().strftime('%m%d_%H%M') 53 | log_dir = os.path.join('logs', os.path.join('scan', dir_name)) 54 | os.makedirs(log_dir) 55 | scan_log = Logger(os.path.join(log_dir, 'scan.log')) 56 | rule_log = Logger(os.path.join(log_dir, 'recommend.rule')) 57 | 58 | # create model 59 | print("=> creating model '{}'".format(args.arch)) 60 | 61 | if args.pretrained == 'pytorch': 62 | print("=> using pre-trained model from pytorch model zoo") 63 | model = models.__dict__[args.arch](pretrained=True) 64 | args.pretrained_parallel = False 65 | else: 66 | if args.arch.startswith('inception'): 67 | model = models.__dict__[args.arch](transform_input=True) 68 | else: 69 | model = models.__dict__[args.arch]() 70 | if args.pretrained and not args.pretrained_parallel: 71 | if os.path.isfile(args.pretrained): 72 | print("=> using pre-trained model '{}'".format(args.pretrained)) 73 | checkpoint = torch.load(args.pretrained) 74 | model.load_state_dict(checkpoint['state_dict']) 75 | else: 76 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 77 | 78 | if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): 79 | model.features = torch.nn.DataParallel(model.features, device_ids=list(range(args.nGPU))) 80 | model.cuda() 81 | else: 82 | model = torch.nn.DataParallel(model, device_ids=list(range(args.nGPU))).cuda() 83 | 84 | if args.pretrained and args.pretrained_parallel: 85 | if os.path.isfile(args.pretrained): 86 | print("=> loading checkpoint '{}'".format(args.pretrained)) 87 | checkpoint = torch.load(args.pretrained) 88 | model.load_state_dict(checkpoint['state_dict']) 89 | print("=> loaded checkpoint") 90 | else: 91 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 92 | 93 | cudnn.benchmark = True 94 | 95 | # Data loading code 96 | valdir = os.path.join(args.data, 'val') 97 | normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 98 | std=[0.229, 0.224, 0.225]) 99 | 100 | if args.arch.startswith('inception'): 101 | input_size = 299 102 | else: 103 | input_size = 224 104 | 105 | val_loader = torch.utils.data.DataLoader( 106 | datasets.ImageFolder(valdir, transforms.Compose([ 107 | transforms.Scale(int(input_size / 0.875)), 108 | transforms.CenterCrop(input_size), 109 | transforms.ToTensor(), 110 | normalize, 111 | ])), 112 | batch_size=args.batch_size, shuffle=False, 113 | num_workers=args.workers, pin_memory=True) 114 | 115 | # test baseline top1 accuracy 116 | top1, _ = validate(val_loader=val_loader, model=model, sparsity=0) 117 | # sensitivity scan 118 | sensitivity_scan(model=model, val_loader=val_loader, relatively=args.relatively, top1=top1) 119 | 120 | scan_log.close() 121 | rule_log.close() 122 | 123 | 124 | def validate(val_loader, model, sparsity): 125 | top1 = AverageMeter() 126 | top5 = AverageMeter() 127 | 128 | # switch to evaluate mode 129 | model.eval() 130 | 131 | with torch.no_grad(): 132 | for i, (input, target) in enumerate(val_loader): 133 | target = target.cuda(non_blocking=True) 134 | 135 | # compute output 136 | output = model(input) 137 | 138 | # measure accuracy and record loss 139 | prec1, prec5 = accuracy(output, target, topk=(1, 5)) 140 | top1.update(prec1[0], input.size(0)) 141 | top5.update(prec5[0], input.size(0)) 142 | 143 | print(' * Sparsity: {spars:.2f} | Prec@1: {top1.avg:.3f} | Prec@5: {top5.avg:.3f}' 144 | .format(spars=sparsity, top1=top1, top5=top5)) 145 | 146 | return top1.avg, top5.avg 147 | 148 | 149 | def sensitivity_scan(model, val_loader, top1, relatively=False): 150 | c1 = 100 - (100-top1) * 1.01 151 | c5 = 100 - (100-top1) * 1.05 152 | for i, (param_name, param) in enumerate(model.named_parameters()): 153 | print("{:3d} -> {param_name:^30} -> {param_shape}" 154 | .format(i, param_name=param_name, param_shape=param.size())) 155 | scan_log.write(content="@Param: {param_name:^30}".format(param_name=param_name), wrap=True) 156 | if param.dim() > 1: 157 | p1s, p5s = 1.0, 1.0 158 | scan_log.write(content="------ scanning param ------", wrap=True, verbose=True) 159 | param_clone = param.data.clone() 160 | origin_sparsity = get_sparsity(param=param_clone) 161 | for sparsity in np.arange(start=0.1, stop=1.0, step=0.1): 162 | if relatively: 163 | sparsity *= origin_sparsity 164 | prune_vanilla_elementwise(sparsity=sparsity, param=param.data) 165 | top1, top5 = validate(val_loader=val_loader, model=model, sparsity=sparsity) 166 | scan_log.write(content="{spars:.3f}\t{top1:.3f}\t{top5:.5f}" 167 | .format(spars=sparsity, top1=top1, top5=top5), 168 | wrap=True) 169 | param.data.copy_(param_clone) 170 | if top1 > c5: 171 | p5s = min(p5s, sparsity) 172 | if top1 > c1: 173 | p1s = min(p1s, sparsity) 174 | break 175 | scan_log.flush() 176 | rule_log.write("{param_name} {stage_0:.5f},{stage_1:.5f}" 177 | .format(param_name=param_name, stage_0=p1s, stage_1=p5s), 178 | wrap=True, verbose=True, flush=True) 179 | else: 180 | scan_log.write("------ skipping param ------", wrap=True, verbose=True, flush=True) 181 | 182 | 183 | def accuracy(output, target, topk=(1,)): 184 | """Computes the precision@k for the specified values of k""" 185 | with torch.no_grad(): 186 | maxk = max(topk) 187 | batch_size = target.size(0) 188 | 189 | _, pred = output.topk(maxk, 1, True, True) 190 | pred = pred.t() 191 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 192 | 193 | res = [] 194 | for k in topk: 195 | correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) 196 | res.append(correct_k.mul_(100.0 / batch_size)) 197 | return res 198 | 199 | 200 | if __name__ == '__main__': 201 | main() 202 | -------------------------------------------------------------------------------- /slender/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synxlin/nn-compression/34918a4ed2bbe44a483a6e81a740ae5fe3ffc065/slender/__init__.py -------------------------------------------------------------------------------- /slender/coding/__init__.py: -------------------------------------------------------------------------------- 1 | from .codec import Codec 2 | -------------------------------------------------------------------------------- /slender/coding/codec.py: -------------------------------------------------------------------------------- 1 | import re 2 | import torch 3 | 4 | from .encode import EncodedParam, EncodedModule 5 | from ..utils import AverageMeter 6 | 7 | 8 | class Codec(object): 9 | def __init__(self, rule): 10 | """ 11 | Codec for coding 12 | :param rule: str, path to the rule file, each line formats 13 | 'param_name coding_method bit_length_fixed_point bit_length_fixed_point_of_integer_part 14 | bit_length_of_zero_run_length' 15 | list of tuple, 16 | [(param_name(str), coding_method(str), bit_length_fixed_point(int), 17 | bit_length_fixed_point_of_integer_part(int), bit_length_of_zero_run_length(int))] 18 | """ 19 | if isinstance(rule, str): 20 | content = map(lambda x: x.split(), open(rule).readlines()) 21 | content = filter(lambda x: len(x) == 5, content) 22 | rule = list(map(lambda x: (x[0], x[1], int(x[2]), int(x[3]), int(x[4])), content)) 23 | assert isinstance(rule, list) or isinstance(rule, tuple) 24 | self.rule = rule 25 | self.stats = { 26 | 'compression_ratio': { 27 | 'compressed': AverageMeter(), 28 | 'total': AverageMeter() 29 | }, 30 | 'memory_size': { 31 | 'codebook': AverageMeter(), 32 | 'param': AverageMeter(), 33 | 'compressed_param': AverageMeter(), 34 | 'index': AverageMeter(), 35 | 'total': AverageMeter() 36 | }, 37 | 'detail': dict() 38 | } 39 | 40 | print("=" * 89) 41 | print("Initializing Huffman Codec\n" 42 | "Rules\n" 43 | "{rule}".format(rule=self.rule)) 44 | print("=" * 89) 45 | 46 | def reset_stats(self): 47 | """ 48 | reset stats of codec 49 | :return: 50 | void 51 | """ 52 | self.stats['detail'] = dict() 53 | for _, v in self.stats['compression_ratio'].items(): 54 | v.reset() 55 | for _, v in self.stats['memory_size'].items(): 56 | v.reset() 57 | 58 | def encode_param(self, param, param_name): 59 | """ 60 | encode the parameters based on rule 61 | :param param: torch.(cuda.)tensor, parameter 62 | :param param_name: str, name of parameter 63 | :return: 64 | EncodedParam, encoded parameter 65 | """ 66 | rule_id = -1 67 | for idx, x in enumerate(self.rule): 68 | m = re.match(x[0], param_name) 69 | if m is not None and len(param_name) == m.span()[1]: 70 | rule_id = idx 71 | break 72 | if rule_id > -1: 73 | rule = self.rule[rule_id] 74 | encoded_param = EncodedParam(param, method=rule[1], 75 | bit_length=rule[2], bit_length_integer=rule[3], 76 | encode_indices=True, bit_length_zero_run_length=rule[4]) 77 | return encoded_param 78 | else: 79 | return None 80 | 81 | def encode(self, model): 82 | """ 83 | encode network based on rule 84 | :param model: torch.(cuda.)module, network model 85 | :return: 86 | EncodedModule, encoded model 87 | """ 88 | assert isinstance(model, torch.nn.Module) 89 | self.reset_stats() 90 | encoded_params = dict() 91 | print("=" * 89) 92 | print("Start Encoding") 93 | print("=" * 89) 94 | print("{:^30} | {:<25} | {:<25} | {:<25} | {:<25} | {:<25} | {:<25} | {:<25}". 95 | format('Param Name', 'Param Density', 'Param Bit', 'Index Bit', 'Param Mem', 96 | 'Index Mem', 'Codebook Mem', 'Compression Ratio')) 97 | for param_name, param in model.named_parameters(): 98 | if 'AuxLogits' in param_name: 99 | # deal with googlenet 100 | continue 101 | encoded_param = self.encode_param(param=param.data, param_name=param_name) 102 | if encoded_param is not None: 103 | # check encoded result 104 | assert torch.equal(param.data, encoded_param.data) 105 | stats = encoded_param.stats 106 | print("{param_name:^30} | {density:<25} | {bit_param:<25} | {bit_index:<25} | " 107 | "{mem_param:<25} | {mem_index:<25} | {mem_codebook:<25} | {compression_ratio:<25}" 108 | .format(param_name=param_name, density=stats['num_nz'] / stats['num_el'], 109 | bit_param=stats['bit_length']['param'], bit_index=stats['bit_length']['index'], 110 | mem_param=stats['memory_size']['param'], mem_index=stats['memory_size']['index'], 111 | mem_codebook=stats['memory_size']['codebook'], 112 | compression_ratio=stats['compression_ratio'])) 113 | encoded_params[param_name] = encoded_param 114 | # statistics 115 | self.stats['compression_ratio']['compressed'].accumulate(stats['num_el'] * 32, 116 | stats['memory_size']['total']) 117 | self.stats['compression_ratio']['total'].accumulate(stats['num_el'] * 32, 118 | stats['memory_size']['total']) 119 | self.stats['memory_size']['codebook'].accumulate(stats['memory_size']['codebook']) 120 | self.stats['memory_size']['param'].accumulate(stats['memory_size']['param']) 121 | self.stats['memory_size']['index'].accumulate(stats['memory_size']['index']) 122 | self.stats['memory_size']['compressed_param'].accumulate(stats['memory_size']['param']) 123 | self.stats['detail'][param_name] = stats 124 | else: 125 | print("{:^30} | skipping".format(param_name)) 126 | memory_size_param = param.data.numel() * 32 127 | self.stats['compression_ratio']['total'].accumulate(memory_size_param, memory_size_param) 128 | self.stats['memory_size']['param'].accumulate(memory_size_param) 129 | print("=" * 89) 130 | print("Stop Encoding") 131 | print("=" * 89) 132 | print("Compress Ratio | {}\n" 133 | "Overall Compress Ratio | {}\n" 134 | "Codebook Memory Size | {:.3f} KB\n" 135 | "Compressed Param Memory Size | {:.3f} KB\n" 136 | "Index Memory Size | {:.3f} KB\n" 137 | "Overall Param Memory Size | {:.3f} KB" 138 | .format(self.stats['compression_ratio']['compressed'].avg, 139 | self.stats['compression_ratio']['total'].avg, 140 | self.stats['memory_size']['codebook'].sum / 8 / 1024, 141 | self.stats['memory_size']['compressed_param'].sum / 8 / 1024, 142 | self.stats['memory_size']['index'].sum / 8 / 1024, 143 | self.stats['memory_size']['param'].sum / 8 / 1024)) 144 | print("=" * 89) 145 | return EncodedModule(module=model, encoded_param=encoded_params) 146 | 147 | @staticmethod 148 | def decode(model, state_dict): 149 | """ 150 | decode the network using state dict from EncodedModule 151 | :param model: torch.nn.module, network model 152 | :param state_dict: state dict from EncodedModule 153 | :return: 154 | torch.nn.module, decoded network 155 | """ 156 | assert isinstance(model, torch.nn.Module) 157 | print("=" * 89) 158 | print("Start Decoding") 159 | for param_name, param in model.named_parameters(): 160 | if 'AuxLogits' in param_name: 161 | # deal with googlenet 162 | state_dict[param_name] = param.data 163 | elif param_name in state_dict and isinstance(state_dict[param_name], dict): 164 | print("Decoding {}".format(param_name)) 165 | encoded_param = EncodedParam() 166 | encoded_param.load_state_dict(state_dict[param_name]) 167 | state_dict[param_name] = encoded_param.data 168 | model.load_state_dict(state_dict) 169 | print("Stop Decoding") 170 | print("=" * 89) 171 | return model 172 | -------------------------------------------------------------------------------- /slender/coding/encode.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch 3 | import multiprocessing 4 | from collections import Counter 5 | from heapq import heappush, heappop, heapify 6 | from bitarray import bitarray 7 | from itertools import repeat 8 | 9 | from ..replicate import replicate 10 | from ..utils import iter_str_every 11 | 12 | 13 | def get_huffman_codebook(symb2freq): 14 | """ 15 | Huffman encode the given dict mapping symbols to weights 16 | :param symb2freq: dict, {symbol: frequency} 17 | :return: 18 | dict, value(float/int) : code(bitarray) 19 | """ 20 | heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()] 21 | heapify(heap) 22 | while len(heap) > 1: 23 | lo = heappop(heap) 24 | hi = heappop(heap) 25 | for pair in lo[1:]: 26 | pair[1] = '0' + pair[1] 27 | for pair in hi[1:]: 28 | pair[1] = '1' + pair[1] 29 | heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:]) 30 | codebook = sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p)) 31 | return dict(map(lambda x: (x[0], bitarray(x[1])), codebook)) 32 | 33 | 34 | def get_vanilla_codebook(symb): 35 | codebook = dict() 36 | symb = set(symb) 37 | bit_length = int(math.ceil(math.log(len(symb), 2))) 38 | bit_format = '{:0%db}' % bit_length 39 | for i, s in enumerate(symb): 40 | codebook[s] = bitarray(bit_format.format(i)) 41 | return codebook 42 | 43 | 44 | def _encode_positive_integer(args): 45 | """ 46 | 47 | :param args[0]: x: int 48 | :param args[1]: bit_length: int, bit length of fixed point x, 49 | including sign bit 50 | :return: 51 | str, 52 | """ 53 | bit_format = '{:0%db}' % args[1] 54 | return bit_format.format(args[0]) 55 | 56 | 57 | def _encode_float(args): 58 | """ 59 | 60 | :param args[0]: x: int or float 61 | :param args[1]: bit_length: int, bit length of fixed point x, 62 | including sign bit 63 | :param args[2]: bit_length_integer: int, bit length of integer part 64 | of fixed point x 65 | :return: 66 | str, 67 | """ 68 | bit_format = '{:0%db}' % args[1] 69 | mul_coeff = 2 ** (args[1] - args[2] - 1) 70 | add_coeff = 2 ** args[1] 71 | return bit_format.format(int(math.floor(args[0] * mul_coeff)) + add_coeff)[-args[1]:] 72 | 73 | 74 | def _decode_positive_integer(bits): 75 | """ 76 | 77 | :param bits: 78 | :return: 79 | """ 80 | return int(bits, 2) 81 | 82 | 83 | def _decode_float(args): 84 | """ 85 | 86 | :param args[0]: bits: 87 | :param args[1]: bit_length: 88 | :param args[2]: bit_length_integer: 89 | :return: 90 | """ 91 | div_coeff = 2 ** (args[2] - args[1] + 1) 92 | max_coeff = 2 ** (args[1] - 1) 93 | sub_coeff = 2 * max_coeff 94 | 95 | num = int(args[0], 2) 96 | if num >= max_coeff: 97 | num -= sub_coeff 98 | num *= div_coeff 99 | return num 100 | 101 | 102 | class EncodedParam(object): 103 | 104 | def __init__(self, param=None, method='huffman', 105 | bit_length=8, bit_length_integer=0, 106 | encode_indices=False, bit_length_zero_run_length=4): 107 | """ 108 | EncodedParam class 109 | :param param: torch.(cuda.)tensor, default=None 110 | :param method: str, coding method, 111 | choose from ['vanilla', 'fixed_point', 'huffman'] 112 | :param bit_length: int, bit length of fixed point param, 113 | including sign bit, default=8 114 | :param bit_length_integer: int, bit length of integer part 115 | of fixed point param, default=0 116 | :param encode_indices: bool, whether to encode zero run length, default=False 117 | :param bit_length_zero_run_length: int, bit length of zero run length 118 | without sign bit 119 | since run length is non-negative 120 | """ 121 | assert method in ['vanilla', 'fixed_point', 'huffman'] 122 | if bit_length <= 0: 123 | bit_length = 0 124 | bit_length_integer = 0 125 | if method == 'fixed_point': 126 | method = 'vanilla' 127 | if bit_length_integer < 0 or method != 'fixed_point': 128 | bit_length_integer = 0 129 | self.method = method 130 | self.bit_length = bit_length 131 | self.bit_length_integer = bit_length_integer 132 | if bit_length_zero_run_length <= 0: 133 | encode_indices = False 134 | bit_length_zero_run_length = 0 135 | self.max_bit_length_zero_run_length = bit_length_zero_run_length 136 | self.encode_indices = encode_indices 137 | self.max_zero_run_length = max_zero_run_length = 2 ** bit_length_zero_run_length - 2 138 | 139 | self.bit_stream = {'param': None, 'index': None} 140 | self.codebook = None 141 | 142 | if torch.is_tensor(param): 143 | self.num_el = num_el = param.numel() 144 | self.num_nz = self.num_el 145 | self.shape = param.size() 146 | num_cpu = multiprocessing.cpu_count() 147 | if encode_indices: 148 | param = param.view(num_el) 149 | nonzero_indices = param.nonzero() 150 | self.num_nz = nonzero_indices.numel() 151 | nonzero_indices, _ = torch.sort(nonzero_indices.view(self.num_nz)) 152 | nonzero_indices[1:] -= (nonzero_indices[:-1] + 1) 153 | run_length = nonzero_indices.cpu().tolist() 154 | num_chunks = 0 155 | run_length_chunks = [] 156 | for rl in run_length: 157 | if rl <= max_zero_run_length: 158 | run_length_chunks.append(rl) 159 | else: 160 | left_rl = rl 161 | while left_rl > max_zero_run_length: 162 | run_length_chunks.append(max_zero_run_length + 1) 163 | left_rl -= max_zero_run_length 164 | num_chunks += 1 165 | run_length_chunks.append(left_rl) 166 | # encode indices (fixed point) 167 | # bit_format = '{:0%db}' % bit_length_zero_run_length 168 | # parallel encode 169 | pool = multiprocessing.Pool(processes=num_cpu) 170 | bit_stream_index = ''.join(pool.map(_encode_positive_integer, 171 | zip(run_length_chunks, 172 | repeat(bit_length_zero_run_length)))) 173 | pool.close() 174 | self.bit_stream['index'] = bitarray(bit_stream_index) 175 | param = param[param != 0] 176 | else: 177 | self.bit_stream['index'] = bitarray() 178 | param = param.view(num_el) 179 | # get param codebook 180 | param_list = param.cpu().tolist() 181 | if self.method == 'huffman': 182 | symb2freq = Counter(param_list) 183 | self.codebook = get_huffman_codebook(symb2freq) 184 | # encode param 185 | self.bit_stream['param'] = bitarray() 186 | self.bit_stream['param'].encode(self.codebook, param_list) 187 | elif self.method == 'vanilla': 188 | symb = set(param_list) 189 | self.codebook = get_vanilla_codebook(symb) 190 | # encode param 191 | self.bit_stream['param'] = bitarray() 192 | self.bit_stream['param'].encode(self.codebook, param_list) 193 | else: # fixed point 194 | # bit_format = '{:0%db}' % self.bit_length 195 | # mul_coeff = 2 ** (self.bit_length - self.bit_length_integer - 1) 196 | # add_coeff = 2 ** self.bit_length 197 | # bit_stream = ''.join(map(lambda x: bit_format 198 | # .format(int(math.floor(x * mul_coeff)) + add_coeff)[-self.bit_length:], 199 | # param_list)) 200 | # parallel encode 201 | pool = multiprocessing.Pool(processes=num_cpu) 202 | bit_stream = ''.join(pool.map(_encode_float, 203 | zip(param_list, repeat(bit_length), 204 | repeat(bit_length_integer)))) 205 | pool.close() 206 | self.bit_stream['param'] = bitarray(bit_stream) 207 | else: 208 | self.num_el = 0 209 | self.num_nz = 0 210 | self.shape = None 211 | 212 | @property 213 | def memory_size(self): 214 | """ 215 | memory size in bit (total bit length) after encoding 216 | :return: 217 | int, bit length after encoding 218 | """ 219 | if self.codebook is None: 220 | return len(self.bit_stream['param']) + len(self.bit_stream['index']) 221 | else: 222 | return 32 * len(self.codebook) + \ 223 | sum(map(lambda v: len(v), self.codebook.values())) + \ 224 | len(self.bit_stream['param']) + len(self.bit_stream['index']) 225 | 226 | @property 227 | def stats(self): 228 | """ 229 | stats of encoding 230 | :return: 231 | dict, containing info of memory_size of codebook/param/index, compression ratio, num_el and shape 232 | """ 233 | stats = dict() 234 | stats['memory_size'] = dict() 235 | stats['bit_length'] = dict() 236 | 237 | if self.codebook is None: 238 | stats['memory_size']['codebook'] = 0 239 | stats['bit_length']['codebook'] = 0 240 | else: 241 | stats['bit_length']['codebook'] = sum(map(lambda v: len(v), self.codebook.values())) 242 | stats['memory_size']['codebook'] = 32 * len(self.codebook) + stats['bit_length']['codebook'] 243 | stats['bit_length']['codebook'] /= len(self.codebook) 244 | 245 | stats['memory_size']['param'] = len(self.bit_stream['param']) 246 | stats['bit_length']['param'] = stats['memory_size']['param'] / self.num_nz 247 | 248 | stats['memory_size']['index'] = len(self.bit_stream['index']) 249 | stats['bit_length']['index'] = stats['memory_size']['index'] / self.num_nz 250 | 251 | stats['memory_size']['total'] = stats['memory_size']['codebook'] + stats['memory_size']['param'] + \ 252 | stats['memory_size']['index'] 253 | stats['compression_ratio'] = (32 * self.num_el) / stats['memory_size']['total'] 254 | 255 | stats['num_el'] = self.num_el 256 | stats['num_nz'] = self.num_nz 257 | stats['shape'] = self.shape 258 | return stats 259 | 260 | @property 261 | def data(self): 262 | """ 263 | returns decoded param 264 | :return: torch.tensor, param 265 | """ 266 | if self.codebook is None: 267 | bit_stream = self.bit_stream['param'].to01() 268 | bit_length = self.bit_length 269 | bit_length_integer = self.bit_length_integer 270 | 271 | # div_coeff = 2 ** (self.bit_length_integer - bit_length + 1) 272 | # max_coeff = 2 ** (bit_length - 1) 273 | # sub_coeff = 2 * max_coeff 274 | # param_list = [] 275 | # for i in range(0, len(bit_stream), bit_length): 276 | # bits = bit_stream[i:(i + bit_length)] 277 | # num = int(bits, 2) 278 | # if num >= max_coeff: 279 | # num -= sub_coeff 280 | # num *= div_coeff 281 | # param_list.append(num) 282 | 283 | pool = multiprocessing.Pool(processes=multiprocessing.cpu_count()) 284 | param_list = list(pool.map(_decode_float, 285 | zip(iter_str_every(bit_stream, bit_length), 286 | repeat(bit_length), repeat(bit_length_integer)))) 287 | pool.close() 288 | else: 289 | param_list = self.bit_stream['param'].decode(self.codebook) 290 | 291 | if self.encode_indices: 292 | param_nz_list = param_list 293 | bit_stream = self.bit_stream['index'].to01() 294 | param_list = [] 295 | nz_idx = 0 296 | for i in range(0, len(bit_stream), self.max_bit_length_zero_run_length): 297 | bits = bit_stream[i:(i+self.max_bit_length_zero_run_length)] 298 | run_length = int(bits, 2) 299 | if run_length > self.max_zero_run_length: 300 | param_list.extend([0] * self.max_zero_run_length) 301 | else: 302 | param_list.extend([0] * run_length) 303 | param_list.append(param_nz_list[nz_idx]) 304 | nz_idx += 1 305 | param_list.extend([0] * (self.num_el - len(param_list))) 306 | 307 | return torch.tensor(param_list).view(self.shape) 308 | 309 | def state_dict(self): 310 | """ 311 | Returns a dictionary containing a whole state of the EncodedParam 312 | :return: dict, a dictionary containing a whole state of the EncodedParam 313 | """ 314 | state_dict = dict() 315 | state_dict['method'] = self.method 316 | state_dict['bit_length'] = self.bit_length 317 | state_dict['bit_length_integer'] = self.bit_length_integer 318 | state_dict['encode_indices'] = self.encode_indices 319 | state_dict['max_bit_length_zero_run_length'] = self.max_bit_length_zero_run_length 320 | state_dict['max_zero_run_length'] = self.max_zero_run_length 321 | state_dict['num_el'] = self.num_el 322 | state_dict['num_nz'] = self.num_nz 323 | state_dict['shape'] = self.shape 324 | state_dict['bit_stream'] = self.bit_stream 325 | state_dict['codebook'] = self.codebook 326 | return state_dict 327 | 328 | def load_state_dict(self, state_dict): 329 | """ 330 | Recover EncodedParam 331 | :param state_dict: dict, a dictionary containing a whole state of the EncodedParam 332 | :return: EncodedParam 333 | """ 334 | for k, v in state_dict.items(): 335 | self.__setattr__(k, v) 336 | 337 | 338 | class EncodedModule(object): 339 | 340 | def __init__(self, module, encoded_param): 341 | """ 342 | Encoded Module class 343 | :param module: torch.nn.Module, network model or nn module 344 | :param encoded_param: dict, {param name(str): encoded parameters(dict, EncodedParam.state_dict())} 345 | """ 346 | assert isinstance(module, torch.nn.Module) 347 | assert isinstance(encoded_param, dict) 348 | self.module = replicate(module) 349 | self.encoded_param = encoded_param 350 | 351 | for param_name, param in self.module.named_parameters(): 352 | if 'AuxLogits' in param_name or param_name in self.encoded_param: 353 | param.data.set_() 354 | 355 | def state_dict(self): 356 | """ 357 | Returns a dictionary containing a whole state of the encoded module 358 | :return: dict, a dictionary containing a whole state of the encoded module 359 | """ 360 | state_dict = self.module.state_dict() 361 | for param_name, param in self.encoded_param.items(): 362 | state_dict[param_name] = param.state_dict() 363 | return state_dict 364 | -------------------------------------------------------------------------------- /slender/prune/__init__.py: -------------------------------------------------------------------------------- 1 | from .vanilla import VanillaPruner 2 | from .channel import * 3 | -------------------------------------------------------------------------------- /slender/prune/channel.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | import torch 4 | from sklearn.linear_model import Lasso 5 | 6 | 7 | num_pruned_tolerate_coeff = 1.1 8 | 9 | 10 | def channel_selection(sparsity, output_feature, fn_next_output_feature, method='greedy'): 11 | """ 12 | select channel to prune with a given metric 13 | :param sparsity: float, pruning sparsity 14 | :param output_feature: torch.(cuda.)Tensor, output feature map of the layer being pruned 15 | :param fn_next_output_feature: function, function to calculate the next output feature map 16 | :param method: str 17 | 'greedy': select one contributed to the smallest next feature after another 18 | 'lasso': select pruned channels by lasso regression 19 | 'random': randomly select 20 | :return: 21 | list of int, indices of filters to be pruned 22 | """ 23 | num_channel = output_feature.size(1) 24 | num_pruned = int(math.floor(num_channel * sparsity)) 25 | 26 | if method == 'greedy': 27 | indices_pruned = [] 28 | while len(indices_pruned) < num_pruned: 29 | min_diff = 1e10 30 | min_idx = 0 31 | for idx in range(num_channel): 32 | if idx in indices_pruned: 33 | continue 34 | indices_try = indices_pruned + [idx] 35 | output_feature_try = torch.zeros_like(output_feature) 36 | output_feature_try[:, indices_try, ...] = output_feature[:, indices_try, ...] 37 | output_feature_try = fn_next_output_feature(output_feature_try) 38 | output_feature_try_norm = output_feature_try.norm(2) 39 | if output_feature_try_norm < min_diff: 40 | min_diff = output_feature_try_norm 41 | min_idx = idx 42 | indices_pruned.append(min_idx) 43 | elif method == 'lasso': 44 | next_output_feature = fn_next_output_feature(output_feature) 45 | num_el = next_output_feature.numel() 46 | next_output_feature = next_output_feature.data.view(num_el).cpu() 47 | next_output_feature_divided = [] 48 | for idx in range(num_channel): 49 | output_feature_try = torch.zeros_like(output_feature) 50 | output_feature_try[:, idx, ...] = output_feature[:, idx, ...] 51 | output_feature_try = fn_next_output_feature(output_feature_try) 52 | next_output_feature_divided.append(output_feature_try.data.view(num_el, 1)) 53 | next_output_feature_divided = torch.cat(next_output_feature_divided, dim=1).cpu() 54 | 55 | alpha = 5e-5 56 | solver = Lasso(alpha=alpha, warm_start=True, selection='random') 57 | 58 | # first, try to find a alpha that provides enough pruned channels 59 | alpha_l, alpha_r = 0, alpha 60 | num_pruned_try = 0 61 | while num_pruned_try < num_pruned: 62 | alpha_r *= 2 63 | solver.alpha = alpha_r 64 | solver.fit(next_output_feature_divided, next_output_feature) 65 | num_pruned_try = sum(solver.coef_ == 0) 66 | 67 | # then, narrow down alpha to get more close to the desired number of pruned channels 68 | num_pruned_max = int(num_pruned * num_pruned_tolerate_coeff) 69 | while True: 70 | alpha = (alpha_l + alpha_r) / 2 71 | solver.alpha = alpha 72 | solver.fit(next_output_feature_divided, next_output_feature) 73 | num_pruned_try = sum(solver.coef_ == 0) 74 | if num_pruned_try > num_pruned_max: 75 | alpha_r = alpha 76 | elif num_pruned_try < num_pruned: 77 | alpha_l = alpha 78 | else: 79 | break 80 | 81 | # finally, convert lasso coeff to indices 82 | indices_pruned = solver.coef_.nonzero()[0].tolist() 83 | elif method == 'random': 84 | indices_pruned = random.sample(range(num_channel), num_pruned) 85 | else: 86 | raise NotImplementedError 87 | 88 | return indices_pruned 89 | 90 | 91 | def module_surgery(module, next_module, indices_pruned): 92 | """ 93 | prune the redundant filters/channels 94 | :param module: torch.nn.module, module of the layer being pruned 95 | :param next_module: torch.nn.module, module of the next layer to the one being pruned 96 | :param indices_pruned: list of int, indices of filters/channels to be pruned 97 | :return: 98 | void 99 | """ 100 | # operate module 101 | if isinstance(module, torch.nn.modules.conv._ConvNd): 102 | indices_stayed = list(set(range(module.out_channels)) - set(indices_pruned)) 103 | num_channels_stayed = len(indices_stayed) 104 | module.out_channels = num_channels_stayed 105 | elif isinstance(module, torch.nn.Linear): 106 | indices_stayed = list(set(range(module.out_features)) - set(indices_pruned)) 107 | num_channels_stayed = len(indices_stayed) 108 | module.out_features = num_channels_stayed 109 | else: 110 | raise NotImplementedError 111 | # operate module weight 112 | new_weight = module.weight[indices_stayed, ...].clone() 113 | del module.weight 114 | module.weight = torch.nn.Parameter(new_weight) 115 | # operate module bias 116 | if module.bias is not None: 117 | new_bias = module.bias[indices_stayed, ...].clone() 118 | del module.bias 119 | module.bias = torch.nn.Parameter(new_bias) 120 | # operate next_module 121 | if isinstance(next_module, torch.nn.modules.conv._ConvNd): 122 | next_module.in_channels = num_channels_stayed 123 | elif isinstance(next_module, torch.nn.Linear): 124 | next_module.in_features = num_channels_stayed 125 | else: 126 | raise NotImplementedError 127 | # operate next_module weight 128 | new_weight = next_module.weight[:, indices_stayed, ...].clone() 129 | del next_module.weight 130 | next_module.weight = torch.nn.Parameter(new_weight) 131 | 132 | 133 | def weight_reconstruction(next_module, next_input_feature, next_output_feature, cpu=True): 134 | """ 135 | reconstruct the weight of the next layer to the one being pruned 136 | :param next_module: torch.nn.module, module of the next layer to the one being pruned 137 | :param next_input_feature: torch.(cuda.)Tensor, new input feature map of the next layer 138 | :param next_output_feature: torch.(cuda.)Tensor, original output feature map of the next layer 139 | :param cpu: bool, whether done in cpu 140 | :return: 141 | void 142 | """ 143 | if next_module.bias is not None: 144 | bias_size = [1] * next_output_feature.dim() 145 | bias_size[1] = -1 146 | next_output_feature -= next_module.bias.view(bias_size) 147 | if cpu: 148 | next_input_feature = next_input_feature.cpu() 149 | if isinstance(next_module, torch.nn.modules.conv._ConvNd): 150 | unfold = torch.nn.Unfold(kernel_size=next_module.kernel_size, 151 | dilation=next_module.dilation, 152 | padding=next_module.padding, 153 | stride=next_module.stride) 154 | if not cpu: 155 | unfold = unfold.cuda() 156 | unfold.eval() 157 | next_input_feature = unfold(next_input_feature) 158 | next_input_feature = next_input_feature.transpose(1, 2) 159 | num_fields = next_input_feature.size(0) * next_input_feature.size(1) 160 | next_input_feature = next_input_feature.reshape(num_fields, -1) 161 | next_output_feature = next_output_feature.view(next_output_feature.size(0), next_output_feature.size(1), -1) 162 | next_output_feature = next_output_feature.transpose(1, 2).reshape(num_fields, -1) 163 | if cpu: 164 | next_output_feature = next_output_feature.cpu() 165 | param, _ = torch.gels(next_output_feature.data, next_input_feature.data) 166 | param = param[0:next_input_feature.size(1), :].clone().t().contiguous().view(next_output_feature.size(1), -1) 167 | if isinstance(next_module, torch.nn.modules.conv._ConvNd): 168 | param = param.view(next_module.out_channels, next_module.in_channels, *next_module.kernel_size) 169 | del next_module.weight 170 | next_module.weight = torch.nn.Parameter(param) 171 | 172 | 173 | def prune_channel(sparsity, module, next_module, fn_next_input_feature, input_feature, method='greedy', cpu=True): 174 | """ 175 | channel pruning core function 176 | :param sparsity: float, pruning sparsity 177 | :param module: torch.nn.module, module of the layer being pruned 178 | :param next_module: torch.nn.module, module of the next layer to the one being pruned 179 | :param fn_next_input_feature: function, function to calculate the input feature map for next_module 180 | :param input_feature: torch.(cuda.)Tensor, input feature map of the layer being pruned 181 | :param method: str 182 | 'greedy': select one contributed to the smallest next feature after another 183 | 'lasso': pruned channels by lasso regression 184 | 'random': randomly select 185 | :param cpu: bool, whether done in cpu for larger reconstruction batch size 186 | :return: 187 | void 188 | """ 189 | assert input_feature.dim() >= 2 # N x C x ... 190 | output_feature = module(input_feature) 191 | next_input_feature = fn_next_input_feature(output_feature) 192 | next_output_feature = next_module(next_input_feature) 193 | 194 | def fn_next_output_feature(feature): 195 | return next_module(fn_next_input_feature(feature)) 196 | 197 | indices_pruned = channel_selection(sparsity=sparsity, output_feature=output_feature, 198 | fn_next_output_feature=fn_next_output_feature, method=method) 199 | module_surgery(module=module, next_module=next_module, indices_pruned=indices_pruned) 200 | 201 | next_input_feature = fn_next_input_feature(module(input_feature)) 202 | weight_reconstruction(next_module=next_module, next_input_feature=next_input_feature, 203 | next_output_feature=next_output_feature, cpu=cpu) 204 | -------------------------------------------------------------------------------- /slender/prune/vanilla.py: -------------------------------------------------------------------------------- 1 | import re 2 | import math 3 | import torch 4 | from collections import Iterable 5 | 6 | 7 | def prune_vanilla_elementwise(param, sparsity, fn_importance=lambda x: x.abs()): 8 | """ 9 | element-wise vanilla pruning 10 | :param param: torch.(cuda.)Tensor, weight of conv/fc layer 11 | :param sparsity: float, pruning sparsity 12 | :param fn_importance: function, inputs 'param' and returns the importance of 13 | each position in 'param', 14 | default=lambda x: x.abs() 15 | :return: 16 | torch.(cuda.)ByteTensor, mask for zeros 17 | """ 18 | sparsity = min(max(0.0, sparsity), 1.0) 19 | if sparsity == 1.0: 20 | return torch.zeros_like(param).byte() 21 | num_el = param.numel() 22 | importance = fn_importance(param) 23 | num_pruned = int(math.ceil(num_el * sparsity)) 24 | num_stayed = num_el - num_pruned 25 | if sparsity <= 0.5: 26 | _, topk_indices = torch.topk(importance.view(num_el), k=num_pruned, 27 | dim=0, largest=False, sorted=False) 28 | mask = torch.zeros_like(param).byte() 29 | param.view(num_el).index_fill_(0, topk_indices, 0) 30 | mask.view(num_el).index_fill_(0, topk_indices, 1) 31 | else: 32 | thr = torch.min(torch.topk(importance.view(num_el), k=num_stayed, 33 | dim=0, largest=True, sorted=False)[0]) 34 | mask = torch.lt(importance, thr) 35 | param.masked_fill_(mask, 0) 36 | return mask 37 | 38 | 39 | def prune_vanilla_kernelwise(param, sparsity, fn_importance=lambda x: x.norm(1, -1)): 40 | """ 41 | kernel-wise vanilla pruning, the importance determined by L1 norm 42 | :param param: torch.(cuda.)Tensor, weight of conv/fc layer 43 | :param sparsity: float, pruning sparsity 44 | :param fn_importance: function, inputs 'param' as size (param.size(0) * param.size(1), -1) and 45 | returns the importance of each kernel in 'param', 46 | default=lambda x: x.norm(1, -1) 47 | :return: 48 | torch.(cuda.)ByteTensor, mask for zeros 49 | """ 50 | assert param.dim() >= 3 51 | sparsity = min(max(0.0, sparsity), 1.0) 52 | if sparsity == 1.0: 53 | return torch.zeros_like(param).byte() 54 | num_kernels = param.size(0) * param.size(1) 55 | param_k = param.view(num_kernels, -1) 56 | param_importance = fn_importance(param_k) 57 | num_pruned = int(math.ceil(num_kernels * sparsity)) 58 | _, topk_indices = torch.topk(param_importance, k=num_pruned, 59 | dim=0, largest=False, sorted=False) 60 | mask = torch.zeros_like(param).byte() 61 | mask_k = mask.view(num_kernels, -1) 62 | param_k.index_fill_(0, topk_indices, 0) 63 | mask_k.index_fill_(0, topk_indices, 1) 64 | return mask 65 | 66 | 67 | def prune_vanilla_filterwise(sparsity, param, fn_importance=lambda x: x.norm(1, -1)): 68 | """ 69 | filter-wise vanilla pruning, the importance determined by L1 norm 70 | :param param: torch.(cuda.)Tensor, weight of conv/fc layer 71 | :param sparsity: float, pruning sparsity 72 | :param fn_importance: function, inputs 'param' as size (param.size(0), -1) and 73 | returns the importance of each filter in 'param', 74 | default=lambda x: x.norm(1, -1) 75 | :return: 76 | torch.(cuda.)ByteTensor, mask for zeros 77 | """ 78 | assert param.dim() >= 3 79 | sparsity = min(max(0.0, sparsity), 1.0) 80 | if sparsity == 1.0: 81 | return torch.zeros_like(param).byte() 82 | num_filters = param.size(0) 83 | param_k = param.view(num_filters, -1) 84 | param_importance = fn_importance(param_k) 85 | num_pruned = int(math.ceil(num_filters * sparsity)) 86 | _, topk_indices = torch.topk(param_importance, k=num_pruned, 87 | dim=0, largest=False, sorted=False) 88 | mask = torch.zeros_like(param).byte() 89 | mask_k = mask.view(num_filters, -1) 90 | param_k.index_fill_(0, topk_indices, 0) 91 | mask_k.index_fill_(0, topk_indices, 1) 92 | return mask 93 | 94 | 95 | class VanillaPruner(object): 96 | 97 | def __init__(self, rule=None): 98 | """ 99 | Pruner Class for Vanilla Pruning Method 100 | :param rule: str, path to the rule file, each line formats 101 | 'param_name granularity sparsity_stage_0, sparstiy_stage_1, ...' 102 | list of tuple, [(param_name(str), granularity(str), 103 | sparsity(float) or [sparsity_stage_0(float), sparstiy_stage_1,], 104 | fn_importance(optional, str or function))] 105 | 'granularity': str, choose from ['element', 'kernel', 'filter'] 106 | 'fn_importance': str, choose from ['abs', 'l1norm', 'l2norm'] 107 | """ 108 | if rule: 109 | if isinstance(rule, str): 110 | content = map(lambda x: x.split(), open(rule).readlines()) 111 | content = filter(lambda x: len(x) == 3, content) 112 | rule = list(map(lambda x: (x[0], x[1], list(map(float, x[2].split(',')))), content)) 113 | for r in rule: 114 | if not isinstance(r[2], Iterable): 115 | assert isinstance(r[2], float) or isinstance(r[2], int) 116 | r[2] = [float(r[2])] 117 | if len(r) == 3: 118 | r.append('default') 119 | granularity = r[1] 120 | if granularity == 'element': 121 | r.append(prune_vanilla_elementwise) 122 | elif granularity == 'kernel': 123 | r.append(prune_vanilla_kernelwise) 124 | elif granularity == 'filter': 125 | r.append(prune_vanilla_filterwise) 126 | else: 127 | raise NotImplementedError 128 | 129 | self.rule = rule 130 | 131 | self.masks = dict() 132 | 133 | print("=" * 89) 134 | if self.rule: 135 | print("Initializing Vanilla Pruner with rules:") 136 | for r in self.rule: 137 | print(r[:-1]) 138 | else: 139 | print("Initializing Vanilla Pruner WITHOUT rules") 140 | print("=" * 89) 141 | 142 | def load_state_dict(self, state_dict, replace_rule=True): 143 | """ 144 | Recover Pruner 145 | :param state_dict: dict, a dictionary containing a whole state of the Pruner 146 | :param replace_rule: bool, whether to use rule settings in 'state_dict' 147 | :return: VanillaPruner 148 | """ 149 | if replace_rule: 150 | self.rule = state_dict['rule'] 151 | for r in self.rule: 152 | granularity = r[1] 153 | if granularity == 'element': 154 | r.append(prune_vanilla_elementwise) 155 | elif granularity == 'kernel': 156 | r.append(prune_vanilla_kernelwise) 157 | elif granularity == 'filter': 158 | r.append(prune_vanilla_filterwise) 159 | else: 160 | raise NotImplementedError 161 | self.masks = state_dict['masks'] 162 | print("=" * 89) 163 | print("Customizing Vanilla Pruner with rules:") 164 | for r in self.rule: 165 | print(r[:-1]) 166 | print("=" * 89) 167 | 168 | def state_dict(self): 169 | """ 170 | Returns a dictionary containing a whole state of the Pruner 171 | :return: dict, a dictionary containing a whole state of the Pruner 172 | """ 173 | state_dict = dict() 174 | state_dict['rule'] = [r[:-1] for r in self.rule] 175 | state_dict['masks'] = self.masks 176 | return state_dict 177 | 178 | def prune_param(self, param, param_name, stage=0, verbose=False): 179 | """ 180 | prune parameter 181 | :param param: torch.(cuda.)tensor 182 | :param param_name: str, name of param 183 | :param stage: int, the pruning stage, default=0 184 | :param verbose: bool, whether to print the pruning details 185 | :return: 186 | torch.(cuda.)ByteTensor, mask for zeros 187 | """ 188 | rule_id = -1 189 | for idx, r in enumerate(self.rule): 190 | m = re.match(r[0], param_name) 191 | if m is not None and len(param_name) == m.span()[1]: 192 | rule_id = idx 193 | break 194 | if rule_id > -1: 195 | sparsity = self.rule[rule_id][2][stage] 196 | fn_prune = self.rule[rule_id][-1] 197 | fn_importance = self.rule[rule_id][3] 198 | if verbose: 199 | print("{param_name:^30} | {stage:5d} | {spars:.3f}". 200 | format(param_name=param_name, stage=stage, spars=sparsity)) 201 | if fn_importance is None or fn_importance == 'default': 202 | mask = fn_prune(param=param, sparsity=sparsity) 203 | elif fn_importance == 'abs': 204 | mask = fn_prune(param=param, sparsity=sparsity, fn_importance=lambda x: x.abs()) 205 | elif fn_importance == 'l1norm': 206 | mask = fn_prune(param=param, sparsity=sparsity, fn_importance=lambda x: x.norm(1, -1)) 207 | elif fn_importance == 'l2norm': 208 | mask = fn_prune(param=param, sparsity=sparsity, fn_importance=lambda x: x.norm(2, -1)) 209 | else: 210 | mask = fn_prune(param=param, sparsity=sparsity, fn_importance=fn_importance) 211 | return mask 212 | else: 213 | if verbose: 214 | print("{param_name:^30} | skipping".format(param_name=param_name)) 215 | return None 216 | 217 | def prune(self, model, stage=0, update_masks=False, verbose=False): 218 | """ 219 | prune models 220 | :param model: torch.nn.Module 221 | :param stage: int, the pruning stage, default=0 222 | :param update_masks: bool, whether update masks 223 | :param verbose: bool, whether to print the pruning details 224 | :return: 225 | void 226 | """ 227 | update_masks = True if update_masks or len(self.masks) == 0 else False 228 | if verbose: 229 | print("=" * 89) 230 | print("Pruning Models") 231 | if len(self.masks) == 0: 232 | print("Initializing Masks") 233 | elif update_masks: 234 | print("Updating Masks") 235 | print("=" * 89) 236 | print("{name:^30} | stage | sparsity".format(name='param_name')) 237 | for param_name, param in model.named_parameters(): 238 | if 'AuxLogits' not in param_name: 239 | # deal with googlenet 240 | if param.dim() > 1: 241 | if update_masks: 242 | mask = self.prune_param(param=param.data, param_name=param_name, 243 | stage=stage, verbose=verbose) 244 | if mask is not None: 245 | self.masks[param_name] = mask 246 | else: 247 | if param_name in self.masks: 248 | mask = self.masks[param_name] 249 | param.data.masked_fill_(mask, 0) 250 | if verbose: 251 | print("=" * 89) 252 | -------------------------------------------------------------------------------- /slender/quantize/__init__.py: -------------------------------------------------------------------------------- 1 | from .quantizer import Quantizer 2 | -------------------------------------------------------------------------------- /slender/quantize/fixed_point.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | 4 | def quantize_fixed_point(param, bit_length=8, bit_length_integer=0, **unused): 5 | """ 6 | vanilla fixed point quantization, inherently fixing zeros 7 | :param param: torch.(cuda.)tensor 8 | :param bit_length: int, bit length of fixed point param 9 | including sign bit, default=8 10 | :param bit_length_integer: int, bit length of integer part 11 | of fixed point param, default=0 12 | :param unused: unused: unused options 13 | :return: 14 | """ 15 | mul_coeff = 2 ** (bit_length - 1 - bit_length_integer) 16 | div_coeff = 2 ** (bit_length_integer - bit_length + 1) 17 | max_coeff = 2 ** (bit_length - 1) 18 | param.mul_(mul_coeff).floor_().clamp_(-max_coeff - 1, max_coeff - 1).mul_(div_coeff) 19 | codebook = {'cluster_centers_': torch.arange(-max_coeff * div_coeff, 20 | max_coeff * div_coeff, div_coeff), 21 | 'method': 'fixed_point', 22 | } 23 | return codebook -------------------------------------------------------------------------------- /slender/quantize/kmeans.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from sklearn.cluster import KMeans 3 | import torch 4 | 5 | 6 | def quantize_k_means(param, k=16, codebook=None, guess='k-means++', 7 | update_labels=False, re_quantize=False, **unused): 8 | """ 9 | quantize using k-means clustering 10 | :param param: 11 | :param codebook: sklearn.cluster.KMeans, codebook of quantization, default=None 12 | :param k: int, the number of quantization level, default=16 13 | :param guess: str, initial quantization centroid generation method, 14 | choose from 'linear', 'random', 'k-means++' 15 | numpy.ndarray of shape (num_el, 1) 16 | :param update_labels: bool, whether to re-allocate the param elements to the latest centroids 17 | :param re_quantize: bool, whether to re-quantize the param 18 | :param unused: unused options 19 | :return: 20 | sklearn.cluster.KMeans, codebook of quantization 21 | """ 22 | param_shape = param.size() 23 | num_el = param.numel() 24 | param_1d = param.view(num_el) 25 | 26 | if codebook is None or re_quantize: 27 | param_numpy = param_1d.view(num_el, 1).cpu().numpy() 28 | 29 | if guess == 'linear': 30 | guess = np.linspace(np.min(param_numpy), np.max(param_numpy), k) 31 | guess = guess.reshape(guess.size, 1) 32 | codebook = KMeans(n_clusters=k, init=guess, n_jobs=-1).fit(param_numpy) 33 | codebook.cluster_centers_ = torch.from_numpy(codebook.cluster_centers_).float() 34 | codebook.labels_ = torch.from_numpy(codebook.labels_).long() 35 | if param.is_cuda: 36 | codebook.cluster_centers_ = codebook.cluster_centers_.cuda(param.device) 37 | 38 | else: 39 | if update_labels: 40 | sorted_centers, indices = torch.sort(codebook.cluster_centers_, dim=0) 41 | boundaries = (sorted_centers[1:] + sorted_centers[:-1]) / 2 42 | sorted_labels = torch.ge(param_1d - boundaries, 0).long().sum(dim=0) 43 | codebook.labels_ = indices.index_select(0, sorted_labels).view(num_el) 44 | for i in range(k): 45 | codebook.cluster_centers_[i, 0] = param_1d[codebook.labels_ == i].mean() 46 | 47 | param_quantize = codebook.cluster_centers_[codebook.labels_].view(param_shape) 48 | if param.is_contiguous(): 49 | param_quantize = param_quantize.contiguous() 50 | param.set_(param_quantize) 51 | 52 | return codebook 53 | 54 | 55 | def quantize_k_means_fix_zeros(param, k=16, guess='k-means++', codebook=None, 56 | update_labels=False, re_quantize=False, **unused): 57 | """ 58 | quantize using k-means clustering while fixing the zeros 59 | :param param: 60 | :param codebook: sklearn.cluster.KMeans, codebook of quantization, default=None 61 | :param k: int, the number of quantization level, default=16 62 | :param guess: str, initial quantization centroid generation method, 63 | choose from 'linear', 'random', 'k-means++' 64 | :param update_labels: bool, whether to re-allocate the param elements to the latest centroids 65 | :param re_quantize: bool, whether to re-quantize the param 66 | :param unused: unused options 67 | :return: 68 | sklearn.cluster.KMeans, codebook of quantization 69 | """ 70 | param_shape = param.size() 71 | num_el = param.numel() 72 | param_1d = param.view(num_el) 73 | if codebook is not None: 74 | param_1d[codebook.labels_ == 0] = 0 75 | 76 | if codebook is None or re_quantize: 77 | param_numpy = param_1d.cpu().numpy() 78 | param_nz = param_numpy[param_numpy != 0] 79 | param_nz = param_nz.reshape(param_nz.size, 1) 80 | 81 | if guess == 'linear': 82 | guess = np.linspace(np.min(param_nz), np.max(param_nz), k - 1) # one less cluster due to zero-fixed 83 | guess = guess.reshape(guess.size, 1) 84 | codebook = KMeans(n_clusters=k-1, init=guess, n_jobs=-1).fit(param_nz) # one less cluster due to zero-fixed 85 | centers = codebook.cluster_centers_ 86 | centers = np.append(0.0, centers) # append zero as centroid[0] 87 | codebook.cluster_centers_ = centers.reshape(centers.size, 1) 88 | codebook.labels_ = codebook.predict(param_numpy.reshape(num_el, 1)) 89 | codebook.cluster_centers_ = torch.from_numpy(codebook.cluster_centers_).float() 90 | codebook.labels_ = torch.from_numpy(codebook.labels_).long() 91 | if param.is_cuda: 92 | codebook.cluster_centers_ = codebook.cluster_centers_.cuda(param.device) 93 | 94 | # nonzero_indices = param_1d.nonzero() 95 | # nonzero_indices = nonzero_indices.view(nonzero_indices.numel()) 96 | # codebook.cluster_centers_ = torch.from_numpy(codebook.cluster_centers_).float().cuda() 97 | # labels_ = torch.from_numpy(codebook.labels_).long().cuda().add_(1) 98 | # codebook.labels_ = labels_.new(num_el).zero_().index_copy_(0, nonzero_indices, labels_) 99 | 100 | else: 101 | if update_labels: 102 | sorted_centers, indices = torch.sort(codebook.cluster_centers_, dim=0) 103 | boundaries = (sorted_centers[1:] + sorted_centers[:-1]) / 2 104 | sorted_labels = torch.ge(param_1d - boundaries, 0).long().sum(dim=0) 105 | codebook.labels_ = indices.index_select(0, sorted_labels).view(num_el) 106 | for i in range(1, k): 107 | # not from (0, k), because we fix the zero centroid 108 | codebook.cluster_centers_[i, 0] = param_1d[codebook.labels_ == i].mean() 109 | 110 | param_quantize = codebook.cluster_centers_[codebook.labels_].view(param_shape) 111 | if not param.is_contiguous(): 112 | param_quantize = param_quantize.contiguous() 113 | param.set_(param_quantize) 114 | 115 | return codebook 116 | -------------------------------------------------------------------------------- /slender/quantize/linear.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch 3 | 4 | magic_percentile = 0.001 5 | 6 | 7 | def quantize_linear(param, k=16, **unused): 8 | """ 9 | linearly quantize 10 | :param param: torch.(cuda.)tensor 11 | :param k: int, the number of quantization level, default=16 12 | :param unused: unused options 13 | :return: 14 | dict, {'centers_': torch.tensor}, codebook of quantization 15 | """ 16 | num_el = param.numel() 17 | kth = int(math.ceil(num_el * magic_percentile)) 18 | param_flatten = param.view(num_el) 19 | param_min, _ = torch.topk(param_flatten, kth, dim=0, largest=False, sorted=False) 20 | param_min = param_min.max() 21 | param_max, _ = torch.topk(param_flatten, kth, dim=0, largest=True, sorted=False) 22 | param_max = param_max.min() 23 | step = (param_max - param_min) / (k - 1) 24 | param.clamp_(param_min, param_max).sub_(param_min).div_(step).round_().mul_(step).add_(param_min) 25 | # codebook = {'centers_': torch.tensor(list(set(param_flatten.cpu().tolist())))} 26 | codebook = {'cluster_centers_': torch.linspace(param_min, param_max, k), 27 | 'method': 'linear', 28 | } 29 | return codebook 30 | 31 | 32 | def quantize_linear_fix_zeros(param, k=16, **unused): 33 | """ 34 | linearly quantize while fixing zeros 35 | :param param: torch.(cuda.)tensor 36 | :param k: int, the number of quantization level, default=16 37 | :param unused: unused options 38 | :return: 39 | dict, {'centers_': torch.tensor}, codebook of quantization 40 | """ 41 | zero_mask = torch.eq(param, 0.0) # get zero mask 42 | num_param = param.numel() 43 | kth = int(math.ceil(num_param * magic_percentile)) 44 | param_flatten = param.view(num_param) 45 | param_min, _ = torch.topk(param_flatten, kth, dim=0, largest=False, sorted=False) 46 | param_min = param_min.max() 47 | param_max, _ = torch.topk(param_flatten, kth, dim=0, largest=True, sorted=False) 48 | param_max = param_max.min() 49 | step = (param_max - param_min) / (k - 2) 50 | param.clamp_(param_min, param_max).sub_(param_min).div_(step).round_().mul_(step).add_(param_min) 51 | param.masked_fill_(zero_mask, 0) # recover zeros 52 | # codebook = {'centers_': torch.tensor(list(set(param_flatten.cpu().tolist())))} 53 | codebook = {'cluster_centers_': torch.zeros(k), 54 | 'method': 'linear', 55 | } 56 | codebook['cluster_centers_'][1:] = torch.linspace(param_min, param_max, k - 1) 57 | return codebook -------------------------------------------------------------------------------- /slender/quantize/quantizer.py: -------------------------------------------------------------------------------- 1 | import re 2 | from sklearn.cluster import KMeans 3 | 4 | from slender.quantize.fixed_point import quantize_fixed_point 5 | from slender.quantize.linear import quantize_linear, quantize_linear_fix_zeros 6 | from slender.quantize.kmeans import quantize_k_means, quantize_k_means_fix_zeros 7 | 8 | 9 | def vanilla_quantize(method='k-means', fix_zeros=True, **options): 10 | """ 11 | returns quantization function based on the options 12 | :param fix_zeros: bool, whether to fix zeros in the param 13 | :param method: str, quantization method, choose from 'linear', 'k-means' 14 | :param bit_length: int, bit length of fixed point param, default=8 15 | :param bit_length_integer: int, bit length of integer part 16 | of fixed point param, default=0 17 | :param k: int, the number of quantization level, default=16 18 | :param codebook: sklearn.cluster.KMeans, codebook of quantization, default=None 19 | :param guess: str, initial quantization centroid generation method, 20 | choose from 'linear', 'random', 'k-means++' 21 | numpy.ndarray of shape (num_el, 1) 22 | :param update_labels: bool, whether to re-allocate the param elements 23 | to the latest centroids when using k-means 24 | :param re_quantize: bool, whether to re-quantize the param when using k-means 25 | :return: 26 | codebook 27 | """ 28 | if method == 'k-means': 29 | if fix_zeros: 30 | return quantize_k_means_fix_zeros(**options) 31 | else: 32 | return quantize_k_means(**options) 33 | elif method == 'linear': 34 | if fix_zeros: 35 | return quantize_linear_fix_zeros(**options) 36 | else: 37 | return quantize_linear(**options) 38 | else: 39 | return quantize_fixed_point(**options) 40 | 41 | 42 | class Quantizer(object): 43 | 44 | def __init__(self, rule=None, fix_zeros=True): 45 | """ 46 | Quantizer class for quantization 47 | :param rule: str, path to the rule file, each line formats 48 | 'param_name method bit_length initial_guess_or_bit_length_of_integer' 49 | list of tuple, 50 | [(param_name(str), method(str), bit_length(int), 51 | initial_guess(str)_or_bit_length_of_integer(int))] 52 | :param fix_zeros: whether to fix zeros when quantizing 53 | """ 54 | if rule: 55 | if isinstance(rule, str): 56 | content = map(lambda x: x.split(), open(rule).readlines()) 57 | content = filter(lambda x: len(x) == 4, content) 58 | rule = list(map(lambda x: (x[0], x[1], int(x[2]), 59 | int(x[3]) if x[1] == 'fixed_point' else x[3]), 60 | content)) 61 | self.rule = rule 62 | 63 | self.codebooks = dict() 64 | self.fix_zeros = fix_zeros 65 | self.fn_quantize = vanilla_quantize 66 | 67 | print("=" * 89) 68 | if self.rule: 69 | print("Initializing Quantizer with rules:") 70 | for r in self.rule: 71 | print(r) 72 | else: 73 | print("Initializing Quantizer WITHOUT rules") 74 | print("=" * 89) 75 | 76 | def load_state_dict(self, state_dict): 77 | """ 78 | Recover Quantizer 79 | :param state_dict: dict, a dictionary containing a whole state of the Quantizer 80 | :return: 81 | Quantizer 82 | """ 83 | self.rule = state_dict['rule'] 84 | self.fix_zeros = state_dict['fix_zeros'] 85 | self.codebooks = dict() 86 | for name, codebook in state_dict['codebooks'].items(): 87 | if codebook['method'] == 'k-means': 88 | self.codebooks[name] = KMeans().set_params(**codebook['params']) 89 | self.codebooks[name].cluster_centers_ = codebook['centers'] 90 | self.codebooks[name].labels_ = codebook['labels'] 91 | else: 92 | self.codebooks[name] = codebook 93 | print("=" * 89) 94 | print("Customizing Quantizer with rules:") 95 | for r in self.rule: 96 | print(r) 97 | print("=" * 89) 98 | 99 | def state_dict(self): 100 | """ 101 | Returns a dictionary containing a whole state of the Quantizer 102 | :return: dict, a dictionary containing a whole state of the Quantizer 103 | """ 104 | state_dict = dict() 105 | state_dict['rule'] = self.rule 106 | state_dict['fix_zeros'] = self.fix_zeros 107 | codebooks = dict() 108 | for name, codebook in self.codebooks.items(): 109 | if isinstance(codebook, KMeans): 110 | codebooks[name] = { 111 | 'params': codebook.get_params(), 112 | 'centers': codebook.cluster_centers_, 113 | 'labels': codebook.labels_, 114 | 'method': 'k-means' 115 | } 116 | else: 117 | codebooks[name] = codebook 118 | state_dict['codebooks'] = codebooks 119 | return state_dict 120 | 121 | def quantize_param(self, param, param_name, verbose=False, **quantize_options): 122 | """ 123 | quantize param 124 | :param param: torch.(cuda.)tensor 125 | :param param_name: str, name of param 126 | :param update_labels: bool, whether to re-allocate the param elements 127 | to the latest centroids when using k-means 128 | :param re_quantize: bool, whether to re-quantize the param when using k-means 129 | :param verbose: bool, whether to print quantize details 130 | :return: 131 | dict, {'centers_': torch.tensor}, codebook of linear quantization 132 | sklearn.cluster.KMeans, codebook of k-means quantization 133 | """ 134 | rule_id = -1 135 | for idx, r in enumerate(self.rule): 136 | m = re.match(r[0], param_name) 137 | if m is not None and len(param_name) == m.span()[1]: 138 | rule_id = idx 139 | break 140 | if rule_id > -1: 141 | method = self.rule[rule_id][1] 142 | bit_length = self.rule[rule_id][2] 143 | k = 2 ** bit_length 144 | guess = self.rule[rule_id][3] 145 | bit_length_integer = guess 146 | if k <= 0: 147 | if verbose: 148 | print("{param_name:^30} | skipping".format(param_name=param_name)) 149 | return None 150 | codebook = self.codebooks.get(param_name) 151 | if verbose: 152 | if codebook is None: 153 | print("{param_name:^30} | {bit_length:2d} bit | initializing". 154 | format(param_name=param_name, bit_length=bit_length)) 155 | elif method == 'k-means': 156 | if quantize_options.get('re_quantize'): 157 | print("{param_name:^30} | {bit_length:2d} bit | re-quantizing". 158 | format(param_name=param_name, bit_length=bit_length)) 159 | elif quantize_options.get('update_labels'): 160 | print("{param_name:^30} | {bit_length:2d} bit | updating labels and centroids". 161 | format(param_name=param_name, bit_length=bit_length)) 162 | else: 163 | print("{param_name:^30} | {bit_length:2d} bit | updating centroids only". 164 | format(param_name=param_name, bit_length=bit_length)) 165 | else: 166 | print("{param_name:^30} | {bit_length:2d} bit | re-quantizing". 167 | format(param_name=param_name, bit_length=bit_length)) 168 | codebook = self.fn_quantize(method=method, fix_zeros=self.fix_zeros, 169 | param=param, bit_length=bit_length, 170 | bit_length_integer=bit_length_integer, 171 | k=k, guess=guess, codebook=codebook, 172 | **quantize_options) 173 | return codebook 174 | else: 175 | if verbose: 176 | print("{param_name:^30} | skipping".format(param_name=param_name)) 177 | return None 178 | 179 | def quantize(self, model, update_labels=False, re_quantize=False, verbose=False): 180 | """ 181 | quantize model 182 | :param model: torch.nn.module 183 | :param update_labels: bool, whether to re-allocate the param elements 184 | to the latest centroids when using k-means 185 | :param re_quantize: bool, whether to re-quantize the param when using k-means 186 | :param verbose: bool, whether to print quantize details 187 | :return: 188 | void 189 | """ 190 | if verbose: 191 | print("=" * 89) 192 | print("Quantizing Model") 193 | print("=" * 89) 194 | print("{name:^30} | qz bit | state".format(name='param_name')) 195 | for param_name, param in model.named_parameters(): 196 | if param.dim() > 1: 197 | codebook = self.quantize_param(param.data, param_name, verbose=verbose, 198 | update_labels=update_labels, 199 | re_quantize=re_quantize) 200 | if codebook is not None: 201 | self.codebooks[param_name] = codebook 202 | if verbose: 203 | print("=" * 89) 204 | -------------------------------------------------------------------------------- /slender/replicate.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | 4 | def replicate(network, keep_param=False): 5 | assert isinstance(network, torch.nn.Module) 6 | 7 | params = list(network.parameters()) 8 | param_indices = {param: idx for idx, param in enumerate(params)} 9 | param_copies = [torch.nn.Parameter(param.detach().clone()) for param in params] 10 | 11 | buffers = list(network._all_buffers()) 12 | buffer_indices = {buf: idx for idx, buf in enumerate(buffers)} 13 | buffer_copies = [buffer.clone() for buffer in buffers] 14 | 15 | modules = list(network.modules()) 16 | module_indices = {} 17 | module_copies = [] 18 | 19 | for i, module in enumerate(modules): 20 | module_indices[module] = i 21 | replica = module.__new__(type(module)) 22 | replica.__dict__ = module.__dict__.copy() 23 | replica._parameters = replica._parameters.copy() 24 | replica._buffers = replica._buffers.copy() 25 | replica._modules = replica._modules.copy() 26 | module_copies.append(replica) 27 | 28 | for i, module in enumerate(modules): 29 | for key, child in module._modules.items(): 30 | if child is None: 31 | replica = module_copies[i] 32 | replica._modules[key] = None 33 | else: 34 | module_idx = module_indices[child] 35 | replica = module_copies[i] 36 | replica._modules[key] = module_copies[module_idx] 37 | for key, param in module._parameters.items(): 38 | if param is None: 39 | replica = module_copies[i] 40 | replica._parameters[key] = None 41 | else: 42 | param_idx = param_indices[param] 43 | replica = module_copies[i] 44 | replica._parameters[key] = param_copies[param_idx] 45 | for key, buf in module._buffers.items(): 46 | if buf is None: 47 | replica = module_copies[i] 48 | replica._buffers[key] = None 49 | else: 50 | buffer_idx = buffer_indices[buf] 51 | replica = module_copies[i] 52 | replica._buffers[key] = buffer_copies[buffer_idx] 53 | 54 | return module_copies[0] 55 | -------------------------------------------------------------------------------- /slender/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | from itertools import islice 3 | 4 | 5 | def iter_str_every(iterable, k): 6 | """ 7 | 8 | :param iterable: 9 | :param k: 10 | :return: 11 | """ 12 | i = iter(iterable) 13 | piece = ''.join(islice(i, k)) 14 | while piece: 15 | yield piece 16 | piece = ''.join(islice(i, k)) 17 | 18 | 19 | def get_sparsity(param): 20 | """ 21 | 22 | :param param: 23 | :return: 24 | """ 25 | mask = param.eq(0) 26 | return float(mask.sum()) / mask.numel() 27 | 28 | 29 | class AverageMeter(object): 30 | """Computes and stores the average and current value""" 31 | def __init__(self): 32 | self.val = 0 33 | self.avg = 0 34 | self.sum = 0 35 | self.count = 0 36 | 37 | def reset(self): 38 | self.val = 0 39 | self.avg = 0 40 | self.sum = 0 41 | self.count = 0 42 | 43 | def update(self, val, n=1): 44 | self.val = val 45 | self.sum += val * n 46 | self.count += n 47 | if self.count > 0: 48 | self.avg = self.sum / self.count 49 | 50 | def accumulate(self, val, n=1): 51 | self.sum += val 52 | self.count += n 53 | if self.count > 0: 54 | self.avg = self.sum / self.count 55 | 56 | 57 | class Logger(object): 58 | def __init__(self, file_path): 59 | """ 60 | write log to file 61 | :param file_path: str, path to the file 62 | """ 63 | self.f = open(file_path, 'w') 64 | self.fid = self.f.fileno() 65 | self.filepath = file_path 66 | 67 | def close(self): 68 | """ 69 | close log file 70 | :return: 71 | """ 72 | return self.f.close() 73 | 74 | def flush(self): 75 | self.f.flush() 76 | os.fsync(self.fid) 77 | 78 | def write(self, content, wrap=True, flush=False, verbose=False): 79 | """ 80 | write file and flush buffer to the disk 81 | :param content: str 82 | :param wrap: bool, whether to add '\n' at the end of the content 83 | :param flush: bool, whether to flush buffer to the disk, default=False 84 | :param verbose: bool, whether to print the content, default=False 85 | :return: 86 | void 87 | """ 88 | if verbose: 89 | print(content) 90 | if wrap: 91 | content += "\n" 92 | self.f.write(content) 93 | if flush: 94 | self.f.flush() 95 | os.fsync(self.fid) 96 | 97 | 98 | class StageScheduler(object): 99 | 100 | def __init__(self, max_num_stage, stage_step=45): 101 | """ 102 | 103 | :param max_num_stage: 104 | :param stage_step: 105 | """ 106 | self.max_num_stage = max_num_stage 107 | 108 | self.stage_step = stage_step 109 | if isinstance(stage_step, int): 110 | self.stage_step = [stage_step] * max_num_stage 111 | if isinstance(stage_step, str): 112 | self.stage_step = list(map(int, stage_step.split(','))) 113 | assert isinstance(self.stage_step, list) 114 | 115 | num_stage = len(self.stage_step) 116 | if num_stage < self.max_num_stage: 117 | for i in range(self.max_num_stage - num_stage): 118 | self.stage_step.append(self.stage_step[num_stage - 1]) 119 | elif num_stage > self.max_num_stage: 120 | self.max_num_stage = num_stage 121 | assert len(self.stage_step) == self.max_num_stage 122 | 123 | for i in range(1, self.max_num_stage): 124 | self.stage_step[i] += self.stage_step[i - 1] 125 | 126 | def step(self, epoch): 127 | """ 128 | 129 | :param epoch: 130 | :return: 131 | """ 132 | stage = self.max_num_stage - 1 133 | for i, max_epoch in enumerate(self.stage_step): 134 | if epoch < max_epoch: 135 | stage = i 136 | break 137 | if stage > 0: 138 | epoch -= self.stage_step[stage - 1] 139 | return stage, epoch 140 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synxlin/nn-compression/34918a4ed2bbe44a483a6e81a740ae5fe3ffc065/test/__init__.py -------------------------------------------------------------------------------- /test/test_coding.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | from slender.prune.vanilla import prune_vanilla_elementwise 4 | from slender.quantize.linear import quantize_linear_fix_zeros 5 | from slender.quantize.fixed_point import quantize_fixed_point 6 | from slender.quantize.quantizer import Quantizer 7 | from slender.coding.encode import EncodedParam 8 | from slender.coding.codec import Codec 9 | 10 | 11 | def test_encode_param(): 12 | param = torch.rand(256, 128, 3, 3) 13 | prune_vanilla_elementwise(sparsity=0.7, param=param) 14 | quantize_linear_fix_zeros(param, k=16) 15 | huffman = EncodedParam(param=param, method='huffman', 16 | encode_indices=True, bit_length_zero_run_length=4) 17 | stats = huffman.stats 18 | print(stats) 19 | assert torch.eq(param, huffman.data).all() 20 | state_dict = huffman.state_dict() 21 | huffman = EncodedParam() 22 | huffman.load_state_dict(state_dict) 23 | assert torch.eq(param, huffman.data).all() 24 | vanilla = EncodedParam(param=param, method='vanilla', 25 | encode_indices=True, bit_length_zero_run_length=4) 26 | stats = vanilla.stats 27 | print(stats) 28 | assert torch.eq(param, vanilla.data).all() 29 | quantize_fixed_point(param=param, bit_length=4, bit_length_integer=0) 30 | fixed_point = EncodedParam(param=param, method='fixed_point', 31 | bit_length=4, bit_length_integer=0, 32 | encode_indices=True, bit_length_zero_run_length=4) 33 | stats = fixed_point.stats 34 | print(stats) 35 | assert torch.eq(param, fixed_point.data).all() 36 | 37 | 38 | def test_codec(): 39 | quantize_rule = [ 40 | ('0.weight', 'k-means', 4, 'k-means++'), 41 | ('1.weight', 'fixed_point', 6, 1), 42 | ] 43 | model = torch.nn.Sequential(torch.nn.Conv2d(256, 128, 3, bias=True), 44 | torch.nn.Conv2d(128, 512, 1, bias=False)) 45 | mask_dict = {} 46 | for n, p in model.named_parameters(): 47 | mask_dict[n] = prune_vanilla_elementwise(sparsity=0.6, param=p.data) 48 | quantizer = Quantizer(rule=quantize_rule, fix_zeros=True) 49 | quantizer.quantize(model, update_labels=False, verbose=True) 50 | rule = [ 51 | ('0.weight', 'huffman', 0, 0, 4), 52 | ('1.weight', 'fixed_point', 6, 1, 4) 53 | ] 54 | codec = Codec(rule=rule) 55 | encoded_module = codec.encode(model) 56 | print(codec.stats) 57 | state_dict = encoded_module.state_dict() 58 | model_2 = torch.nn.Sequential(torch.nn.Conv2d(256, 128, 3, bias=True), 59 | torch.nn.Conv2d(128, 512, 1, bias=False)) 60 | model_2 = Codec.decode(model_2, state_dict) 61 | for p1, p2 in zip(model.parameters(), model_2.parameters()): 62 | if p1.dim() > 1: 63 | assert torch.eq(p1, p2).all() 64 | -------------------------------------------------------------------------------- /test/test_quantize.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | from slender.prune.vanilla import prune_vanilla_elementwise 4 | from slender.quantize.linear import quantize_linear, quantize_linear_fix_zeros 5 | from slender.quantize.kmeans import quantize_k_means, quantize_k_means_fix_zeros 6 | from slender.quantize.fixed_point import quantize_fixed_point 7 | from slender.quantize.quantizer import Quantizer 8 | 9 | 10 | def test_quantize_linear(): 11 | param = torch.rand(128, 64, 3, 3) - 0.5 12 | codebook = quantize_linear(param, k=16) 13 | assert codebook['cluster_centers_'].numel() == 16 14 | centers_ = codebook['cluster_centers_'].tolist() 15 | vals = set(param.view(param.numel()).tolist()) 16 | for v in vals: 17 | assert v in centers_ 18 | 19 | 20 | def test_quantize_linear_fix_zeros(): 21 | param = torch.rand(128, 64, 3, 3) - 0.5 22 | mask = prune_vanilla_elementwise(sparsity=0.4, param=param) 23 | codebook = quantize_linear_fix_zeros(param, k=16) 24 | assert codebook['cluster_centers_'].numel() == 16 25 | centers_ = codebook['cluster_centers_'].tolist() 26 | vals = set(param.view(param.numel()).tolist()) 27 | for v in vals: 28 | assert v in centers_ 29 | assert param.masked_select(mask).eq(0).all() 30 | 31 | 32 | def test_quantize_k_means(): 33 | param = torch.rand(128, 64, 3, 3) - 0.5 34 | codebook = quantize_k_means(param, k=16) 35 | assert codebook.cluster_centers_.numel() == 16 36 | centers_ = codebook.cluster_centers_.view(16).tolist() 37 | vals = set(param.view(param.numel()).tolist()) 38 | for v in vals: 39 | assert v in centers_ 40 | param = torch.rand(128, 64, 3, 3) 41 | codebook = quantize_k_means(param, k=16, codebook=codebook, 42 | update_centers=True) 43 | assert codebook.cluster_centers_.numel() == 16 44 | centers_ = codebook.cluster_centers_.view(16).tolist() 45 | vals = set(param.view(param.numel()).tolist()) 46 | for v in vals: 47 | assert v in centers_ 48 | 49 | 50 | def test_quantize_k_means_fix_zeros(): 51 | param = torch.rand(128, 64, 3, 3) - 0.5 52 | mask = prune_vanilla_elementwise(sparsity=0.4, param=param) 53 | codebook = quantize_k_means_fix_zeros(param, k=16) 54 | assert codebook.cluster_centers_.numel() == 16 55 | centers_ = codebook.cluster_centers_.view(16).tolist() 56 | vals = set(param.view(param.numel()).tolist()) 57 | for v in vals: 58 | assert v in centers_ 59 | assert param.masked_select(mask).eq(0).all() 60 | codebook = quantize_k_means_fix_zeros(param, k=16, codebook=codebook, 61 | update_centers=True) 62 | assert codebook.cluster_centers_.numel() == 16 63 | centers_ = codebook.cluster_centers_.view(16).tolist() 64 | vals = set(param.view(param.numel()).tolist()) 65 | for v in vals: 66 | assert v in centers_ 67 | assert param.masked_select(mask).eq(0).all() 68 | 69 | 70 | def test_quantized_fixed_point(): 71 | param = torch.rand(128, 64, 3, 3) - 0.5 72 | mask = prune_vanilla_elementwise(sparsity=0.4, param=param) 73 | codebook = quantize_fixed_point(param, bit_length=8, bit_length_integer=1) 74 | assert codebook['cluster_centers_'].numel() == 2 ** 8 75 | centers_ = codebook['cluster_centers_'].tolist() 76 | vals = set(param.view(param.numel()).tolist()) 77 | for v in vals: 78 | assert v in centers_ 79 | assert param.masked_select(mask).eq(0).all() 80 | 81 | 82 | def test_quantizer(): 83 | rule = [ 84 | ('0.weight', 'k-means', 4, 'k-means++'), 85 | ('1.weight', 'fixed_point', 6, 1), 86 | ] 87 | rule_dict = { 88 | '0.weight': ['k-means', 16], 89 | '1.weight': ['fixed_point', 6, 1] 90 | } 91 | model = torch.nn.Sequential(torch.nn.Conv2d(256, 128, 3, bias=True), 92 | torch.nn.Conv2d(128, 512, 1, bias=False)) 93 | mask_dict = {} 94 | for n, p in model.named_parameters(): 95 | mask_dict[n] = prune_vanilla_elementwise(sparsity=0.4, param=p) 96 | quantizer = Quantizer(rule=rule, fix_zeros=True) 97 | quantizer.quantize(model, update_labels=False, verbose=True) 98 | for n, p in model.named_parameters(): 99 | if n in rule_dict: 100 | vals = set(p.data.view(p.numel()).tolist()) 101 | if rule_dict[n][0] == 'k-means': 102 | centers_ = quantizer.codebooks[n].cluster_centers_.view(rule_dict[n][1]).tolist() 103 | else: 104 | centers_ = quantizer.codebooks[n]['cluster_centers_'] 105 | for v in vals: 106 | assert v in centers_ 107 | assert p.data.masked_select(mask_dict[n]).eq(0).all 108 | 109 | state_dict = quantizer.state_dict() 110 | quantizer = Quantizer().load_state_dict(state_dict) 111 | model = torch.nn.Sequential(torch.nn.Conv2d(256, 128, 3, bias=True), 112 | torch.nn.Conv2d(128, 512, 1, bias=False)) 113 | mask_dict = {} 114 | for n, p in model.named_parameters(): 115 | mask_dict[n] = prune_vanilla_elementwise(sparsity=0.4, param=p) 116 | quantizer.quantize(model, update_labels=True, verbose=True) 117 | for n, p in model.named_parameters(): 118 | if n in rule_dict: 119 | vals = set(p.data.view(p.numel()).tolist()) 120 | if rule_dict[n][0] == 'k-means': 121 | centers_ = quantizer.codebooks[n].cluster_centers_.view(rule_dict[n][1]).tolist() 122 | else: 123 | centers_ = quantizer.codebooks[n]['cluster_centers_'] 124 | for v in vals: 125 | assert v in centers_ 126 | assert p.data.masked_select(mask_dict[n]).eq(0).all -------------------------------------------------------------------------------- /test/test_vanilla_prune.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch 3 | 4 | from slender.prune.vanilla import prune_vanilla_elementwise, prune_vanilla_kernelwise, \ 5 | prune_vanilla_filterwise, VanillaPruner 6 | 7 | 8 | def test_prune_vanilla_elementwise(): 9 | param = torch.rand(64, 128, 3, 3) 10 | mask = prune_vanilla_elementwise(sparsity=0.3, param=param) 11 | assert mask.sum() == int(math.ceil(param.numel() * 0.3)) 12 | assert param.masked_select(mask).eq(0).all() 13 | mask = prune_vanilla_elementwise(sparsity=0.7, param=param) 14 | assert mask.sum() == int(math.ceil(param.numel() * 0.7)) 15 | assert param.masked_select(mask).eq(0).all() 16 | 17 | 18 | def test_prune_vanilla_kernelwise(): 19 | param = torch.rand(64, 128, 3, 3) 20 | mask = prune_vanilla_kernelwise(sparsity=0.5, param=param) 21 | mask_s = mask.view(64*128, -1).all(1).sum() 22 | assert mask_s == 32*128 23 | assert param.masked_select(mask).eq(0).all() 24 | 25 | 26 | def test_prune_vanilla_filterwise(): 27 | param = torch.rand(64, 128, 3, 3) 28 | mask = prune_vanilla_filterwise(sparsity=0.5, param=param) 29 | mask_s = mask.view(64, -1).all(1).sum() 30 | assert mask_s == 32 31 | assert param.masked_select(mask).eq(0).all() 32 | 33 | 34 | def test_vanilla_pruner(): 35 | rule = [ 36 | ('0.weight', 'element', [0.3, 0.5]), 37 | ('1.weight', 'element', [0.4, 0.6]) 38 | ] 39 | rule_dict = { 40 | '0.weight': [0.3, 0.5], 41 | '1.weight': [0.4, 0.6] 42 | } 43 | model = torch.nn.Sequential(torch.nn.Conv2d(256, 128, 3, bias=True), 44 | torch.nn.Conv2d(128, 512, 1, bias=False)) 45 | pruner = VanillaPruner(rule=rule) 46 | pruner.prune(model=model, stage=0, verbose=True) 47 | for n, param in model.named_parameters(): 48 | if param.dim() > 1: 49 | mask = pruner.masks[n] 50 | assert mask.sum() == int(math.ceil(param.numel() * rule_dict[n][0])) 51 | assert param.data.masked_select(mask).eq(0).all() 52 | state_dict = pruner.state_dict() 53 | pruner = VanillaPruner().load_state_dict(state_dict) 54 | model = torch.nn.Sequential(torch.nn.Conv2d(256, 128, 3, bias=True), 55 | torch.nn.Conv2d(128, 512, 1, bias=False)) 56 | pruner.prune(model=model, stage=0) 57 | for n, param in model.named_parameters(): 58 | if param.dim() > 1: 59 | mask = pruner.masks[n] 60 | assert mask.sum() == int(math.ceil(param.numel() * rule_dict[n][0])) 61 | assert param.data.masked_select(mask).eq(0).all() 62 | pruner.prune(model=model, stage=1, update_masks=True, verbose=True) 63 | for n, param in model.named_parameters(): 64 | if param.dim() > 1: 65 | mask = pruner.masks[n] 66 | assert mask.sum() == int(math.ceil(param.numel() * rule_dict[n][1])) 67 | assert param.data.masked_select(mask).eq(0).all() 68 | --------------------------------------------------------------------------------