entropack 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. entropack-0.1.0/LICENSE +201 -0
  2. entropack-0.1.0/PKG-INFO +158 -0
  3. entropack-0.1.0/README.md +140 -0
  4. entropack-0.1.0/entropack/__init__.py +15 -0
  5. entropack-0.1.0/entropack/backends/__init__.py +19 -0
  6. entropack-0.1.0/entropack/backends/cuda/__init__.py +16 -0
  7. entropack-0.1.0/entropack/backends/cuda/device.py +96 -0
  8. entropack-0.1.0/entropack/backends/cuda/kernels.py +70 -0
  9. entropack-0.1.0/entropack/compression/__init__.py +4 -0
  10. entropack-0.1.0/entropack/compression/api.py +76 -0
  11. entropack-0.1.0/entropack/compression/compressed_tensor.py +205 -0
  12. entropack-0.1.0/entropack/linear/__init__.py +5 -0
  13. entropack-0.1.0/entropack/linear/linear.py +444 -0
  14. entropack-0.1.0/entropack/linear/quant_kernels.py +108 -0
  15. entropack-0.1.0/entropack/linear/utils.py +41 -0
  16. entropack-0.1.0/entropack/registry.py +121 -0
  17. entropack-0.1.0/entropack/schemes/__init__.py +12 -0
  18. entropack-0.1.0/entropack/schemes/base.py +121 -0
  19. entropack-0.1.0/entropack/schemes/checks.py +33 -0
  20. entropack-0.1.0/entropack/schemes/config.py +111 -0
  21. entropack-0.1.0/entropack/schemes/dfloat11/__init__.py +52 -0
  22. entropack-0.1.0/entropack/schemes/dfloat11/cuda.py +223 -0
  23. entropack-0.1.0/entropack/schemes/dfloat11/dfloat11.cu +740 -0
  24. entropack-0.1.0/entropack/schemes/dfloat11/eager.py +239 -0
  25. entropack-0.1.0/entropack/schemes/dfloat11/format.py +146 -0
  26. entropack-0.1.0/entropack/schemes/lattice_rans/__init__.py +60 -0
  27. entropack-0.1.0/entropack/schemes/lattice_rans/cuda.py +670 -0
  28. entropack-0.1.0/entropack/schemes/lattice_rans/eager.py +405 -0
  29. entropack-0.1.0/entropack/schemes/lattice_rans/format.py +309 -0
  30. entropack-0.1.0/entropack/schemes/lattice_rans/lattice_rans.cu +1140 -0
  31. entropack-0.1.0/entropack/schemes/lattice_rans/rans.py +209 -0
  32. entropack-0.1.0/entropack/schemes/lattice_rans/rdo.py +162 -0
  33. entropack-0.1.0/entropack/schemes/tile_ans/__init__.py +55 -0
  34. entropack-0.1.0/entropack/schemes/tile_ans/cuda.py +170 -0
  35. entropack-0.1.0/entropack/schemes/tile_ans/device.cuh +90 -0
  36. entropack-0.1.0/entropack/schemes/tile_ans/eager.py +307 -0
  37. entropack-0.1.0/entropack/schemes/tile_ans/format.py +164 -0
  38. entropack-0.1.0/entropack/schemes/tile_ans/tile_ans.cu +469 -0
  39. entropack-0.1.0/entropack.egg-info/PKG-INFO +158 -0
  40. entropack-0.1.0/entropack.egg-info/SOURCES.txt +56 -0
  41. entropack-0.1.0/entropack.egg-info/dependency_links.txt +1 -0
  42. entropack-0.1.0/entropack.egg-info/requires.txt +9 -0
  43. entropack-0.1.0/entropack.egg-info/top_level.txt +1 -0
  44. entropack-0.1.0/pyproject.toml +33 -0
  45. entropack-0.1.0/setup.cfg +4 -0
  46. entropack-0.1.0/tests/test_bitwise.py +432 -0
  47. entropack-0.1.0/tests/test_compression_api.py +145 -0
  48. entropack-0.1.0/tests/test_decode_tables.py +142 -0
  49. entropack-0.1.0/tests/test_device_generalization.py +286 -0
  50. entropack-0.1.0/tests/test_docs.py +257 -0
  51. entropack-0.1.0/tests/test_docs_examples.py +127 -0
  52. entropack-0.1.0/tests/test_lattice_rans_alphabet.py +133 -0
  53. entropack-0.1.0/tests/test_lattice_rans_cuda.py +323 -0
  54. entropack-0.1.0/tests/test_lattice_rans_multidtype.py +183 -0
  55. entropack-0.1.0/tests/test_lattice_rans_padding.py +130 -0
  56. entropack-0.1.0/tests/test_linear.py +550 -0
  57. entropack-0.1.0/tests/test_prepare_weight.py +100 -0
  58. entropack-0.1.0/tests/test_registry.py +334 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [ModelScope]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: entropack
3
+ Version: 0.1.0
4
+ Summary: EntroPack: general-purpose tensor compression for PyTorch with lossless and rate-controlled lossy schemes and GPU encoding and decoding.
5
+ Author: DiffSynth-Studio
6
+ License-Expression: Apache-2.0
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: torch>=2.10
11
+ Requires-Dist: numpy>=1.23
12
+ Requires-Dist: dahuffman>=0.4
13
+ Provides-Extra: cuda13
14
+ Requires-Dist: cupy-cuda13x>=14; extra == "cuda13"
15
+ Provides-Extra: cuda12
16
+ Requires-Dist: cupy-cuda12x>=14; extra == "cuda12"
17
+ Dynamic: license-file
18
+
19
+ # EntroPack
20
+
21
+ ### General-purpose tensor compression for PyTorch
22
+
23
+ EntroPack is a general-purpose tensor compression library for PyTorch. It supports lossless
24
+ compression for exact recovery and lossy compression with a target bitrate to balance storage
25
+ and reconstruction accuracy. GPU encoding and decoding compress tensors and restore them
26
+ in their original shape and dtype.
27
+
28
+ [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE)
29
+ ![Python](https://img.shields.io/badge/python-%3E%3D3.10-blue.svg)
30
+
31
+ [Documentation](docs/en/index.rst) · [中文](README_zh.md)
32
+
33
+ - **Flexible bitrates.** Compress each weight matrix at any non-integer target bitrate,
34
+ or preserve every input bit with a lossless scheme.
35
+ - **Dtype preservation.** Restore tensors in their input dtype, including BF16, FP16, FP8,
36
+ and INT8.
37
+ - **PyTorch integration.** Compress and restore tensors through a common API, and save
38
+ them with `state_dict`. Compressed linear layers provide an integration for model weights.
39
+
40
+ ## Installation
41
+
42
+ Use Python 3.10 or later and install a CUDA-enabled build of PyTorch 2.10 or later
43
+ for your environment.
44
+
45
+ ### Install from source (recommended)
46
+
47
+ ```bash
48
+ git clone https://github.com/modelscope/entropack.git
49
+ cd entropack
50
+ pip install -e ".[cuda13]"
51
+ ```
52
+
53
+ ### Install from PyPI
54
+
55
+ PyPI releases may lag behind source updates. Install from source for the latest features.
56
+
57
+ ```bash
58
+ pip install "entropack[cuda13]"
59
+ ```
60
+
61
+ Both installation methods above use CUDA 13 and include the matching CuPy package.
62
+ For CUDA 12, replace `cuda13` with `cuda12` in either command. If a compatible CuPy is
63
+ already installed, use `pip install -e .` for source installation or `pip install entropack` for PyPI.
64
+
65
+ See [Quick start](docs/en/Usage/Quick-start.md) for environment requirements and usage examples.
66
+
67
+ ## Get started
68
+
69
+ ### Direct tensor compression
70
+
71
+ This example compresses a 2D BF16 tensor at a target of 3.5 bits per element,
72
+ then decompresses it to a tensor with the original shape and dtype:
73
+
74
+ ```python
75
+ import torch
76
+ import entropack as ep
77
+
78
+ tensor = (torch.randn(256, 256, device="cuda") * 0.02).to(torch.bfloat16)
79
+ config = ep.LatticeRANSConfig(target_bpp=3.5)
80
+
81
+ compressed = ep.compress(tensor, config)
82
+ restored = ep.decompress(compressed, config)
83
+
84
+ print(f"Target: {config.target_bpp:.2f} bits per element")
85
+ print(f"Stored: {compressed.actual_bpp:.2f} bits per element")
86
+ print(restored.shape, restored.dtype)
87
+ ```
88
+
89
+ `target_bpp` is the requested number of bits per element (bpp). `actual_bpp` reports the stored
90
+ rate, including metadata. Targets from 1 to 11 are supported, including non-integer values.
91
+
92
+ ### Compressed Linear
93
+
94
+ `CompressedLinear.from_linear` compresses an existing `torch.nn.Linear`'s weights using
95
+ the supplied Config and returns a new Compressed Linear. Call it as `layer(x)` to compute
96
+ the output, just as with an ordinary linear layer:
97
+
98
+ ```python
99
+ import torch
100
+ import entropack as ep
101
+
102
+ linear = torch.nn.Linear(256, 256, dtype=torch.bfloat16, device="cuda")
103
+ config = ep.LatticeRANSConfig(target_bpp=4.0)
104
+ layer = ep.CompressedLinear.from_linear(linear, config=config)
105
+ x = torch.randn(8, 256, dtype=torch.bfloat16, device="cuda")
106
+
107
+ with torch.inference_mode():
108
+ output = layer(x)
109
+ print(output.shape, f"{layer.compressed_bits:.2f} bits per weight")
110
+ ```
111
+
112
+ See [Compressed Linear usage](docs/en/Usage/Linear-layers.md) for model replacement and checkpoint examples.
113
+
114
+ ## Configuration
115
+
116
+ Config defines the compression scheme and its settings. It is passed to tensor compression
117
+ and decompression functions or to a compressed Linear layer's constructor.
118
+
119
+ | Config | Compression and use cases |
120
+ | --- | --- |
121
+ | `DFloat11Config()` | Specialized lossless compression for BF16 tensors. Decompression restores every input bit, for applications requiring exact recovery. |
122
+ | `TileANSConfig()` | Lossless compression for BF16, FP16, FP32, FP8, INT8, and other supported dtypes. The compression ratio depends on the input data distribution. |
123
+ | `LatticeRANSConfig(target_bpp=...)` | Lossy compression of 2D floating-point and integer tensors. `target_bpp` specifies the target bits per element, from 1 to 11 including non-integer values, to balance storage size and reconstruction accuracy. |
124
+
125
+ See [Compression configuration](docs/en/Usage/Configuration.md) for scheme selection
126
+ and the complete parameter reference.
127
+
128
+ ## Performance
129
+
130
+ On one NVIDIA H20, EntroPack compresses the weights of all 276 linear layers in
131
+ Z-Image-Turbo's diffusion transformer at a 4 bpp target in **3.5 seconds**. The compressed
132
+ weights occupy **4.02 bpp**, with **7.18%** relative L2 reconstruction error. Inference with
133
+ these weights takes **544.7 ms** per denoising step, only **7.7%** above the original BF16
134
+ model's 505.7 ms.
135
+
136
+ ## Documentation
137
+
138
+ | Guide | Contents |
139
+ | --- | --- |
140
+ | [Quick start](docs/en/Usage/Quick-start.md) | Install and run tensor compression and Compressed Linear examples |
141
+ | [Compression configuration](docs/en/Usage/Configuration.md) | Choose a scheme and look up supported dtypes and parameters |
142
+ | [Tensor compression](docs/en/Usage/Tensor-compression.md) | Encode, decode, inspect storage, move data, and save or load tensors |
143
+ | [Compressed Linear usage](docs/en/Usage/Linear-layers.md) | Replace model layers, use low-precision computation, and manage checkpoints |
144
+ | [API reference](docs/en/API_Reference/index.md) | Look up functions, classes, and properties |
145
+
146
+ Compression principles: [DFloat11](docs/en/Principles/DFloat11.md), [tile-ANS](docs/en/Principles/Tile-ANS.md),
147
+ and [EntroPack lattice quantization](docs/en/Principles/Lattice-rANS.md).
148
+
149
+ ## Acknowledgements
150
+
151
+ EntroPack's design is inspired by [DFloat11](https://github.com/LeanModels/DFloat11),
152
+ [dahuffman](https://github.com/soxofaan/dahuffman),
153
+ [DietGPU](https://github.com/facebookresearch/dietgpu), and
154
+ [tile-ANS](https://arxiv.org/abs/2606.15789).
155
+
156
+ ## License
157
+
158
+ [Apache License 2.0](LICENSE).
@@ -0,0 +1,140 @@
1
+ # EntroPack
2
+
3
+ ### General-purpose tensor compression for PyTorch
4
+
5
+ EntroPack is a general-purpose tensor compression library for PyTorch. It supports lossless
6
+ compression for exact recovery and lossy compression with a target bitrate to balance storage
7
+ and reconstruction accuracy. GPU encoding and decoding compress tensors and restore them
8
+ in their original shape and dtype.
9
+
10
+ [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE)
11
+ ![Python](https://img.shields.io/badge/python-%3E%3D3.10-blue.svg)
12
+
13
+ [Documentation](docs/en/index.rst) · [中文](README_zh.md)
14
+
15
+ - **Flexible bitrates.** Compress each weight matrix at any non-integer target bitrate,
16
+ or preserve every input bit with a lossless scheme.
17
+ - **Dtype preservation.** Restore tensors in their input dtype, including BF16, FP16, FP8,
18
+ and INT8.
19
+ - **PyTorch integration.** Compress and restore tensors through a common API, and save
20
+ them with `state_dict`. Compressed linear layers provide an integration for model weights.
21
+
22
+ ## Installation
23
+
24
+ Use Python 3.10 or later and install a CUDA-enabled build of PyTorch 2.10 or later
25
+ for your environment.
26
+
27
+ ### Install from source (recommended)
28
+
29
+ ```bash
30
+ git clone https://github.com/modelscope/entropack.git
31
+ cd entropack
32
+ pip install -e ".[cuda13]"
33
+ ```
34
+
35
+ ### Install from PyPI
36
+
37
+ PyPI releases may lag behind source updates. Install from source for the latest features.
38
+
39
+ ```bash
40
+ pip install "entropack[cuda13]"
41
+ ```
42
+
43
+ Both installation methods above use CUDA 13 and include the matching CuPy package.
44
+ For CUDA 12, replace `cuda13` with `cuda12` in either command. If a compatible CuPy is
45
+ already installed, use `pip install -e .` for source installation or `pip install entropack` for PyPI.
46
+
47
+ See [Quick start](docs/en/Usage/Quick-start.md) for environment requirements and usage examples.
48
+
49
+ ## Get started
50
+
51
+ ### Direct tensor compression
52
+
53
+ This example compresses a 2D BF16 tensor at a target of 3.5 bits per element,
54
+ then decompresses it to a tensor with the original shape and dtype:
55
+
56
+ ```python
57
+ import torch
58
+ import entropack as ep
59
+
60
+ tensor = (torch.randn(256, 256, device="cuda") * 0.02).to(torch.bfloat16)
61
+ config = ep.LatticeRANSConfig(target_bpp=3.5)
62
+
63
+ compressed = ep.compress(tensor, config)
64
+ restored = ep.decompress(compressed, config)
65
+
66
+ print(f"Target: {config.target_bpp:.2f} bits per element")
67
+ print(f"Stored: {compressed.actual_bpp:.2f} bits per element")
68
+ print(restored.shape, restored.dtype)
69
+ ```
70
+
71
+ `target_bpp` is the requested number of bits per element (bpp). `actual_bpp` reports the stored
72
+ rate, including metadata. Targets from 1 to 11 are supported, including non-integer values.
73
+
74
+ ### Compressed Linear
75
+
76
+ `CompressedLinear.from_linear` compresses an existing `torch.nn.Linear`'s weights using
77
+ the supplied Config and returns a new Compressed Linear. Call it as `layer(x)` to compute
78
+ the output, just as with an ordinary linear layer:
79
+
80
+ ```python
81
+ import torch
82
+ import entropack as ep
83
+
84
+ linear = torch.nn.Linear(256, 256, dtype=torch.bfloat16, device="cuda")
85
+ config = ep.LatticeRANSConfig(target_bpp=4.0)
86
+ layer = ep.CompressedLinear.from_linear(linear, config=config)
87
+ x = torch.randn(8, 256, dtype=torch.bfloat16, device="cuda")
88
+
89
+ with torch.inference_mode():
90
+ output = layer(x)
91
+ print(output.shape, f"{layer.compressed_bits:.2f} bits per weight")
92
+ ```
93
+
94
+ See [Compressed Linear usage](docs/en/Usage/Linear-layers.md) for model replacement and checkpoint examples.
95
+
96
+ ## Configuration
97
+
98
+ Config defines the compression scheme and its settings. It is passed to tensor compression
99
+ and decompression functions or to a compressed Linear layer's constructor.
100
+
101
+ | Config | Compression and use cases |
102
+ | --- | --- |
103
+ | `DFloat11Config()` | Specialized lossless compression for BF16 tensors. Decompression restores every input bit, for applications requiring exact recovery. |
104
+ | `TileANSConfig()` | Lossless compression for BF16, FP16, FP32, FP8, INT8, and other supported dtypes. The compression ratio depends on the input data distribution. |
105
+ | `LatticeRANSConfig(target_bpp=...)` | Lossy compression of 2D floating-point and integer tensors. `target_bpp` specifies the target bits per element, from 1 to 11 including non-integer values, to balance storage size and reconstruction accuracy. |
106
+
107
+ See [Compression configuration](docs/en/Usage/Configuration.md) for scheme selection
108
+ and the complete parameter reference.
109
+
110
+ ## Performance
111
+
112
+ On one NVIDIA H20, EntroPack compresses the weights of all 276 linear layers in
113
+ Z-Image-Turbo's diffusion transformer at a 4 bpp target in **3.5 seconds**. The compressed
114
+ weights occupy **4.02 bpp**, with **7.18%** relative L2 reconstruction error. Inference with
115
+ these weights takes **544.7 ms** per denoising step, only **7.7%** above the original BF16
116
+ model's 505.7 ms.
117
+
118
+ ## Documentation
119
+
120
+ | Guide | Contents |
121
+ | --- | --- |
122
+ | [Quick start](docs/en/Usage/Quick-start.md) | Install and run tensor compression and Compressed Linear examples |
123
+ | [Compression configuration](docs/en/Usage/Configuration.md) | Choose a scheme and look up supported dtypes and parameters |
124
+ | [Tensor compression](docs/en/Usage/Tensor-compression.md) | Encode, decode, inspect storage, move data, and save or load tensors |
125
+ | [Compressed Linear usage](docs/en/Usage/Linear-layers.md) | Replace model layers, use low-precision computation, and manage checkpoints |
126
+ | [API reference](docs/en/API_Reference/index.md) | Look up functions, classes, and properties |
127
+
128
+ Compression principles: [DFloat11](docs/en/Principles/DFloat11.md), [tile-ANS](docs/en/Principles/Tile-ANS.md),
129
+ and [EntroPack lattice quantization](docs/en/Principles/Lattice-rANS.md).
130
+
131
+ ## Acknowledgements
132
+
133
+ EntroPack's design is inspired by [DFloat11](https://github.com/LeanModels/DFloat11),
134
+ [dahuffman](https://github.com/soxofaan/dahuffman),
135
+ [DietGPU](https://github.com/facebookresearch/dietgpu), and
136
+ [tile-ANS](https://arxiv.org/abs/2606.15789).
137
+
138
+ ## License
139
+
140
+ [Apache License 2.0](LICENSE).
@@ -0,0 +1,15 @@
1
+ from importlib import metadata
2
+
3
+ try:
4
+ __version__ = metadata.version("entropack")
5
+ except metadata.PackageNotFoundError:
6
+ __version__ = "0+unknown"
7
+
8
+ from .compression import CompressedTensor, compress, decompress
9
+ from .linear import CompressedFP8Linear, CompressedINT8Linear, CompressedLinear
10
+ from .schemes import CompressionConfig, DFloat11Config, LatticeRANSConfig, RawConfig, TileANSConfig
11
+
12
+ __all__ = [
13
+ "CompressedFP8Linear", "CompressedINT8Linear", "CompressedLinear", "CompressedTensor", "CompressionConfig",
14
+ "DFloat11Config", "LatticeRANSConfig", "RawConfig", "TileANSConfig", "__version__", "compress", "decompress",
15
+ ]
@@ -0,0 +1,19 @@
1
+ from collections.abc import Callable
2
+ from dataclasses import dataclass
3
+
4
+ import torch
5
+
6
+ from . import cuda
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Backend:
11
+ name: str
12
+ priority: int = 0
13
+ probe: Callable[[], str | None] | None = None
14
+ device: Callable[[], torch.device] | None = None
15
+
16
+
17
+ BACKENDS: tuple[Backend, ...] = (
18
+ Backend("cuda", priority=100, probe=cuda.probe, device=cuda.runs_on), Backend("eager", priority=0),
19
+ )
@@ -0,0 +1,16 @@
1
+ import torch
2
+
3
+
4
+ def probe() -> str | None:
5
+ if not torch.cuda.is_available():
6
+ return "torch.cuda.is_available() is False (no NVIDIA device / driver)"
7
+ try:
8
+ import cupy
9
+ except ImportError as e:
10
+ return (f"cupy is not installed ({e}); install a matching build, e.g. "
11
+ "`pip install cupy-cuda13x` for CUDA 13 or `pip install cupy-cuda12x` for CUDA 12")
12
+ return None
13
+
14
+
15
+ def runs_on() -> torch.device:
16
+ return torch.device("cuda", torch.cuda.current_device())
@@ -0,0 +1,96 @@
1
+ from dataclasses import dataclass
2
+
3
+ import cupy
4
+ import torch
5
+
6
+ from .kernels import device_index
7
+
8
+ _FALLBACK_WARP_SIZE = 32
9
+
10
+ _DEFAULT_GRID_WAVES = 8
11
+
12
+ __all__ = ["DeviceCaps", "caps", "resolve_threads", "validate_threads_per_block"]
13
+
14
+
15
+ def _shared_optin(index: int, properties) -> int:
16
+ optin = getattr(properties, "shared_memory_per_block_optin", 0)
17
+ if optin:
18
+ return int(optin)
19
+ with cupy.cuda.Device(index):
20
+ attributes = cupy.cuda.Device(index).attributes
21
+ return int(attributes["MaxSharedMemoryPerBlockOptin"])
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class DeviceCaps:
26
+ index: int
27
+ name: str
28
+ compute_capability: tuple[int, int]
29
+ sm_count: int
30
+ warp_size: int
31
+ max_threads_per_block: int
32
+ threads_per_sm: int
33
+ regs_per_sm: int
34
+ shared_per_block: int
35
+ shared_optin: int
36
+ shared_per_sm: int
37
+ l2_bytes: int
38
+
39
+ def blocks_per_sm(self, threads_per_block: int, shared_per_block: int = 0, regs_per_thread: int = 0) -> int:
40
+ blocks = self.threads_per_sm // threads_per_block
41
+ if shared_per_block > 0:
42
+ blocks = min(blocks, self.shared_per_sm // shared_per_block)
43
+ if regs_per_thread > 0:
44
+ blocks = min(blocks, self.regs_per_sm // (regs_per_thread * threads_per_block))
45
+ return max(1, blocks)
46
+
47
+ def resident_blocks(self, threads_per_block: int, shared_per_block: int = 0, regs_per_thread: int = 0) -> int:
48
+ return self.sm_count * self.blocks_per_sm(threads_per_block, shared_per_block, regs_per_thread)
49
+
50
+ def grid(self, wanted: int, threads_per_block: int, shared_per_block: int = 0, waves: int = _DEFAULT_GRID_WAVES) -> int:
51
+ limit = self.resident_blocks(threads_per_block, shared_per_block) * waves
52
+ return max(1, min(wanted, limit))
53
+
54
+ def shared_limit(self, static_slack: int = 0) -> int:
55
+ return max(0, min(self.shared_optin, self.shared_per_sm - static_slack))
56
+
57
+ def threads_per_block(self, wanted: int) -> int:
58
+ usable = min(wanted, self.max_threads_per_block)
59
+ usable -= usable % self.warp_size
60
+ return max(self.warp_size, usable)
61
+
62
+
63
+ _caps_cache: dict[int, DeviceCaps] = {}
64
+
65
+
66
+ def caps(device=None) -> DeviceCaps:
67
+ index = device_index(device)
68
+ cached = _caps_cache.get(index)
69
+ if cached is not None:
70
+ return cached
71
+ properties = torch.cuda.get_device_properties(index)
72
+ queried = DeviceCaps(
73
+ index=index, name=properties.name, compute_capability=(properties.major, properties.minor),
74
+ sm_count=properties.multi_processor_count, warp_size=getattr(properties, "warp_size", 0) or _FALLBACK_WARP_SIZE,
75
+ max_threads_per_block=properties.max_threads_per_block, threads_per_sm=properties.max_threads_per_multi_processor,
76
+ regs_per_sm=properties.regs_per_multiprocessor, shared_per_block=properties.shared_memory_per_block,
77
+ shared_optin=_shared_optin(index, properties), shared_per_sm=properties.shared_memory_per_multiprocessor,
78
+ l2_bytes=getattr(properties, "L2_cache_size", 0),
79
+ )
80
+ _caps_cache[index] = queried
81
+ return queried
82
+
83
+
84
+ def validate_threads_per_block(caps: DeviceCaps, threads_per_block: int) -> None:
85
+ if threads_per_block % caps.warp_size or threads_per_block > caps.max_threads_per_block:
86
+ raise ValueError(
87
+ f"threads_per_block={threads_per_block} is not launchable on {caps.name}: it must be "
88
+ f"a multiple of the {caps.warp_size}-thread warp size and at most {caps.max_threads_per_block}"
89
+ )
90
+
91
+
92
+ def resolve_threads(caps: DeviceCaps, requested: int | None, default: int) -> int:
93
+ if requested is None:
94
+ return caps.threads_per_block(default)
95
+ validate_threads_per_block(caps, requested)
96
+ return requested