Commit 9e459ea3 authored by jerrrrry's avatar jerrrrry
Browse files

Initial commit

parents
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Our framework is based on CompressAI(https://github.com/InterDigitalInc/CompressAI).
We modify following files for usage.
/examples/train.py
/compressai/utils/eval_model/__main__.py
/compressai/utils/update_model/__main__.py
/compressai/zoo/image.py
/compressai/zoo/__init__.py
We add following files for our model.
/compressai/models/ours.py
/compressai/models/our_utils.py
=======================================================================
CompressAI's Apache License
=======================================================================
This repo contains CompressAI code, which was previously licensed under
Apache License Version 2.0:
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
\ No newline at end of file
# InvCompress
Official Pytorch Implementation for "Enhanced Invertible Encoding for Learned Image Compression", ACMMM 2021 (Oral)
![](./figures/overview.png)
**Figure:** *Our framework*
## Acknowledgement
The framework is based on [CompressAI](https://github.com/InterDigitalInc/CompressAI), we add our model in compressai.models.ours, compressai.models.our_utils. We modify compressai.utils, compressai.zoo, compressai.layers and examples/train.py for usage.
Part of the codes benefit from [Invertible-Image-Rescaling](https://github.com/pkuxmq/Invertible-Image-Rescaling).
## Introduction
In this paper, we target at structuring a better transformation between the image space and the latent feature space. Instead of employing previous autoencoder style networks to build this transformation, we propose an enhanced Invertible Encoding Network with invertible neural networks (INNs) to largely mitigate the information loss problem for better compression. To solve the challenge of unstable training with INN, we propose an attentive channel squeeze layer to flexibly adjust the feature dimension for a lower bit rate. We also present a feature enhancement module with same-resolution transforms and residual connections to improve the network nonlinear representation capacity.
[[Paper](https://arxiv.org/abs/2108.03690)]
![](./figures/result.png)
**Figure:** *Our results*
## Installation
As mentioned in [CompressAI](https://github.com/InterDigitalInc/CompressAI), "A C++17 compiler, a recent version of pip (19.0+), and common python packages are also required (see setup.py for the full list)."
```bash
git clone https://github.com/xyq7/InvCompress.git
cd InvCompress/codes/
conda create -n invcomp python=3.7
conda activate invcomp
pip install -U pip && pip install -e .
conda install -c conda-forge tensorboard
```
### Evaluation
If you want evaluate with pretrained model, please download from [Google drive](https://drive.google.com/file/d/1m35JFz00V7UUGQFjx6szfyDNvI2weAMW/view?usp=sharing) or [Baidu cloud](https://pan.baidu.com/s/14y1FA4qQ3pEB4KHUZE79RQ) (code: dfsz) and put in ./experiments/
Some evaluation dataset can be downloaded from
[kodak dataset](http://r0k.us/graphics/kodak/), [CLIC](http://challenge.compression.cc/tasks/), and [Tecnick](https://sourceforge.net/projects/testimages/files/OLD/OLD_SAMPLING/testimages.zip)
Note that as mentioned in original [CompressAI](https://github.com/InterDigitalInc/CompressAI), "Inference on GPU is not recommended for the autoregressive models (the entropy coder is run sequentially on CPU)." So for inference of our model, please run on CPU.
```bash
python -m compressai.utils.eval_model checkpoint $eval_data_dir -a invcompress -exp $exp_name -s $save_dir
```
An example: to evaluate model of quality 1 optimized with mse on kodak dataset.
```bash
python -m compressai.utils.eval_model checkpoint ../data/kodak -a invcompress -exp exp_01_mse_q1 -s ../results/exp_01
```
If you want to evaluate your trained model on own data, please run update before evaluation. An example:
```bash
python -m compressai.utils.update_model -exp $exp_name -a invcompress
python -m compressai.utils.eval_model checkpoint $eval_data_dir -a invcompress -exp $exp_name -s $save_dir
```
### Train
We use the training dataset processed in the [repo](https://github.com/liujiaheng/CompressionData). We further preprocess with /codes/scripts/flicker_process.py
Training setting is detailed in the paper. You can also use your own data for training.
```bash
python examples/train.py -exp $exp_name -m invcompress -d $train_data_dir --epochs $epoch_num -lr $lr --batch-size $batch_size --cuda --gpu_id $gpu_id --lambda $lamvda --metrics $metric --save
```
An example: to train model of quality 1 optimized with mse metric.
```bash
python examples/train.py -exp exp_01_mse_q1 -m invcompress -d ../data/flicker --epochs 600 -lr 1e-4 --batch-size 8 --cuda --gpu_id 0 --lambda 0.0016 --metrics mse --save
```
Other usage please refer to the original library [CompressAI](https://github.com/InterDigitalInc/CompressAI)
## Citation
If you find this work useful for your research, please cite:
```
@inproceedings{xie2021enhanced,
title = {Enhanced Invertible Encoding for Learned Image Compression},
author = {Yueqi Xie and Ka Leong Cheng and Qifeng Chen},
booktitle = {Proceedings of the ACM International Conference on Multimedia},
pages = {162--170},
year = {2021}
}
```
## Contact
Feel free to contact us if there is any question. (YueqiXIE, yxieay@connect.ust.hk; Ka Leong Cheng, klchengad@connect.ust.hk)
# Contributing
If you want to contribute bug-fixes please directly file a pull-request. If you
plan to introduce new features or extend CompressAI, please first open an issue
to start a public discussion or contact us directly.
## Coding style
We try to follow PEP 8 recommendations. Automatic formatting is performed via
[black](https://github.com/google/yapf://github.com/psf/black) and
[isort](https://github.com/timothycrosley/isort/).
## Testing
We use [pytest](https://docs.pytest.org/en/5.4.3/getting-started.html). To run
all the tests:
* `pip install pytest pytest-cov coverage`
* `python -m pytest --cov=compressai -s`
* You can run `coverage report` or `coverage html` to visualize the tests
coverage analysis
## Documentation
See `docs/Readme.md` for more information.
## Licence
By contributing to CompressAI, you agree that your contributions will be
licensed under the same license as described in the LICENSE file at the root of
this repository.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
include LICENSE
include requirements.txt
recursive-include compressai *.cpp *.hpp
recursive-include third_party *.h
PYTORCH_DOCKER_IMAGE = pytorch/pytorch:1.6.0-cuda10.1-cudnn7
PYTHON_DOCKER_IMAGE = python:3.8-buster
GIT_DESCRIBE = $(shell git describe --first-parent)
ARCHIVE = compressai.tar.gz
.PHONY: help
help:
@echo 'Docker targets:'
@echo ' docker - based on latest pytorch image (with GPU support)'
@echo ' docker-cpu - based on latest python3 image (smaller image without GPU support)'
.PHONY: docker
docker:
@git archive --format=tar.gz HEAD > docker/${ARCHIVE}
@cd docker && \
docker build \
--build-arg PYTORCH_IMAGE=${PYTORCH_DOCKER_IMAGE} \
--build-arg WITH_JUPYTER=0 \
--progress=auto \
-t compressai:${GIT_DESCRIBE} .
@rm docker/${ARCHIVE}
.PHONY: docker-cpu
docker-cpu:
@git archive --format=tar.gz HEAD > docker/${ARCHIVE}
@cd docker && \
docker build \
-f Dockerfile.cpu \
--build-arg BASE_IMAGE=${PYTHON_DOCKER_IMAGE} \
--build-arg WITH_JUPYTER=0 \
--progress=auto \
-t compressai:${GIT_DESCRIBE}-cpu .
@rm docker/${ARCHIVE}
2021-01-26: Experimental multi-GPU support
* `aux_parameters` was dropped to support data parallel
* see the updated example/train.py
* use `load_pretrained` to convert `state_dict`s to the new format
2020-06-21: First release of CompressAI !
# Copyright 2020 InterDigital Communications, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from compressai import datasets, entropy_models, layers, models, ops
try:
from .version import __version__
except ImportError:
pass
_entropy_coder = "ans"
_available_entropy_coders = [_entropy_coder]
try:
import range_coder
_available_entropy_coders.append("rangecoder")
except ImportError:
pass
def set_entropy_coder(entropy_coder):
"""
Specifies the default entropy coder used to encode the bit-streams.
Use :mod:`available_entropy_coders` to list the possible values.
Args:
entropy_coder (string): Name of the entropy coder
"""
global _entropy_coder # pylint: disable=W0603
if entropy_coder not in _available_entropy_coders:
raise ValueError(
f'Invalid entropy coder "{entropy_coder}", choose from'
f'({", ".join(_available_entropy_coders)}).'
)
_entropy_coder = entropy_coder
def get_entropy_coder():
"""
Return the name of the default entropy coder used to encode the bit-streams.
"""
return _entropy_coder
def available_entropy_coders():
"""
Return the list of available entropy coders.
"""
return _available_entropy_coders
/* Copyright 2020 InterDigital Communications, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <algorithm>
#include <cmath>
#include <numeric>
#include <vector>
std::vector<uint32_t> pmf_to_quantized_cdf(const std::vector<float> &pmf,
int precision) {
/* NOTE(begaintj): ported from `ryg_rans` public implementation. Not optimal
* although it's only run once per model after training. See TF/compression
* implementation for an optimized version. */
std::vector<uint32_t> cdf(pmf.size() + 1);
cdf[0] = 0; /* freq 0 */
std::transform(pmf.begin(), pmf.end(), cdf.begin() + 1,
[=](float p) { return std::round(p * (1 << precision)); });
const uint32_t total = std::accumulate(cdf.begin(), cdf.end(), 0);
std::transform(cdf.begin(), cdf.end(), cdf.begin(),
[precision, total](uint32_t p) {
return ((static_cast<uint64_t>(1 << precision) * p) / total);
});
std::partial_sum(cdf.begin(), cdf.end(), cdf.begin());
cdf.back() = 1 << precision;
for (int i = 0; i < static_cast<int>(cdf.size() - 1); ++i) {
if (cdf[i] == cdf[i + 1]) {
/* Try to steal frequency from low-frequency symbols */
uint32_t best_freq = ~0u;
int best_steal = -1;
for (int j = 0; j < static_cast<int>(cdf.size()) - 1; ++j) {
uint32_t freq = cdf[j + 1] - cdf[j];
if (freq > 1 && freq < best_freq) {
best_freq = freq;
best_steal = j;
}
}
assert(best_steal != -1);
if (best_steal < i) {
for (int j = best_steal + 1; j <= i; ++j) {
cdf[j]--;
}
} else {
assert(best_steal > i);
for (int j = i + 1; j <= best_steal; ++j) {
cdf[j]++;
}
}
}
}
assert(cdf[0] == 0);
assert(cdf.back() == (1 << precision));
for (int i = 0; i < static_cast<int>(cdf.size()) - 1; ++i) {
assert(cdf[i + 1] > cdf[i]);
}
return cdf;
}
PYBIND11_MODULE(_CXX, m) {
m.attr("__name__") = "compressai._CXX";
m.doc() = "C++ utils";
m.def("pmf_to_quantized_cdf", &pmf_to_quantized_cdf,
"Return quantized CDF for a given PMF");
}
/* Copyright 2020 InterDigital Communications, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Rans64 extensions from:
* https://fgiesen.wordpress.com/2015/12/21/rans-in-practice/
* Unbounded range coding from:
* https://github.com/tensorflow/compression/blob/master/tensorflow_compression/cc/kernels/unbounded_index_range_coding_kernels.cc
**/
#include "rans_interface.hpp"
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <algorithm>
#include <array>
#include <cassert>
#include <numeric>
#include <stdexcept>
#include <string>
#include <vector>
#include "rans64.h"
namespace py = pybind11;
/* probability range, this could be a parameter... */
constexpr int precision = 16;
constexpr uint16_t bypass_precision = 4; /* number of bits in bypass mode */
constexpr uint16_t max_bypass_val = (1 << bypass_precision) - 1;
namespace {
/* We only run this in debug mode as its costly... */
void assert_cdfs(const std::vector<std::vector<int>> &cdfs,
const std::vector<int> &cdfs_sizes) {
for (int i = 0; i < static_cast<int>(cdfs.size()); ++i) {
assert(cdfs[i][0] == 0);
assert(cdfs[i][cdfs_sizes[i] - 1] == (1 << precision));
for (int j = 0; j < cdfs_sizes[i] - 1; ++j) {
assert(cdfs[i][j + 1] > cdfs[i][j]);
}
}
}
/* Support only 16 bits word max */
inline void Rans64EncPutBits(Rans64State *r, uint32_t **pptr, uint32_t val,
uint32_t nbits) {
assert(nbits <= 16);
assert(val < (1u << nbits));
/* Re-normalize */
uint64_t x = *r;
uint32_t freq = 1 << (16 - nbits);
uint64_t x_max = ((RANS64_L >> 16) << 32) * freq;
if (x >= x_max) {
*pptr -= 1;
**pptr = (uint32_t)x;
x >>= 32;
Rans64Assert(x < x_max);
}
/* x = C(s, x) */
*r = (x << nbits) | val;
}
inline uint32_t Rans64DecGetBits(Rans64State *r, uint32_t **pptr,
uint32_t n_bits) {
uint64_t x = *r;
uint32_t val = x & ((1u << n_bits) - 1);
/* Re-normalize */
x = x >> n_bits;
if (x < RANS64_L) {
x = (x << 32) | **pptr;
*pptr += 1;
Rans64Assert(x >= RANS64_L);
}
*r = x;
return val;
}
} // namespace
void BufferedRansEncoder::encode_with_indexes(
const std::vector<int32_t> &symbols, const std::vector<int32_t> &indexes,
const std::vector<std::vector<int32_t>> &cdfs,
const std::vector<int32_t> &cdfs_sizes,
const std::vector<int32_t> &offsets) {
assert(cdfs.size() == cdfs_sizes.size());
assert_cdfs(cdfs, cdfs_sizes);
// backward loop on symbols from the end;
for (size_t i = 0; i < symbols.size(); ++i) {
const int32_t cdf_idx = indexes[i];
assert(cdf_idx >= 0);
assert(cdf_idx < cdfs.size());
const auto &cdf = cdfs[cdf_idx];
const int32_t max_value = cdfs_sizes[cdf_idx] - 2;
assert(max_value >= 0);
assert((max_value + 1) < cdf.size());
int32_t value = symbols[i] - offsets[cdf_idx];
uint32_t raw_val = 0;
if (value < 0) {
raw_val = -2 * value - 1;
value = max_value;
} else if (value >= max_value) {
raw_val = 2 * (value - max_value);
value = max_value;
}
assert(value >= 0);
assert(value < cdfs_sizes[cdf_idx] - 1);
_syms.push_back({static_cast<uint16_t>(cdf[value]),
static_cast<uint16_t>(cdf[value + 1] - cdf[value]),
false});
/* Bypass coding mode (value == max_value -> sentinel flag) */
if (value == max_value) {
/* Determine the number of bypasses (in bypass_precision size) needed to
* encode the raw value. */
int32_t n_bypass = 0;
while ((raw_val >> (n_bypass * bypass_precision)) != 0) {
++n_bypass;
}
/* Encode number of bypasses */
int32_t val = n_bypass;
while (val >= max_bypass_val) {
_syms.push_back({max_bypass_val, max_bypass_val + 1, true});
val -= max_bypass_val;
}
_syms.push_back(
{static_cast<uint16_t>(val), static_cast<uint16_t>(val + 1), true});
/* Encode raw value */
for (int32_t j = 0; j < n_bypass; ++j) {
const int32_t val =
(raw_val >> (j * bypass_precision)) & max_bypass_val;
_syms.push_back(
{static_cast<uint16_t>(val), static_cast<uint16_t>(val + 1), true});
}
}
}
}
py::bytes BufferedRansEncoder::flush() {
Rans64State rans;
Rans64EncInit(&rans);
std::vector<uint32_t> output(_syms.size(), 0xCC); // too much space ?
uint32_t *ptr = output.data() + output.size();
assert(ptr != nullptr);
while (!_syms.empty()) {
const RansSymbol sym = _syms.back();
if (!sym.bypass) {
Rans64EncPut(&rans, &ptr, sym.start, sym.range, precision);
} else {
// unlikely...
Rans64EncPutBits(&rans, &ptr, sym.start, bypass_precision);
}
_syms.pop_back();
}
Rans64EncFlush(&rans, &ptr);
const int nbytes =
std::distance(ptr, output.data() + output.size()) * sizeof(uint32_t);
return std::string(reinterpret_cast<char *>(ptr), nbytes);
}
py::bytes
RansEncoder::encode_with_indexes(const std::vector<int32_t> &symbols,
const std::vector<int32_t> &indexes,
const std::vector<std::vector<int32_t>> &cdfs,
const std::vector<int32_t> &cdfs_sizes,
const std::vector<int32_t> &offsets) {
BufferedRansEncoder buffered_rans_enc;
buffered_rans_enc.encode_with_indexes(symbols, indexes, cdfs, cdfs_sizes,
offsets);
return buffered_rans_enc.flush();
}
std::vector<int32_t>
RansDecoder::decode_with_indexes(const std::string &encoded,
const std::vector<int32_t> &indexes,
const std::vector<std::vector<int32_t>> &cdfs,
const std::vector<int32_t> &cdfs_sizes,
const std::vector<int32_t> &offsets) {
assert(cdfs.size() == cdfs_sizes.size());
assert_cdfs(cdfs, cdfs_sizes);
std::vector<int32_t> output(indexes.size());
Rans64State rans;
uint32_t *ptr = (uint32_t *)encoded.data();
assert(ptr != nullptr);
Rans64DecInit(&rans, &ptr);
for (int i = 0; i < static_cast<int>(indexes.size()); ++i) {
const int32_t cdf_idx = indexes[i];
assert(cdf_idx >= 0);
assert(cdf_idx < cdfs.size());
const auto &cdf = cdfs[cdf_idx];
const int32_t max_value = cdfs_sizes[cdf_idx] - 2;
assert(max_value >= 0);
assert((max_value + 1) < cdf.size());
const int32_t offset = offsets[cdf_idx];
const uint32_t cum_freq = Rans64DecGet(&rans, precision);
const auto cdf_end = cdf.begin() + cdfs_sizes[cdf_idx];
const auto it = std::find_if(cdf.begin(), cdf_end,
[cum_freq](int v) { return v > cum_freq; });
assert(it != cdf_end + 1);
const uint32_t s = std::distance(cdf.begin(), it) - 1;
Rans64DecAdvance(&rans, &ptr, cdf[s], cdf[s + 1] - cdf[s], precision);
int32_t value = static_cast<int32_t>(s);
if (value == max_value) {
/* Bypass decoding mode */
int32_t val = Rans64DecGetBits(&rans, &ptr, bypass_precision);
int32_t n_bypass = val;
while (val == max_bypass_val) {
val = Rans64DecGetBits(&rans, &ptr, bypass_precision);
n_bypass += val;
}
int32_t raw_val = 0;
for (int j = 0; j < n_bypass; ++j) {
val = Rans64DecGetBits(&rans, &ptr, bypass_precision);
assert(val <= max_bypass_val);
raw_val |= val << (j * bypass_precision);
}
value = raw_val >> 1;
if (raw_val & 1) {
value = -value - 1;
} else {
value += max_value;
}
}
output[i] = value + offset;
}
return output;
}
void RansDecoder::set_stream(const std::string &encoded) {
_stream = encoded;
uint32_t *ptr = (uint32_t *)_stream.data();
assert(ptr != nullptr);
_ptr = ptr;
Rans64DecInit(&_rans, &_ptr);
}
std::vector<int32_t>
RansDecoder::decode_stream(const std::vector<int32_t> &indexes,
const std::vector<std::vector<int32_t>> &cdfs,
const std::vector<int32_t> &cdfs_sizes,
const std::vector<int32_t> &offsets) {
assert(cdfs.size() == cdfs_sizes.size());
assert_cdfs(cdfs, cdfs_sizes);
std::vector<int32_t> output(indexes.size());
assert(_ptr != nullptr);
for (int i = 0; i < static_cast<int>(indexes.size()); ++i) {
const int32_t cdf_idx = indexes[i];
assert(cdf_idx >= 0);
assert(cdf_idx < cdfs.size());
const auto &cdf = cdfs[cdf_idx];
const int32_t max_value = cdfs_sizes[cdf_idx] - 2;
assert(max_value >= 0);
assert((max_value + 1) < cdf.size());
const int32_t offset = offsets[cdf_idx];
const uint32_t cum_freq = Rans64DecGet(&_rans, precision);
const auto cdf_end = cdf.begin() + cdfs_sizes[cdf_idx];
const auto it = std::find_if(cdf.begin(), cdf_end,
[cum_freq](int v) { return v > cum_freq; });
assert(it != cdf_end + 1);
const uint32_t s = std::distance(cdf.begin(), it) - 1;
Rans64DecAdvance(&_rans, &_ptr, cdf[s], cdf[s + 1] - cdf[s], precision);
int32_t value = static_cast<int32_t>(s);
if (value == max_value) {
/* Bypass decoding mode */
int32_t val = Rans64DecGetBits(&_rans, &_ptr, bypass_precision);
int32_t n_bypass = val;
while (val == max_bypass_val) {
val = Rans64DecGetBits(&_rans, &_ptr, bypass_precision);
n_bypass += val;
}
int32_t raw_val = 0;
for (int j = 0; j < n_bypass; ++j) {
val = Rans64DecGetBits(&_rans, &_ptr, bypass_precision);
assert(val <= max_bypass_val);
raw_val |= val << (j * bypass_precision);
}
value = raw_val >> 1;
if (raw_val & 1) {
value = -value - 1;
} else {
value += max_value;
}
}
output[i] = value + offset;
}
return output;
}
PYBIND11_MODULE(ans, m) {
m.attr("__name__") = "compressai.ans";
m.doc() = "range Asymmetric Numeral System python bindings";
py::class_<BufferedRansEncoder>(m, "BufferedRansEncoder")
.def(py::init<>())
.def("encode_with_indexes", &BufferedRansEncoder::encode_with_indexes)
.def("flush", &BufferedRansEncoder::flush);
py::class_<RansEncoder>(m, "RansEncoder")
.def(py::init<>())
.def("encode_with_indexes", &RansEncoder::encode_with_indexes);
py::class_<RansDecoder>(m, "RansDecoder")
.def(py::init<>())
.def("set_stream", &RansDecoder::set_stream)
.def("decode_stream", &RansDecoder::decode_stream)
.def("decode_with_indexes", &RansDecoder::decode_with_indexes,
"Decode a string to a list of symbols");
}
/* Copyright 2020 InterDigital Communications, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "rans64.h"
namespace py = pybind11;
struct RansSymbol {
uint16_t start;
uint16_t range;
bool bypass; // bypass flag to write raw bits to the stream
};
/* NOTE: Warning, we buffer everything for now... In case of large files we
* should split the bitstream into chunks... Or for a memory-bounded encoder
**/
class BufferedRansEncoder {
public:
BufferedRansEncoder() = default;
BufferedRansEncoder(const BufferedRansEncoder &) = delete;
BufferedRansEncoder(BufferedRansEncoder &&) = delete;
BufferedRansEncoder &operator=(const BufferedRansEncoder &) = delete;
BufferedRansEncoder &operator=(BufferedRansEncoder &&) = delete;
void encode_with_indexes(const std::vector<int32_t> &symbols,
const std::vector<int32_t> &indexes,
const std::vector<std::vector<int32_t>> &cdfs,
const std::vector<int32_t> &cdfs_sizes,
const std::vector<int32_t> &offsets);
py::bytes flush();
private:
std::vector<RansSymbol> _syms;
};
class RansEncoder {
public:
RansEncoder() = default;
RansEncoder(const RansEncoder &) = delete;
RansEncoder(RansEncoder &&) = delete;
RansEncoder &operator=(const RansEncoder &) = delete;
RansEncoder &operator=(RansEncoder &&) = delete;
py::bytes encode_with_indexes(const std::vector<int32_t> &symbols,
const std::vector<int32_t> &indexes,
const std::vector<std::vector<int32_t>> &cdfs,
const std::vector<int32_t> &cdfs_sizes,
const std::vector<int32_t> &offsets);
};
class RansDecoder {
public:
RansDecoder() = default;
RansDecoder(const RansDecoder &) = delete;
RansDecoder(RansDecoder &&) = delete;
RansDecoder &operator=(const RansDecoder &) = delete;
RansDecoder &operator=(RansDecoder &&) = delete;
std::vector<int32_t>
decode_with_indexes(const std::string &encoded,
const std::vector<int32_t> &indexes,
const std::vector<std::vector<int32_t>> &cdfs,
const std::vector<int32_t> &cdfs_sizes,
const std::vector<int32_t> &offsets);
void set_stream(const std::string &stream);
std::vector<int32_t>
decode_stream(const std::vector<int32_t> &indexes,
const std::vector<std::vector<int32_t>> &cdfs,
const std::vector<int32_t> &cdfs_sizes,
const std::vector<int32_t> &offsets);
private:
Rans64State _rans;
std::string _stream;
uint32_t *_ptr;
};
# Copyright 2020 InterDigital Communications, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .utils import ImageFolder
__all__ = ["ImageFolder"]
# Copyright 2020 InterDigital Communications, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pathlib import Path
from PIL import Image
from torch.utils.data import Dataset
class ImageFolder(Dataset):
"""Load an image folder database. Training and testing image samples
are respectively stored in separate directories:
.. code-block::
- rootdir/
- train/
- img000.png
- img001.png
- test/
- img000.png
- img001.png
Args:
root (string): root directory of the dataset
transform (callable, optional): a function or transform that takes in a
PIL image and returns a transformed version
split (string): split mode ('train' or 'val')
"""
def __init__(self, root, transform=None, split="train"):
splitdir = Path(root) / split
# splitdir = root
if not splitdir.is_dir():
raise RuntimeError(f'Invalid directory "{root}"')
self.samples = sorted([f for f in splitdir.iterdir() if f.is_file()])
# self.samples = self.samples[0:1]
self.transform = transform
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
img: `PIL.Image.Image` or transformed `PIL.Image.Image`.
"""
img = Image.open(self.samples[index]).convert("RGB")
if self.transform:
return self.transform(img)
return img
def __len__(self):
return len(self.samples)
# Copyright 2020 InterDigital Communications, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .entropy_models import EntropyBottleneck, EntropyModel, GaussianConditional
__all__ = [
"EntropyModel",
"EntropyBottleneck",
"GaussianConditional",
]
This diff is collapsed.
# Copyright 2020 InterDigital Communications, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .gdn import *
from .layers import *
__all__ = [
"GDN",
"GDN1",
"AttentionBlock",
"MaskedConv2d",
"ResidualBlock",
"ResidualBlockUpsample",
"ResidualBlockWithStride",
"conv3x3",
"subpel_conv3x3",
]
# Copyright 2020 InterDigital Communications, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch.nn as nn
import torch.nn.functional as F
from compressai.ops.parametrizers import NonNegativeParametrizer
class GDN(nn.Module):
r"""Generalized Divisive Normalization layer.
Introduced in `"Density Modeling of Images Using a Generalized Normalization
Transformation" <https://arxiv.org/abs/1511.06281>`_,
by Balle Johannes, Valero Laparra, and Eero P. Simoncelli, (2016).
.. math::
y[i] = \frac{x[i]}{\sqrt{\beta[i] + \sum_j(\gamma[j, i] * x[j]^2)}}
"""
def __init__(self, in_channels, inverse=False, beta_min=1e-6, gamma_init=0.1):
super().__init__()
beta_min = float(beta_min)
gamma_init = float(gamma_init)
self.inverse = bool(inverse)
self.beta_reparam = NonNegativeParametrizer(minimum=beta_min)
beta = torch.ones(in_channels)
beta = self.beta_reparam.init(beta)
self.beta = nn.Parameter(beta)
self.gamma_reparam = NonNegativeParametrizer()
gamma = gamma_init * torch.eye(in_channels)
gamma = self.gamma_reparam.init(gamma)
self.gamma = nn.Parameter(gamma)
def forward(self, x):
_, C, _, _ = x.size()
beta = self.beta_reparam(self.beta)
gamma = self.gamma_reparam(self.gamma)
gamma = gamma.reshape(C, C, 1, 1)
norm = F.conv2d(x ** 2, gamma, beta)
if self.inverse:
norm = torch.sqrt(norm)
else:
norm = torch.rsqrt(norm)
out = x * norm
return out
class GDN1(GDN):
r"""Simplified GDN layer.
Introduced in `"Computationally Efficient Neural Image Compression"
<http://arxiv.org/abs/1912.08771>`_, by Johnston Nick, Elad Eban, Ariel
Gordon, and Johannes Ballé, (2019).
.. math::
y[i] = \frac{x[i]}{\beta[i] + \sum_j(\gamma[j, i] * |x[j]|}
"""
def forward(self, x):
_, C, _, _ = x.size()
beta = self.beta_reparam(self.beta)
gamma = self.gamma_reparam(self.gamma)
gamma = gamma.reshape(C, C, 1, 1)
norm = F.conv2d(torch.abs(x), gamma, beta)
if not self.inverse:
norm = 1.0 / norm
out = x * norm
return out
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment