├── .circleci └── config.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── TODO.md ├── bin ├── deploy.sh ├── update_version.py └── version.json ├── examples └── mnist_autoencoder │ ├── README.md │ ├── mnist_autoencoder_example.py │ └── progress_plot.png ├── install_and_run_test.sh ├── logo ├── logo.png ├── logo_small.png ├── logo_v1.png └── social.png ├── pypi ├── test.sh └── test_pytorch_versions.sh ├── setup.py ├── tests └── test.py └── torchac ├── __init__.py ├── backend └── torchac_backend.cpp └── torchac.py /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | orbs: 4 | python: circleci/python@0.2.1 5 | 6 | jobs: 7 | build-and-test: 8 | docker: 9 | - image: circleci/python:3.8 10 | steps: 11 | - add_ssh_keys: 12 | fingerprints: 13 | - "SHA256:+8f0fEsj1+0ZW5VftgZdhan1iKLM7Vfj55KujJRMXjk" 14 | - checkout 15 | - run: 16 | command: | 17 | python3 -m venv env_torchac 18 | . env_torchac/bin/activate 19 | pip3 install --upgrade pip 20 | pip3 install numpy torch pytest ninja 21 | echo "export PYTHONPATH=.:$PYTHONPATH" >> $BASH_ENV 22 | name: Setup 23 | - run: 24 | command: | 25 | . env_torchac/bin/activate 26 | ls -al 27 | CUDA_VISIBLE_DEVICES="" python3 -m pytest tests/test.py -s 28 | 29 | 30 | workflows: 31 | main: 32 | jobs: 33 | - build-and-test 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .DS_Store 3 | examples/mnist_autoencoder/plots 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | 63 | # Flask stuff: 64 | instance/ 65 | .webassets-cache 66 | 67 | # Scrapy stuff: 68 | .scrapy 69 | 70 | # Sphinx documentation 71 | docs/_build/ 72 | 73 | # PyBuilder 74 | target/ 75 | 76 | # Jupyter Notebook 77 | .ipynb_checkpoints 78 | 79 | # pyenv 80 | .python-version 81 | 82 | # celery beat schedule file 83 | celerybeat-schedule 84 | 85 | # SageMath parsed files 86 | *.sage.py 87 | 88 | # Environments 89 | .env 90 | .venv 91 | env/ 92 | venv/ 93 | ENV/ 94 | env.bak/ 95 | venv.bak/ 96 | 97 | # Spyder project settings 98 | .spyderproject 99 | .spyproject 100 | 101 | # Rope project settings 102 | .ropeproject 103 | 104 | # mkdocs documentation 105 | /site 106 | 107 | # mypy 108 | .mypy_cache/ 109 | /data/ 110 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | 6 | # torchac: Fast Arithmetic Coding for PyTorch 7 | 8 | [![TestStatus](https://circleci.com/gh/fab-jul/torchac.svg?style=shield)](https://circleci.com/gh/fab-jul/torchac) 9 | [![PyPiVersion](https://badge.fury.io/py/torchac.svg)](https://pypi.org/project/torchac/) 10 | ![PythonVersion](https://img.shields.io/badge/Python-%3E%3D3.8-brightgreen) 11 | ![PyTorchVersions](https://img.shields.io/badge/PyTorch-1.12-brightgreen) 12 | 13 | 14 | 15 | 16 | ## About 17 | 18 | This is a stand-alone version of the arithmetic coder we used in the 19 | neural compression paper [Practical Full Resolution Learned Lossless Image 20 | Compression](https://github.com/fab-jul/L3C-PyTorch) by Mentzer et al. 21 | 22 | The backend is written in C++, the API is for PyTorch tensors. Thanks to 23 | on-the-fly compilation with ninja, the integration is seamless. 24 | 25 | The implementation is based on [this blog post](https://marknelson.us/posts/2014/10/19/data-compression-with-arithmetic-coding.html), 26 | meaning that we implement _arithmetic coding_. 27 | While it could be further optimized, it is already much faster than doing the equivalent thing in pure-Python (because of all the 28 | bit-shifts etc.). In L3C, Encoding all pixels of a `512 x 512` image happens in 0.202s (see [Appendix A](https://arxiv.org/abs/1811.12817) in the paper). 29 | 30 | ### What torchac is 31 | 32 | - A simple-to-use library to encode a stream of symbols into a bitstream given 33 | the cumulative distribution (CDF) of the symbols. 34 | The number of possible symbols must be finite. 35 | 36 | ### What torchac is not 37 | 38 | - We do not provide classes to learn or represent probability/cumulative 39 | distributions. These have to be provided by you. 40 | 41 | 42 | ## HowTo 43 | 44 | ### Set up conda environment 45 | 46 | This library has been tested with 47 | - PyTorch 1.5 - 1.12 48 | - Python 3.8, 3.9 49 | 50 | Other versions of Python may also work, 51 | but on-the-fly ninja compilation only works for PyTorch 1.5+. 52 | 53 | In a supported environment, install `torchac` with `pip`: 54 | 55 | ```bash 56 | pip install torchac 57 | ``` 58 | 59 | If you don't have an environment already set up, you can make one with `conda`, 60 | see [pytorch.org](https://pytorch.org). 61 | 62 | #### Testing installation 63 | 64 | To test the installation, `git clone` this repo and run `bash 65 | install_and_run_test.sh`. It should end in a line that says that `5 passed`. 66 | 67 | ### Example 68 | 69 | The `examples/` folder contains [an example for training an auto-encoder on MNIST](https://github.com/fab-jul/torchac/tree/master/examples/mnist_autoencoder). 70 | 71 |
72 | 73 |

Output of the example script. First two columns show training 74 | set, second two columns show testing set.

75 |
76 | 77 | Snipped from that example: 78 | 79 | ```python 80 | import torchac 81 | 82 | # Encode to bytestream. 83 | output_cdf = ... # Get CDF from your model, shape B, C, H, W, Lp 84 | sym = ... # Get the symbols to encode, shape B, C, H, W. 85 | byte_stream = torchac.encode_float_cdf(output_cdf, sym, check_input_bounds=True) 86 | 87 | # Number of bits taken by the stream 88 | real_bits = len(byte_stream) * 8 89 | 90 | # Write to a file. 91 | with open('outfile.b', 'wb') as fout: 92 | fout.write(byte_stream) 93 | 94 | # Read from a file. 95 | with open('outfile.b', 'rb') as fin: 96 | byte_stream = fin.read() 97 | 98 | # Decode from bytestream. 99 | sym_out = torchac.decode_float_cdf(output_cdf, byte_stream) 100 | 101 | # Output will be equal to the input. 102 | assert sym_out.equal(sym) 103 | ``` 104 | 105 | ## FAQ 106 | 107 | #### 1. Output is not equal to the input 108 | 109 | Either normalization went wrong or you encoded a symbol that is `>Lp`, 110 | see below for more details. 111 | 112 | ## Important Implementation Details 113 | 114 | ### How we represent probability distributions. 115 | 116 | The probabilities are specified as [CDFs](https://en.wikipedia.org/wiki/Cumulative_distribution_function). 117 | For each possible symbol, 118 | we need 2 CDF values. This means that if there are `L` possible symbols 119 | `{0, ..., L-1}`, the CDF must specified the value for `L+1` symbols. 120 | 121 | **Example**: 122 | ``` 123 | Let's say we have L = 3 possible symbols. We need a CDF with 4 values 124 | to specify the symbols distribution: 125 | 126 | symbol: 0 1 2 127 | cdf: C_0 C_1 C_2 C_3 128 | 129 | This corresponds to the 3 probabilities 130 | 131 | P(0) = C_1 - C_0 132 | P(1) = C_2 - C_1 133 | P(2) = C_3 - C_2 134 | 135 | NOTE: The arithmetic coder assumes that C_3 == 1. 136 | ``` 137 | 138 | Important: 139 | 140 | - If you have `L` possible symbols, you need to pass a CDF that 141 | specifies `L + 1` values. Since this is a common number, we call it 142 | `Lp = L + 1` throught the code (the "p" stands for prime, i.e., `L'`). 143 | - The last value of the CDF should be `1`. Note that the arithmetic coder 144 | in `torchac.cpp` will just assume it's `1` regardless of what is passed, so not having a CDF 145 | that ends in `1` will mean you will estimate bitrates wrongly. More details below. 146 | - Note that even though the CDF specifies `Lp` values, symbols are only allowed 147 | to be in `{0, ..., Lp-2}`. In the above example, `Lp == 4`, but the 148 | max symbols is `Lp-2 == 2`. Bigger values will yield **wrong outputs** 149 | 150 | ### Expected input shapes 151 | 152 | We allow any shapes for the inputs, but the spatial dimensions of the 153 | input CDF and the input symbols must match. In particular, we expect: 154 | 155 | - CDF must have shape `(N1, ..., Nm, Lp)`, where `N1, ..., Nm` are the 156 | `m` spatial dimensions, and `Lp` is as described above. 157 | - Symbols must have shape `(N1, ..., Nm)`, i.e., same spatial dimensions 158 | as the CDF. 159 | 160 | For example, in a typical CNN, you might have a CDF of shape 161 | `(batch, channels, height, width, Lp)`. 162 | 163 | 164 | ### Normalized vs. Unnormalized / Floating Point vs. Integer CDFs 165 | 166 | The library differentiates between "normalized" and "unnormalized" CDFs, 167 | and between "floating point" and "integer" CDFs. What do these mean? 168 | 169 | - A proper CDF is strictly monotonically increasing, and we call this a 170 | "normalized" CDF. 171 | - However, since we work with finite precision (16 bits to 172 | be precise in this implementation), it may be that you have a CDF that 173 | is strictly monotonically increasing in `float32` space, but not when 174 | it is converted to 16 bit precision. An "unnormalized" CDF is what we call 175 | a CDF that has the same value for at least two subsequent elements. 176 | - "floating point" CDFs are CDFs that are specified as `float32` and need 177 | to be converted to 16 bit precision. 178 | - "integer" CDFs are CDFs specified as `int16` - BUT are then interpreted 179 | as `uint16` on the C++ side. See "int16 vs uint16" below. 180 | 181 | Examples: 182 | 183 | ```python 184 | float_unnormalized_cdf = [0.1, 0.2, 0.2, 0.3, ..., 1.] 185 | float_normalized_cdf = [0.1, 0.2, 0.20001, 0.3, ..., 1.] 186 | integer_unnormalized_cdf = [10, 20, 20, 30, ..., 0] # See below for why last is 0. 187 | integer_normalized_cdf = [10, 20, 21, 30, ..., 0] # See below for why last is 0. 188 | ``` 189 | 190 | There are two APIs: 191 | 192 | - `encode_float_cdf` and `decode_float_cdf` is to be used for floating point 193 | CDFs. These functions have a flag `needs_normalization` that specifies 194 | whether the input is assumed to be normalized. You can set 195 | `need_normalization=False` if you have CDFs that you know are normalized, e.g., 196 | Gaussian distributions with a large enough sigma. This would then speedup 197 | encoding and decoding large tensors somewhat, and will make bitrate 198 | estimation from the CDF more precise. 199 | - `encode_int16_normalized_cdf` and `decode_int16_normalized_cdf` is to be 200 | used for integer CDFs **that are already normalized**. 201 | 202 | ### int16 vs uint16 - it gets confusing! 203 | 204 | One big source of confusion can be that PyTorch does not support `uint16`. 205 | Yet, that's exactly what we need. So what we do is we just represent 206 | integer CDFs with `int16` in the Python side, and interpret/cast them to `uint16` 207 | on the C++ side. This means that if you were to look at the int16 CDFs 208 | you would see confusing things: 209 | 210 | ```python 211 | # Python 212 | cdf_float = [0., 1/3, 2/3, 1.] # A uniform distribution for L=3 symbols. 213 | cdf_int = [0, 21845, -21845, 0] 214 | 215 | # C++ 216 | uint16* cdf_int = [0, 21845, 43690, 0] 217 | ``` 218 | 219 | Note: 220 | 1. In the python `cdf_int` numbers bigger than `2**16/2` are negative 221 | 2. The final value is actually 0. This is then handled in `torchac.cpp` which 222 | just assums `cdf[..., -1] == 2**16`, which cannot be represented as a `uint16`. 223 | 224 | Fun stuff! 225 | 226 | ## Citation 227 | 228 | If you use the work released here for your research, consider citing this paper: 229 | ``` 230 | @inproceedings{mentzer2019practical, 231 | Author = {Mentzer, Fabian and Agustsson, Eirikur and Tschannen, Michael and Timofte, Radu and Van Gool, Luc}, 232 | Booktitle = {Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, 233 | Title = {Practical Full Resolution Learned Lossless Image Compression}, 234 | Year = {2019}} 235 | ``` 236 | 237 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | ## **State**: Released 2 | #### Future 3 | 4 | - [ ] Docker container with all dependencies 5 | - [ ] link to here from L3C 6 | - [ ] estimate bitrate from normalized CDF 7 | -------------------------------------------------------------------------------- /bin/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | VERSION_NUMBER=$1 6 | 7 | if [[ -z $VERSION_NUMBER ]]; then 8 | echo "Usage: $0 VERSION_NUMBER" 9 | exit 1 10 | fi 11 | 12 | if [ -n "$(git status --porcelain)" ]; then 13 | echo "Error: Git not clean, please commit." 14 | exit 1 15 | fi 16 | 17 | python bin/update_version.py $VERSION_NUMBER 18 | 19 | rm -rf dist/ 20 | python setup.py bdist_wheel 21 | twine upload dist/* 22 | 23 | python bin/update_version.py $VERSION_NUMBER --set-used 24 | 25 | echo "Waiting for changes to propagate..." 26 | sleep 60 # Give PyPi time to prepare the package. 27 | 28 | bash pypi/test.sh tests/test.py 29 | 30 | git commit bin/version.json -m "Updated Version: $VERSION_NUMBER" 31 | git tag $VERSION_NUMBER 32 | git push 33 | git push --tags 34 | -------------------------------------------------------------------------------- /bin/update_version.py: -------------------------------------------------------------------------------- 1 | from distutils.version import LooseVersion, StrictVersion 2 | import argparse 3 | import json 4 | 5 | 6 | def main(): 7 | p = argparse.ArgumentParser() 8 | p.add_argument('new_version') 9 | p.add_argument('--set-used', action='store_true') 10 | flags = p.parse_args() 11 | new_version = flags.new_version 12 | set_used = flags.set_used 13 | 14 | with open('bin/version.json', 'r') as f: 15 | version_info = json.load(f) 16 | 17 | is_unused = not version_info["used"] 18 | cur_version = version_info["version"] 19 | if is_unused: 20 | version_is_ok = LooseVersion(new_version) >= LooseVersion(cur_version) 21 | else: 22 | version_is_ok = LooseVersion(new_version) > LooseVersion(cur_version) 23 | 24 | if not version_is_ok: 25 | raise ValueError(f'Not ok: {new_version}. Current version={cur_version}') 26 | 27 | with open('bin/version.json', 'w') as f: 28 | json.dump({'version': new_version, 'used': set_used}, f) 29 | 30 | 31 | if __name__ == '__main__': 32 | main() 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /bin/version.json: -------------------------------------------------------------------------------- 1 | {"version": "0.9.3", "used": true} -------------------------------------------------------------------------------- /examples/mnist_autoencoder/README.md: -------------------------------------------------------------------------------- 1 | # MNIST AutoEncoder 2 | 3 |
4 | 5 |

Output of the example script. First two columns show training 6 | set, second two columns show testing set.

7 |
8 | 9 | This example shows how to train a simple auto-encoder for MNIST, 10 | with a quantized bottleneck, and a conditional probability 11 | model that estimates the distribution of the bottleneck. It basically 12 | follows recent image compression papers in terms of structure, 13 | but is much simpler and not tuned. 14 | 15 | Goals: 16 | - Show how to use the probability distribution predicted from some probability 17 | model CNN to estimate the bitrate 18 | - Actually encode symbols with that model using `torchac`, and see how many 19 | bits it takes to store 20 | 21 | What could be improved: 22 | - The models don't actually train very well. The purpose of the example is to 23 | show how `torchac` can be used. 24 | 25 | ## Runnig it 26 | 27 | The example supports interactive plots with matplotlib, which it tries 28 | to use by default. If they are not available (in headless environments), 29 | it falls back to storing plots in `plots`. If you want to force 30 | non-interactive, you can set `export NO_INTERACTIVE=1` before 31 | running the script. 32 | 33 | ```bash 34 | # If not installed already: 35 | pip install matplotlib 36 | pip install torchac 37 | 38 | # Got to this folder 39 | cd examples/mnist_qutoencder 40 | 41 | # Run the script 42 | python mnist_autoencoder_example.py 43 | ``` 44 | -------------------------------------------------------------------------------- /examples/mnist_autoencoder/mnist_autoencoder_example.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import dataclasses 3 | import itertools 4 | import warnings 5 | 6 | import os 7 | import time 8 | 9 | import torch 10 | from torch import nn 11 | import torch.nn.functional as F 12 | 13 | import numpy as np 14 | import torchvision 15 | import matplotlib.pyplot as plt 16 | import matplotlib 17 | 18 | try: 19 | import torchac 20 | except ImportError: 21 | raise ImportError('torchac is not available! Please see the main README ' 22 | 'on how to install it.') 23 | 24 | 25 | # Set to true to write to disk. 26 | _WRITE_BITS = False 27 | 28 | 29 | # Interactive plots setup 30 | _FORCE_NO_INTERACTIVE_PLOTS = int(os.environ.get('NO_INTERACTIVE', 0)) == 1 31 | 32 | 33 | if not _FORCE_NO_INTERACTIVE_PLOTS: 34 | try: 35 | matplotlib.use("TkAgg") 36 | interactive_plots_available = True 37 | except ImportError: 38 | warnings.warn(f'*** TkAgg not available! Saving plots...') 39 | interactive_plots_available = False 40 | else: 41 | interactive_plots_available = False 42 | 43 | if not interactive_plots_available: 44 | matplotlib.use("Agg") 45 | 46 | 47 | # Set seed. 48 | torch.manual_seed(0) 49 | 50 | 51 | def train_test_loop(use_gpu=True, 52 | bottleneck_size=2, 53 | L=5, 54 | batch_size=8, 55 | lr=1e-2, 56 | rate_loss_enable_itr=500, 57 | num_test_batches=10, 58 | train_plot_every_itr=50, 59 | max_training_itr=None, 60 | mnist_download_dir='data', 61 | ): 62 | """Train and test an autoencoder. 63 | 64 | :param use_gpu: Whether to use the GPU, if it is available. 65 | :param bottleneck_size: Number of channels in the bottleneck. 66 | :param L: Number of levels that we quantize to. 67 | :param batch_size: Batch size we train with. 68 | :param lr: Learning rate of Adam. 69 | :param rate_loss_enable_itr: Iteration when the rate loss is enabled. 70 | :param num_test_batches: Number of batches we test on (randomly chosen). 71 | :param train_plot_every_itr: How often to update the train plot. 72 | :param max_training_itr: If given, only train for max_training_itr iterations. 73 | :param mnist_download_dir: Where to store MNIST. 74 | """ 75 | ae = Autoencoder(bottleneck_size, L) 76 | prob = ConditionalProbabilityModel(L=L, bottleneck_shape=ae.bottleneck_shape) 77 | 78 | device = 'cuda' if (use_gpu and torch.cuda.is_available()) else 'cpu' 79 | ae = ae.to(device) 80 | prob = prob.to(device) 81 | 82 | mse = nn.MSELoss() 83 | adam = torch.optim.Adam( 84 | itertools.chain(ae.parameters(), prob.parameters()), 85 | lr=lr) 86 | 87 | train_acc = Accumulator() 88 | test_acc = Accumulator() 89 | plotter = Plotter() 90 | 91 | transforms = torchvision.transforms.Compose([ 92 | torchvision.transforms.ToTensor(), 93 | torchvision.transforms.Lambda( 94 | # Make images 32x32. 95 | lambda image: F.pad(image, pad=(2, 2, 2, 2), mode='constant')) 96 | ]) 97 | 98 | train_loader = torch.utils.data.DataLoader( 99 | torchvision.datasets.MNIST(mnist_download_dir, train=True, download=True, 100 | transform=transforms), 101 | batch_size=batch_size, shuffle=True) 102 | 103 | rate_loss_enabled = False 104 | for i, (images, labels) in enumerate(train_loader): 105 | if max_training_itr and i >= max_training_itr: 106 | break 107 | assert images.shape[-2:] == (32, 32) 108 | images = images.to(device) 109 | labels = labels.to(device) 110 | 111 | adam.zero_grad() 112 | 113 | # Get reconstructions and symbols from the autoencoder. 114 | reconstructions, sym = ae(images) 115 | assert sym.shape[1:] == ae.bottleneck_shape 116 | 117 | # Get estimated and real bitrate from probability model, given labels. 118 | bits_estimated, bits_real = prob(sym.detach(), labels) 119 | mse_loss = mse(reconstructions, images) 120 | 121 | # If we are beyond iteration `rate_loss_enable_itr`, enable a rate loss. 122 | if i < rate_loss_enable_itr: 123 | loss = mse_loss 124 | else: 125 | loss = mse_loss + 1/1000 * bits_estimated 126 | rate_loss_enabled = True 127 | 128 | loss.backward() 129 | adam.step() 130 | 131 | # Update Train Plot. 132 | if i > 0 and i % train_plot_every_itr == 0: 133 | train_acc.append(i, bits_estimated, bits_real, mse_loss) 134 | print(f'{i: 10d}; ' 135 | f'loss={loss:.3f}, ' 136 | f'bits_estimated={bits_estimated:.3f}, ' 137 | f'mse={mse_loss:.3f}') 138 | plotter.update('Train', 139 | images, reconstructions, sym, train_acc, rate_loss_enabled) 140 | 141 | # Update Test Plot. 142 | if i > 0 and i % 100 == 0: 143 | print(f'{i: 10d} Testing on {num_test_batches} random batches...') 144 | ae.eval() 145 | prob.eval() 146 | test_loader = torch.utils.data.DataLoader( 147 | torchvision.datasets.MNIST( 148 | mnist_download_dir, train=False, download=True, transform=transforms), 149 | batch_size=batch_size, shuffle=True) 150 | with torch.no_grad(): 151 | across_batch_acc = Accumulator() 152 | for j, (test_images, test_labels) in enumerate(test_loader): 153 | if j >= num_test_batches: 154 | break 155 | test_images = test_images.to(device) 156 | test_labels = test_labels.to(device) 157 | test_reconstructions, test_sym = ae(test_images) 158 | test_bits_estimated, test_bits_real = prob(test_sym, test_labels) 159 | test_mse_loss = mse(test_reconstructions, test_images) 160 | across_batch_acc.append(j, test_bits_estimated, test_bits_real, test_mse_loss) 161 | test_bits_estimated_mean, test_bits_real_mean, test_mse_loss_mean = \ 162 | across_batch_acc.means() 163 | test_acc.append( 164 | i, test_bits_estimated_mean, test_bits_real_mean, test_mse_loss_mean) 165 | plotter.update('Test', test_images, test_reconstructions, test_sym, 166 | test_acc, rate_loss_enabled) 167 | ae.train() 168 | prob.train() 169 | 170 | 171 | class STEQuantize(torch.autograd.Function): 172 | """Straight-Through Estimator for Quantization. 173 | 174 | Forward pass implements quantization by rounding to integers, 175 | backward pass is set to gradients of the identity function. 176 | """ 177 | @staticmethod 178 | def forward(ctx, x): 179 | ctx.save_for_backward(x) 180 | return x.round() 181 | 182 | @staticmethod 183 | def backward(ctx, grad_outputs): 184 | return grad_outputs 185 | 186 | 187 | class Autoencoder(nn.Module): 188 | def __init__(self, bottleneck_size, L): 189 | if L % 2 != 1: 190 | raise ValueError(f'number of levels L={L}, must be odd number!') 191 | super(Autoencoder, self).__init__() 192 | self.L = L 193 | self.enc = nn.Sequential( 194 | nn.Conv2d(1, 32, 5, stride=2, padding=2), 195 | nn.InstanceNorm2d(32), 196 | nn.ReLU(), 197 | nn.Conv2d(32, 32, 5, stride=2, padding=2), 198 | nn.InstanceNorm2d(32), 199 | nn.ReLU(), 200 | nn.Conv2d(32, 32, 5, stride=2, padding=2), 201 | nn.InstanceNorm2d(32), 202 | nn.ReLU(), 203 | nn.Conv2d(32, 32, 5, stride=2, padding=2), 204 | nn.InstanceNorm2d(32), 205 | nn.ReLU(), 206 | nn.Conv2d(32, bottleneck_size, 1, stride=1, padding=0, bias=False), 207 | ) 208 | 209 | self.dec = nn.Sequential( 210 | nn.ConvTranspose2d(bottleneck_size, 32, 5, stride=2, padding=2, output_padding=1), 211 | nn.InstanceNorm2d(32), 212 | nn.ReLU(), 213 | nn.ConvTranspose2d(32, 32, 5, stride=2, padding=2, output_padding=1), 214 | nn.InstanceNorm2d(32), 215 | nn.ReLU(), 216 | nn.ConvTranspose2d(32, 32, 5, stride=2, padding=2, output_padding=1), 217 | nn.InstanceNorm2d(32), 218 | nn.ReLU(), 219 | nn.ConvTranspose2d(32, 32, 5, stride=2, padding=2, output_padding=1), 220 | nn.InstanceNorm2d(32), 221 | nn.ReLU(), 222 | 223 | # Add a few convolutions at the final resolution. 224 | nn.Conv2d(32, 32, 3, stride=1, padding=1), 225 | nn.ReLU(), 226 | nn.Conv2d(32, 32, 1, stride=1, padding=0), 227 | nn.ReLU(), 228 | nn.Conv2d(32, 1, 1, stride=1), 229 | ) 230 | 231 | self.quantize = STEQuantize.apply 232 | self.bottleneck_shape = (bottleneck_size, 2, 2) 233 | 234 | def forward(self, image): 235 | # Encode image x into the latent. 236 | latent = self.enc(image) 237 | # The jiggle is there so that the lowest and highest symbol are not at 238 | # the boundary. Probably not needed. 239 | jiggle = 0.2 240 | spread = self.L - 1 + jiggle 241 | # The sigmoid clamps to [0, 1], then we multiply it by spread and substract 242 | # spread / 2, so that the output is nicely centered around zero and 243 | # in the interval [-spread/2, spread/2] 244 | latent = torch.sigmoid(latent) * spread - spread / 2 245 | latent_quantized = self.quantize(latent) 246 | reconstructions = self.dec(latent_quantized) 247 | sym = latent_quantized + self.L // 2 248 | return reconstructions, sym.to(torch.long) 249 | 250 | 251 | class ConditionalProbabilityModel(nn.Module): 252 | def __init__(self, L, bottleneck_shape): 253 | super(ConditionalProbabilityModel, self).__init__() 254 | self.L = L 255 | self.bottleneck_shape = bottleneck_shape 256 | 257 | self.bottleneck_size, _, _ = bottleneck_shape 258 | 259 | # We predict a value for each channel, for each level. 260 | num_output_channels = self.bottleneck_size * L 261 | 262 | self.model = nn.Sequential( 263 | nn.Conv2d(1, self.bottleneck_size, 3, padding=1), 264 | nn.BatchNorm2d(self.bottleneck_size), 265 | nn.ReLU(), 266 | nn.Conv2d(self.bottleneck_size, self.bottleneck_size, 3, padding=1), 267 | nn.BatchNorm2d(self.bottleneck_size), 268 | nn.ReLU(), 269 | nn.Conv2d(self.bottleneck_size, num_output_channels, 1, padding=0), 270 | ) 271 | 272 | def forward(self, sym, labels): 273 | batch_size = sym.shape[0] 274 | _, H, W = self.bottleneck_shape 275 | # Construct the input, which is just the label of the current number 276 | # at each spatial location. 277 | bottleneck_shape_with_batch_dim = (batch_size, 1, H, W) 278 | static_input = torch.ones( 279 | bottleneck_shape_with_batch_dim, dtype=torch.float32, device=sym.device) 280 | dynamic_input = static_input * labels.reshape(-1, 1, 1, 1) 281 | # Divide by 9 and substract 0.5 to center the input around 0 and make 282 | # it be contained in [-0.5, 0.5]. 283 | dynamic_input = dynamic_input / 9 - 0.5 284 | 285 | # Get the output of the CNN. 286 | output = self.model(dynamic_input) 287 | _, C, H, W = output.shape 288 | assert C == self.bottleneck_size * self.L 289 | 290 | # Reshape it such that the probability per symbol has it's own dimension. 291 | # output_reshaped has shape (B, C, L, H, W). 292 | output_reshaped = output.reshape( 293 | batch_size, self.bottleneck_size, self.L, H, W) 294 | # Take the softmax over that dimension to make this into a normalized 295 | # probability distribution. 296 | output_probabilities = F.softmax(output_reshaped, dim=2) 297 | # Permute the symbols dimension to the end, as expected by torchac. 298 | # output_probabilities has shape (B, C, H, W, L). 299 | output_probabilities = output_probabilities.permute(0, 1, 3, 4, 2) 300 | # Estimate the bitrate from the PMF. 301 | estimated_bits = estimate_bitrate_from_pmf(output_probabilities, sym=sym) 302 | # Convert to a torchac-compatible CDF. 303 | output_cdf = pmf_to_cdf(output_probabilities) 304 | # torchac expects sym as int16, see README for details. 305 | sym = sym.to(torch.int16) 306 | # torchac expects CDF and sym on CPU. 307 | output_cdf = output_cdf.detach().cpu() 308 | sym = sym.detach().cpu() 309 | # Get real bitrate from the byte_stream. 310 | byte_stream = torchac.encode_float_cdf(output_cdf, sym, check_input_bounds=True) 311 | real_bits = len(byte_stream) * 8 312 | if _WRITE_BITS: 313 | # Write to a file. 314 | with open('outfile.b', 'wb') as fout: 315 | fout.write(byte_stream) 316 | # Read from a file. 317 | with open('outfile.b', 'rb') as fin: 318 | byte_stream = fin.read() 319 | assert torchac.decode_float_cdf(output_cdf, byte_stream).equal(sym) 320 | return estimated_bits, real_bits 321 | 322 | 323 | def pmf_to_cdf(pmf): 324 | cdf = pmf.cumsum(dim=-1) 325 | spatial_dimensions = pmf.shape[:-1] + (1,) 326 | zeros = torch.zeros(spatial_dimensions, dtype=pmf.dtype, device=pmf.device) 327 | cdf_with_0 = torch.cat([zeros, cdf], dim=-1) 328 | # On GPU, softmax followed by cumsum can lead to the final value being 329 | # slightly bigger than 1, so we clamp. 330 | cdf_with_0 = cdf_with_0.clamp(max=1.) 331 | return cdf_with_0 332 | 333 | 334 | def estimate_bitrate_from_pmf(pmf, sym): 335 | L = pmf.shape[-1] 336 | pmf = pmf.reshape(-1, L) 337 | sym = sym.reshape(-1, 1) 338 | assert pmf.shape[0] == sym.shape[0] 339 | relevant_probabilities = torch.gather(pmf, dim=1, index=sym) 340 | bitrate = torch.sum(-torch.log2(relevant_probabilities.clamp(min=1e-3))) 341 | return bitrate 342 | 343 | 344 | @dataclasses.dataclass 345 | class Accumulator: 346 | def __init__(self): 347 | self.iterations = [] 348 | self.bits_estimated_acc = [] 349 | self.bits_real_acc = [] 350 | self.mse_acc = [] 351 | 352 | def append(self, i, bits_estimated, bits_real, mse): 353 | self.iterations.append(i) 354 | self.bits_estimated_acc.append(bits_estimated.item()) 355 | self.bits_real_acc.append(bits_real) 356 | self.mse_acc.append(mse.item()) 357 | 358 | def get_errors(self): 359 | return [real / estimated - 1 for real, estimated in 360 | zip(self.bits_real_acc, self.bits_estimated_acc)] 361 | 362 | def means(self): 363 | return (np.mean(self.bits_estimated_acc), 364 | np.mean(self.bits_real_acc), 365 | np.mean(self.mse_acc)) 366 | 367 | 368 | class Plotter(object): 369 | def __init__(self): 370 | plt.ion() 371 | self.fig, axs = plt.subplots(ncols=4, nrows=4, figsize=(12, 8)) 372 | Plotter._setup_axes(axs[:, :2], 'Train') 373 | Plotter._setup_axes(axs[:, 2:], 'Test') 374 | plt.tight_layout() 375 | if interactive_plots_available: 376 | plt.draw() 377 | else: 378 | unique_id = str(time.time()).replace('.', '_') 379 | self.out_dir = os.path.join('plots', unique_id) 380 | os.makedirs(self.out_dir, exist_ok=True) 381 | self.axs = axs 382 | 383 | @staticmethod 384 | def _setup_axes(axs, title): 385 | axs[0, 0].set_axis_off() 386 | axs[0, 0].set_title(f'{title} Input') 387 | axs[0, 1].set_axis_off() 388 | axs[0, 1].set_title(f'{title} Reconstruction') 389 | axs[1, 0].set_axis_off() 390 | axs[1, 0].set_title(f'{title} Bottleneck channel 1') 391 | axs[1, 1].set_axis_off() 392 | axs[1, 1].set_title(f'{title} Bottleneck channel 2') 393 | axs[2, 0].set_title(f'Estimated Bitrate {title}') 394 | axs[2, 1].set_title(f'Real Bitrate {title}') 395 | axs[3, 0].set_title(f'MSE {title}') 396 | axs[3, 1].set_title('Rel. Bitrate Error') 397 | 398 | def update(self, 399 | mode, 400 | images, reconstructions, sym, 401 | acc: Accumulator, 402 | rate_loss_enabled: bool): 403 | # First two columns are for training, second two for testing. 404 | axs = self.axs[:, :2] if mode == 'Train' else self.axs[:, 2:] 405 | title = mode 406 | 407 | # Plot images. 408 | axs[0, 0].imshow(images[0, ...].squeeze().detach().cpu().numpy()) 409 | axs[0, 1].imshow(reconstructions[0, ...].squeeze().detach().cpu().numpy()) 410 | axs[1, 0].imshow(sym[0, 0, ...].to(torch.float).detach().cpu().numpy()) 411 | axs[1, 1].imshow(sym[0, 1, ...].to(torch.float).detach().cpu().numpy()) 412 | 413 | # Plot lines, make sure to empty plot first. 414 | axs[2, 0].clear() 415 | axs[2, 1].clear() 416 | axs[3, 0].clear() 417 | axs[3, 1].clear() 418 | axs[2, 0].set_title(f'Estimated Bitrate {title}') 419 | axs[2, 1].set_title(f'Real Bitrate {title}') 420 | axs[3, 0].set_title(f'MSE {title}') 421 | axs[3, 1].set_title('Rel. Bitrate Error') 422 | 423 | linestyle = '-' if rate_loss_enabled else ':' 424 | color = 'b' if mode == 'Train' else 'r' 425 | linestyle = color + linestyle 426 | axs[2, 0].plot( 427 | acc.iterations, acc.bits_estimated_acc, linestyle) 428 | axs[2, 1].plot( 429 | acc.iterations, acc.bits_real_acc, linestyle) 430 | 431 | axs[3, 0].plot( 432 | acc.iterations, acc.mse_acc, color) 433 | axs[3, 1].plot( 434 | acc.iterations, acc.get_errors(), color) 435 | 436 | if interactive_plots_available: 437 | plt.pause(0.05) 438 | else: 439 | plotname = f'{acc.iterations[-1]:010d}.png' 440 | out_p = os.path.join(self.out_dir, plotname) 441 | print(f'Saving plot at {out_p}...') 442 | self.fig.savefig(out_p) 443 | 444 | 445 | def main(): 446 | p = argparse.ArgumentParser() 447 | p.add_argument('--max_training_itr', type=int) 448 | flags = p.parse_args() 449 | train_test_loop(max_training_itr=flags.max_training_itr) 450 | 451 | 452 | if __name__ == '__main__': 453 | main() 454 | -------------------------------------------------------------------------------- /examples/mnist_autoencoder/progress_plot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fab-jul/torchac/63064ab4caeaa7d435d7dc6877160161066cb558/examples/mnist_autoencoder/progress_plot.png -------------------------------------------------------------------------------- /install_and_run_test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | TEST_DIR=_torchac_test_ 4 | if [[ ! -f tests/test.py ]]; then 5 | echo "Expected tests/test.py, are your running from repo root?" 6 | exit 1 7 | fi 8 | if [[ -d $TEST_DIR ]]; then 9 | echo "Exists! $TEST_DIR" 10 | exit 1 11 | fi 12 | mkdir -p $TEST_DIR 13 | pushd $TEST_DIR 14 | python3 -m venv .venv 15 | . ./.venv/bin/activate 16 | pip install torch numpy ninja torch pytest 17 | popd 18 | pip list 19 | python -m pytest tests/test.py 20 | deactivate 21 | rm -rf $TEST_DIR 22 | 23 | -------------------------------------------------------------------------------- /logo/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fab-jul/torchac/63064ab4caeaa7d435d7dc6877160161066cb558/logo/logo.png -------------------------------------------------------------------------------- /logo/logo_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fab-jul/torchac/63064ab4caeaa7d435d7dc6877160161066cb558/logo/logo_small.png -------------------------------------------------------------------------------- /logo/logo_v1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fab-jul/torchac/63064ab4caeaa7d435d7dc6877160161066cb558/logo/logo_v1.png -------------------------------------------------------------------------------- /logo/social.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fab-jul/torchac/63064ab4caeaa7d435d7dc6877160161066cb558/logo/social.png -------------------------------------------------------------------------------- /pypi/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Test PyPi package 4 | # 5 | 6 | 7 | TESTS_PATH=$1 8 | PYTORCH_VERSION=$2 9 | 10 | if [[ -z $TESTS_PATH ]]; then 11 | echo "Usage: $0 TESTS_PATH [PYTORCH_VERSION]" 12 | exit 1 13 | fi 14 | 15 | if [[ -z $PYTORCH_VERSION ]]; then 16 | PYTORCH="pytorch" # Use latest 17 | else 18 | PYTORCH="pytorch==$PYTORCH_VERSION" # Use latest 19 | fi 20 | 21 | source ~/Documents/miniconda3/etc/profile.d/conda.sh 22 | 23 | ENV_NAME=torchac_test 24 | conda env list | grep $ENV_NAME 25 | if [[ $? == 1 ]]; then # Env does not exist yet. 26 | conda create -n $ENV_NAME pip python==3.8 -y 27 | fi 28 | 29 | set -e 30 | conda activate $ENV_NAME 31 | conda install $PYTORCH torchvision -c pytorch -y 32 | pip install pytest 33 | pip install --upgrade torchac --no-cache-dir 34 | python -c "import torchac" 35 | python -m pytest $TESTS_PATH -s 36 | 37 | 38 | -------------------------------------------------------------------------------- /pypi/test_pytorch_versions.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | source ~/Documents/miniconda3/etc/profile.d/conda.sh 6 | 7 | LOGFILE=tested.txt 8 | echo "Test Log" > $LOGFILE 9 | 10 | for VERSION in 1.5 1.6 1.7; do 11 | echo "Testing pytorch=$VERSION..." 12 | rm -rf ~/.cache/torch_extensions 13 | rm -rf data/MNIST # MNIST may lead to conflicts 14 | bash pypi/test.sh tests/test.py $VERSION 15 | echo "Tests pass for $VERSION" >> $LOGFILE 16 | conda activate torchac_test 17 | pip install matplotlib 18 | CUDA_VISIBLE_DEVICES="" python -u \ 19 | examples/mnist_autoencoder/mnist_autoencoder_example.py \ 20 | --max_training_itr 5 21 | conda deactivate 22 | conda env remove -n torchac_test -y 23 | echo "Example runs for $VERSION" >> $LOGFILE 24 | done 25 | 26 | echo "" 27 | cat $LOGFILE 28 | rm $LOGFILE 29 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | import json 3 | 4 | 5 | def _get_long_description(): 6 | with open('README.md', 'r') as f: 7 | long_description_lines = [] 8 | skip = False 9 | for line in f: 10 | if '' in line: 13 | skip = False 14 | if skip: 15 | continue 16 | long_description_lines.append(line) 17 | return ''.join(long_description_lines) 18 | 19 | 20 | def _get_version(): 21 | with open('bin/version.json', 'r') as f: 22 | version_info = json.load(f) 23 | if version_info['used']: 24 | raise ValueError('Version already used!') 25 | return version_info['version'] 26 | 27 | 28 | setuptools.setup( 29 | name='torchac', 30 | packages=['torchac'], 31 | version=_get_version(), 32 | author='fab-jul', 33 | author_email='fabianjul@gmail.com', 34 | description='Fast Arithmetic Coding for PyTorch', 35 | long_description=_get_long_description(), 36 | long_description_content_type='text/markdown', 37 | python_requires='>=3.6', 38 | license='GNU General Public License', 39 | url='https://github.com/fab-jul/torchac') 40 | -------------------------------------------------------------------------------- /tests/test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torch 3 | from torchac import torchac 4 | 5 | 6 | def test_out_of_range_symbol(): 7 | cdf_float = torch.tensor([0., 1/3, 2/3, 1.], dtype=torch.float32).reshape(1, -1) 8 | assert list(_encode_decode(cdf_float, [10], 9 | needs_normalization=False, 10 | check_input_bounds=False)) == [False] 11 | 12 | 13 | def test_uniform_float(): 14 | cdf_float = torch.tensor([0., 1/3, 2/3, 1.], dtype=torch.float32).reshape(1, -1) 15 | 16 | # Check if integer conversion works as expected. 17 | cdf_int = torchac._convert_to_int_and_normalize(cdf_float, 18 | needs_normalization=False) 19 | assert cdf_int[0, 1] == 2**16//3 20 | assert cdf_int[0, -1] == 0 21 | 22 | # Check if we can uniquely encode without normalization. 23 | assert all(_encode_decode(cdf_float, 24 | symbols_to_check=(0, 1, 2), 25 | needs_normalization=False)) 26 | 27 | 28 | def test_uniform_float_multipdim(): 29 | cdf_float = torch.tensor([0., 1/3, 2/3, 1.], dtype=torch.float32).reshape(1, -1) 30 | 31 | L = 3 32 | C, H, W = 5, 8, 9 33 | 34 | Lp = L + 1 35 | cdf_float = torch.cat([cdf_float for _ in range(C*H*W)], dim=0) 36 | cdf_float = cdf_float.reshape(C, H, W, -1) 37 | assert cdf_float.shape[-1] == Lp 38 | 39 | sym = torch.arange(C * H * W, dtype=torch.int16) % L 40 | sym = sym.reshape(C, H, W) 41 | 42 | byte_stream = torchac.encode_float_cdf( 43 | cdf_float, 44 | sym, 45 | needs_normalization=False, 46 | check_input_bounds=True) 47 | sym_out = torchac.decode_float_cdf( 48 | cdf_float, 49 | byte_stream, 50 | needs_normalization=False) 51 | assert sym_out.equal(sym) 52 | 53 | 54 | def test_normalize_float(): 55 | # Two times the same value -> needs to be normalized! 56 | cdf_float = torch.tensor([0., 1/3, 1/3, 1.], dtype=torch.float32).reshape(1, -1) 57 | # Check if we can uniquely encode 58 | assert all(_encode_decode(cdf_float, 59 | symbols_to_check=(0, 1, 2), 60 | needs_normalization=True)) 61 | 62 | # Should raise because symbol is out of bounds. 63 | with pytest.raises(ValueError): 64 | sym = torch.tensor([3], dtype=torch.int16) 65 | torchac.encode_float_cdf(cdf_float, sym, 66 | needs_normalization=True, 67 | check_input_bounds=True) 68 | 69 | 70 | def test_normalization_sigmoid(): 71 | mu = 0 72 | L = 256 73 | Lp = L + 1 74 | x_for_cdf = torch.linspace(-1, 1, Lp) 75 | # Logistic distribution. 76 | for sigma in [0.001, 0.01, 0.1, 1., 10.]: 77 | cdf_float = torch.sigmoid((x_for_cdf-mu)/sigma) 78 | 79 | # Put it into the expected shape. 80 | cdf_float = cdf_float.reshape(1, -1) 81 | 82 | # Check if we can uniquely decode all valid symbols. 83 | assert all(_encode_decode( 84 | cdf_float, symbols_to_check=range(L), needs_normalization=True)) 85 | 86 | 87 | def _encode_decode(cdf_float, symbols_to_check, 88 | needs_normalization, check_input_bounds=True): 89 | # Check if we can uniquely encode 90 | for symbol in symbols_to_check: 91 | sym = torch.tensor([symbol], dtype=torch.int16) 92 | byte_stream = torchac.encode_float_cdf( 93 | cdf_float, 94 | sym, 95 | needs_normalization=needs_normalization, 96 | check_input_bounds=check_input_bounds) 97 | sym_out = torchac.decode_float_cdf( 98 | cdf_float, 99 | byte_stream, 100 | needs_normalization=needs_normalization) 101 | yield sym_out == sym 102 | -------------------------------------------------------------------------------- /torchac/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from torchac.torchac import encode_float_cdf 3 | from torchac.torchac import decode_float_cdf 4 | from torchac.torchac import encode_int16_normalized_cdf 5 | from torchac.torchac import decode_int16_normalized_cdf 6 | -------------------------------------------------------------------------------- /torchac/backend/torchac_backend.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * COPYRIGHT 2020 ETH Zurich 3 | * BASED on 4 | * 5 | * https://marknelson.us/posts/2014/10/19/data-compression-with-arithmetic-coding.html 6 | */ 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | #include 21 | 22 | 23 | using cdf_t = uint16_t; 24 | 25 | /** Encapsulates a pointer to a CDF tensor */ 26 | struct cdf_ptr { 27 | const cdf_t* data; // expected to be a N_sym x Lp matrix, stored in row major. 28 | const int N_sym; // Number of symbols stored by `data`. 29 | const int Lp; // == L+1, where L is the number of possible values a symbol can take. 30 | cdf_ptr(const cdf_t* data, 31 | const int N_sym, 32 | const int Lp) : data(data), N_sym(N_sym), Lp(Lp) {}; 33 | }; 34 | 35 | /** Class to save output bit by bit to a byte string */ 36 | class OutCacheString { 37 | private: 38 | public: 39 | std::string out=""; 40 | uint8_t cache=0; 41 | uint8_t count=0; 42 | void append(const int bit) { 43 | cache <<= 1; 44 | cache |= bit; 45 | count += 1; 46 | if (count == 8) { 47 | out.append(reinterpret_cast(&cache), 1); 48 | count = 0; 49 | } 50 | } 51 | void flush() { 52 | if (count > 0) { 53 | for (int i = count; i < 8; ++i) { 54 | append(0); 55 | } 56 | assert(count==0); 57 | } 58 | } 59 | void append_bit_and_pending(const int bit, uint64_t &pending_bits) { 60 | append(bit); 61 | while (pending_bits > 0) { 62 | append(!bit); 63 | pending_bits -= 1; 64 | } 65 | } 66 | }; 67 | 68 | /** Class to read byte string bit by bit */ 69 | class InCacheString { 70 | private: 71 | const std::string& in_; 72 | 73 | public: 74 | explicit InCacheString(const std::string& in) : in_(in) {}; 75 | 76 | uint8_t cache=0; 77 | uint8_t cached_bits=0; 78 | size_t in_ptr=0; 79 | 80 | void get(uint32_t& value) { 81 | if (cached_bits == 0) { 82 | if (in_ptr == in_.size()){ 83 | value <<= 1; 84 | return; 85 | } 86 | /// Read 1 byte 87 | cache = (uint8_t) in_[in_ptr]; 88 | in_ptr++; 89 | cached_bits = 8; 90 | } 91 | value <<= 1; 92 | value |= (cache >> (cached_bits - 1)) & 1; 93 | cached_bits--; 94 | } 95 | 96 | void initialize(uint32_t& value) { 97 | for (int i = 0; i < 32; ++i) { 98 | get(value); 99 | } 100 | } 101 | }; 102 | 103 | const void check_sym(const torch::Tensor& sym) { 104 | TORCH_CHECK(sym.sizes().size() == 1, 105 | "Invalid size for sym. Expected just 1 dim.") 106 | } 107 | 108 | /** Get an instance of the `cdf_ptr` struct. */ 109 | const struct cdf_ptr get_cdf_ptr(const torch::Tensor& cdf) 110 | { 111 | TORCH_CHECK(!cdf.is_cuda(), "cdf must be on CPU!") 112 | const auto s = cdf.sizes(); 113 | TORCH_CHECK(s.size() == 2, "Invalid size for cdf! Expected (N, Lp)") 114 | 115 | const int N_sym = s[0]; 116 | const int Lp = s[1]; 117 | const auto cdf_acc = cdf.accessor(); 118 | const cdf_t* cdf_ptr = (uint16_t*)cdf_acc.data(); 119 | 120 | const struct cdf_ptr res(cdf_ptr, N_sym, Lp); 121 | return res; 122 | } 123 | 124 | 125 | // ----------------------------------------------------------------------------- 126 | 127 | 128 | /** Encode symbols `sym` with CDF represented by `cdf_ptr`. NOTE: this is not exposted to python. */ 129 | py::bytes encode( 130 | const cdf_ptr& cdf_ptr, 131 | const torch::Tensor& sym){ 132 | 133 | OutCacheString out_cache; 134 | 135 | uint32_t low = 0; 136 | uint32_t high = 0xFFFFFFFFU; 137 | uint64_t pending_bits = 0; 138 | 139 | const int precision = 16; 140 | 141 | const cdf_t* cdf = cdf_ptr.data; 142 | const int N_sym = cdf_ptr.N_sym; 143 | const int Lp = cdf_ptr.Lp; 144 | const int max_symbol = Lp - 2; 145 | 146 | auto sym_ = sym.accessor(); 147 | 148 | for (int i = 0; i < N_sym; ++i) { 149 | const int16_t sym_i = sym_[i]; 150 | 151 | const uint64_t span = static_cast(high) - static_cast(low) + 1; 152 | 153 | const int offset = i * Lp; 154 | // Left boundary is at offset + sym_i 155 | const uint32_t c_low = cdf[offset + sym_i]; 156 | // Right boundary is at offset + sym_i + 1, except for the `max_symbol` 157 | // For which we hardcode the maxvalue. So if e.g. 158 | // L == 4, it means that Lp == 5, and the allowed symbols are 159 | // {0, 1, 2, 3}. The max symbol is thus Lp - 2 == 3. It's probability 160 | // is then given by c_max - cdf[-2]. 161 | const uint32_t c_high = sym_i == max_symbol ? 0x10000U : cdf[offset + sym_i + 1]; 162 | 163 | high = (low - 1) + ((span * static_cast(c_high)) >> precision); 164 | low = (low) + ((span * static_cast(c_low)) >> precision); 165 | 166 | while (true) { 167 | if (high < 0x80000000U) { 168 | out_cache.append_bit_and_pending(0, pending_bits); 169 | low <<= 1; 170 | high <<= 1; 171 | high |= 1; 172 | } else if (low >= 0x80000000U) { 173 | out_cache.append_bit_and_pending(1, pending_bits); 174 | low <<= 1; 175 | high <<= 1; 176 | high |= 1; 177 | } else if (low >= 0x40000000U && high < 0xC0000000U) { 178 | pending_bits++; 179 | low <<= 1; 180 | low &= 0x7FFFFFFF; 181 | high <<= 1; 182 | high |= 0x80000001; 183 | } else { 184 | break; 185 | } 186 | } 187 | } 188 | 189 | pending_bits += 1; 190 | 191 | if (pending_bits) { 192 | if (low < 0x40000000U) { 193 | out_cache.append_bit_and_pending(0, pending_bits); 194 | } else { 195 | out_cache.append_bit_and_pending(1, pending_bits); 196 | } 197 | } 198 | 199 | out_cache.flush(); 200 | 201 | #ifdef VERBOSE 202 | std::chrono::steady_clock::time_point end= std::chrono::steady_clock::now(); 203 | std::cout << "Time difference (sec) = " << (std::chrono::duration_cast(end - begin).count()) /1000000.0 <((left + right) / 2); 234 | const auto v = cdf[offset + m]; 235 | if (v < target) { 236 | left = m; 237 | } else if (v > target) { 238 | right = m; 239 | } else { 240 | return m; 241 | } 242 | } 243 | 244 | return left; 245 | } 246 | 247 | 248 | torch::Tensor decode( 249 | const cdf_ptr& cdf_ptr, 250 | const std::string& in) { 251 | 252 | #ifdef VERBOSE 253 | std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); 254 | #endif 255 | 256 | const cdf_t* cdf = cdf_ptr.data; 257 | const int N_sym = cdf_ptr.N_sym; // To know the # of syms to decode. Is encoded in the stream! 258 | const int Lp = cdf_ptr.Lp; // To calculate offset 259 | const int max_symbol = Lp - 2; 260 | 261 | // 16 bit! 262 | auto out = torch::empty({N_sym}, torch::kShort); 263 | auto out_ = out.accessor(); 264 | 265 | uint32_t low = 0; 266 | uint32_t high = 0xFFFFFFFFU; 267 | uint32_t value = 0; 268 | const uint32_t c_count = 0x10000U; 269 | const int precision = 16; 270 | 271 | InCacheString in_cache(in); 272 | in_cache.initialize(value); 273 | 274 | for (int i = 0; i < N_sym; ++i) { 275 | const uint64_t span = static_cast(high) - static_cast(low) + 1; 276 | // always < 0x10000 ??? 277 | const uint16_t count = ((static_cast(value) - static_cast(low) + 1) * c_count - 1) / span; 278 | 279 | const int offset = i * Lp; 280 | auto sym_i = binsearch(cdf, count, (cdf_t)max_symbol, offset); 281 | 282 | out_[i] = (int16_t)sym_i; 283 | 284 | if (i == N_sym-1) { 285 | break; 286 | } 287 | 288 | const uint32_t c_low = cdf[offset + sym_i]; 289 | const uint32_t c_high = sym_i == max_symbol ? 0x10000U : cdf[offset + sym_i + 1]; 290 | 291 | high = (low - 1) + ((span * static_cast(c_high)) >> precision); 292 | low = (low) + ((span * static_cast(c_low)) >> precision); 293 | 294 | while (true) { 295 | if (low >= 0x80000000U || high < 0x80000000U) { 296 | low <<= 1; 297 | high <<= 1; 298 | high |= 1; 299 | in_cache.get(value); 300 | } else if (low >= 0x40000000U && high < 0xC0000000U) { 301 | /** 302 | * 0100 0000 ... <= value < 1100 0000 ... 303 | * <=> 304 | * 0100 0000 ... <= value <= 1011 1111 ... 305 | * <=> 306 | * value starts with 01 or 10. 307 | * 01 - 01 == 00 | 10 - 01 == 01 308 | * i.e., with shifts 309 | * 01A -> 0A or 10A -> 1A, i.e., discard 2SB as it's all the same while we are in 310 | * near convergence 311 | */ 312 | low <<= 1; 313 | low &= 0x7FFFFFFFU; // make MSB 0 314 | high <<= 1; 315 | high |= 0x80000001U; // add 1 at the end, retain MSB = 1 316 | value -= 0x40000000U; 317 | in_cache.get(value); 318 | } else { 319 | break; 320 | } 321 | } 322 | } 323 | 324 | #ifdef VERBOSE 325 | std::chrono::steady_clock::time_point end= std::chrono::steady_clock::now(); 326 | std::cout << "Time difference (sec) = " << (std::chrono::duration_cast(end - begin).count()) /1000000.0 <=0.!') 39 | if cdf_float.max() > 1: 40 | raise ValueError(f'cdf_float.max() == {cdf_float.max()}, should be <=1.!') 41 | Lp = cdf_float.shape[-1] 42 | if sym.max() >= Lp - 1: 43 | raise ValueError 44 | cdf_int = _convert_to_int_and_normalize(cdf_float, needs_normalization) 45 | return encode_int16_normalized_cdf(cdf_int, sym) 46 | 47 | 48 | def decode_float_cdf(cdf_float, byte_stream, needs_normalization=True): 49 | """Encode symbols in `byte_stream` with potentially unnormalized float CDF. 50 | 51 | Check the README for more details. 52 | 53 | :param cdf_float: CDF tensor, float32, on CPU. Shape (N1, ..., Nm, Lp). 54 | :param byte_stream: byte-stream, encoding some symbols `sym`. 55 | :param needs_normalization: if True, assume `cdf_float` is un-normalized and 56 | needs normalization. Otherwise only convert it, without normalizing. 57 | 58 | :return: decoded `sym` of shape (N1, ..., Nm). 59 | """ 60 | cdf_int = _convert_to_int_and_normalize(cdf_float, needs_normalization) 61 | return decode_int16_normalized_cdf(cdf_int, byte_stream) 62 | 63 | 64 | def encode_int16_normalized_cdf(cdf_int, sym): 65 | """Encode symbols `sym` with a normalized integer cdf `cdf_int`. 66 | 67 | Check the README for more details. 68 | 69 | :param cdf_int: CDF tensor, int16, on CPU. Shape (N1, ..., Nm, Lp). 70 | :param sym: The symbols to encode, int16, on CPU. Shape (N1, ..., Nm). 71 | 72 | :return: byte-string, encoding `sym` 73 | """ 74 | cdf_int, sym = _check_and_reshape_inputs(cdf_int, sym) 75 | return torchac_backend.encode_cdf(cdf_int, sym) 76 | 77 | 78 | def decode_int16_normalized_cdf(cdf_int, byte_stream): 79 | """Decode symbols in `byte_stream` with a normalized integer cdf `cdf_int`. 80 | 81 | Check the README for more details. 82 | 83 | :param cdf_int: CDF tensor, int16, on CPU. Shape (N1, ..., Nm, Lp). 84 | :param byte_stream: byte-stream, encoding some symbols `sym`. 85 | 86 | :return: decoded `sym` of shape (N1, ..., Nm). 87 | """ 88 | cdf_reshaped = _check_and_reshape_inputs(cdf_int) 89 | # Merge the m dimensions into one. 90 | sym = torchac_backend.decode_cdf(cdf_reshaped, byte_stream) 91 | return _reshape_output(cdf_int.shape, sym) 92 | 93 | 94 | def _check_and_reshape_inputs(cdf, sym=None): 95 | """Check device, dtype, and shapes.""" 96 | if cdf.is_cuda: 97 | raise ValueError('CDF must be on CPU') 98 | if sym is not None and sym.is_cuda: 99 | raise ValueError('Symbols must be on CPU') 100 | if sym is not None and sym.dtype != torch.int16: 101 | raise ValueError('Symbols must be int16!') 102 | if sym is not None: 103 | if len(cdf.shape) != len(sym.shape) + 1 or cdf.shape[:-1] != sym.shape: 104 | raise ValueError(f'Invalid shapes of cdf={cdf.shape}, sym={sym.shape}! ' 105 | 'The first m elements of cdf.shape must be equal to ' 106 | 'sym.shape, and cdf should only have one more dimension.') 107 | Lp = cdf.shape[-1] 108 | cdf = cdf.reshape(-1, Lp) 109 | if sym is None: 110 | return cdf 111 | sym = sym.reshape(-1) 112 | return cdf, sym 113 | 114 | 115 | def _reshape_output(cdf_shape, sym): 116 | """Reshape single dimension `sym` back to the correct spatial dimensions.""" 117 | spatial_dimensions = cdf_shape[:-1] 118 | if len(sym) != np.prod(spatial_dimensions): 119 | raise ValueError() 120 | return sym.reshape(*spatial_dimensions) 121 | 122 | 123 | def _convert_to_int_and_normalize(cdf_float, needs_normalization): 124 | """Convert floatingpoint CDF to integers. See README for more info. 125 | 126 | The idea is the following: 127 | When we get the cdf here, it is (assumed to be) between 0 and 1, i.e, 128 | cdf \in [0, 1) 129 | (note that 1 should not be included.) 130 | We now want to convert this to int16 but make sure we do not get 131 | the same value twice, as this would break the arithmetic coder 132 | (you need a strictly monotonically increasing function). 133 | So, if needs_normalization==True, we multiply the input CDF 134 | with 2**16 - (Lp - 1). This means that now, 135 | cdf \in [0, 2**16 - (Lp - 1)]. 136 | Then, in a final step, we add an arange(Lp), which is just a line with 137 | slope one. This ensure that for sure, we will get unique, strictly 138 | monotonically increasing CDFs, which are \in [0, 2**16) 139 | """ 140 | Lp = cdf_float.shape[-1] 141 | factor = torch.tensor( 142 | 2, dtype=torch.float32, device=cdf_float.device).pow_(PRECISION) 143 | new_max_value = factor 144 | if needs_normalization: 145 | new_max_value = new_max_value - (Lp - 1) 146 | cdf_float = cdf_float.mul(new_max_value) 147 | cdf_float = cdf_float.round() 148 | cdf = cdf_float.to(dtype=torch.int16, non_blocking=True) 149 | if needs_normalization: 150 | r = torch.arange(Lp, dtype=torch.int16, device=cdf.device) 151 | cdf.add_(r) 152 | return cdf 153 | --------------------------------------------------------------------------------