vaezip 0.1.0__py3-none-any.whl

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.
vaezip/utils/lloyd.py ADDED
@@ -0,0 +1,97 @@
1
+ """Lloyd-Max quantization tables for values normalized to [0, 1]."""
2
+
3
+ import torch
4
+
5
+ MAX_FIT_POINTS = 2**17
6
+ TINY = 1e-30
7
+
8
+
9
+ def nearest_level(values: torch.Tensor, tables: torch.Tensor) -> torch.Tensor:
10
+ """
11
+ args:
12
+ values: [B, N], values: [0...1]
13
+ tables: [B, K], sorted ascending
14
+ returns:
15
+ codes: [B, N], dtype: torch.uint8, index of the nearest table entry
16
+ """
17
+ midpoints = (tables[:, 1:] + tables[:, :-1]) / 2
18
+ return torch.searchsorted(midpoints.contiguous(), values.contiguous()).to(
19
+ torch.uint8
20
+ )
21
+
22
+
23
+ def fit_lloyd_table(
24
+ values: torch.Tensor,
25
+ weights: torch.Tensor,
26
+ levels: int,
27
+ iterations: int = 20,
28
+ ) -> torch.Tensor:
29
+ """
30
+ args:
31
+ values: [N], values: [0...1]
32
+ weights: [N], positive importance of each value
33
+ levels: number of table entries
34
+ returns:
35
+ table: [levels], dtype: torch.float32, sorted, fp16-representable
36
+ """
37
+ stride = max(1, values.numel() // MAX_FIT_POINTS)
38
+ values, weights = values[::stride], weights[::stride]
39
+ weights = weights / weights.mean().clamp(min=TINY)
40
+ table = torch.linspace(0, 1, levels, device=values.device)
41
+ for _ in range(iterations):
42
+ assignment = nearest_level(values.unsqueeze(0), table.unsqueeze(0))[0].long()
43
+ weighted_sum = torch.zeros_like(table).index_add_(
44
+ 0, assignment, values * weights
45
+ )
46
+ weight_total = torch.zeros_like(table).index_add_(0, assignment, weights)
47
+ table = torch.where(
48
+ weight_total > 0, weighted_sum / weight_total.clamp(min=TINY), table
49
+ )
50
+ return table.to(torch.float16).float().sort().values
51
+
52
+
53
+ def fit_lloyd_tables_fast(
54
+ values: torch.Tensor,
55
+ weights: torch.Tensor,
56
+ levels: int,
57
+ iterations: int = 2,
58
+ bins: int = 4096,
59
+ ) -> torch.Tensor:
60
+ """
61
+ Batched approximation of `fit_lloyd_table` on a weighted histogram of the values.
62
+ The start is companded quantiles, followed by a few Lloyd steps on bin centroids.
63
+
64
+ args:
65
+ values: [R, N], values: [0...1]
66
+ weights: [R, N], positive importance of each value
67
+ levels: number of table entries
68
+ returns:
69
+ tables: [R, levels], dtype: torch.float32, sorted, fp16-representable
70
+ """
71
+ rows = values.shape[0]
72
+ weights = weights / weights.mean(dim=1, keepdim=True).clamp(min=TINY)
73
+ bin_index = (values * bins).long().clamp_(0, bins - 1)
74
+ mass = torch.zeros(rows, bins, device=values.device).scatter_add_(
75
+ 1, bin_index, weights
76
+ )
77
+ moment = torch.zeros_like(mass).scatter_add_(1, bin_index, values * weights)
78
+ bin_centers = (torch.arange(bins, device=values.device) + 0.5) / bins
79
+ centroid = torch.where(mass > 0, moment / mass.clamp(min=TINY), bin_centers)
80
+
81
+ cumulative_mass = mass.pow(1 / 3).cumsum(dim=1)
82
+ targets = (torch.arange(levels, device=values.device) + 0.5) / levels
83
+ positions = torch.searchsorted(
84
+ cumulative_mass / cumulative_mass[:, -1:],
85
+ targets.expand(rows, -1).contiguous(),
86
+ )
87
+ tables = centroid.gather(1, positions.clamp(max=bins - 1))
88
+ for _ in range(iterations):
89
+ assignment = torch.searchsorted(
90
+ ((tables[:, 1:] + tables[:, :-1]) / 2).contiguous(), centroid
91
+ )
92
+ weighted_sum = torch.zeros_like(tables).scatter_add_(1, assignment, moment)
93
+ weight_total = torch.zeros_like(tables).scatter_add_(1, assignment, mass)
94
+ tables = torch.where(
95
+ weight_total > 0, weighted_sum / weight_total.clamp(min=TINY), tables
96
+ )
97
+ return tables.to(torch.float16).float().sort(dim=1).values
@@ -0,0 +1,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: vaezip
3
+ Version: 0.1.0
4
+ Summary: Compression of VAE latents: low-bit quantization codecs on PyTorch and safetensors
5
+ License-Expression: Unlicense
6
+ Project-URL: Homepage, https://github.com/tensorforger/VaeZip
7
+ Project-URL: Issues, https://github.com/tensorforger/VaeZip/issues
8
+ Project-URL: Changelog, https://github.com/tensorforger/VaeZip/blob/main/CHANGELOG.md
9
+ Project-URL: Benchmark, https://github.com/tensorforger/LatentStorageBenchmark
10
+ Keywords: vae,latents,compression,quantization,pytorch,safetensors
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: torch>=2.2
26
+ Requires-Dist: safetensors>=0.4.3
27
+ Requires-Dist: numpy>=1.24
28
+ Dynamic: license-file
29
+
30
+ ![main_logo](https://raw.githubusercontent.com/tensorforger/tensorforger/main/assets/VaeZip_main_logo.png)
31
+
32
+
33
+ **VaeZip** is the simple and efficient way to store latent tensors. It brings in low-bit quantization codecs, built around **PyTorch** and **safetensors** and exploits how [VAEs store there latents](https://github.com/tensorforger/LatentStorageBenchmark).
34
+
35
+
36
+ The codecs were selected from the results of the
37
+ [LatentStorageBenchmark](https://github.com/tensorforger/LatentStorageBenchmark),
38
+ which compares many latent storage schemes by reconstruction quality, size and I/O time.
39
+
40
+ ![demo](https://raw.githubusercontent.com/tensorforger/tensorforger/main/assets/VaeZip_demo.png)
41
+
42
+ *10x file size reduction with almost no quality loss. [reproduce these results](https://github.com/tensorforger/VaeZip/blob/main/examples/demo_reproduction.ipynb)*.
43
+
44
+ **Use cases**:
45
+ * Storage of large-scale encoded datasets for pretraining.
46
+ * Network transfer of latents in efficient inference pipelines, where VAE and generative transformer/VLM are on different nodes.
47
+ * Pipeline parallelism: Transfer activations/latents between pipeline stages over slow interconnects (PCIe, Ethernet, cross-datacenter).
48
+
49
+ ## Installation
50
+
51
+ ```bash
52
+ pip install vaezip
53
+ ```
54
+
55
+ Requires Python 3.10+ and PyTorch 2.2+. Install PyTorch for your platform first if you need a specific build.
56
+
57
+ ## Quick start
58
+
59
+ ```python
60
+ import torch
61
+ import vaezip
62
+
63
+ latents = torch.randn([4, 32, 128, 128], device="cuda")
64
+
65
+ vaezip.save(latents, "latents.vz.safetensors", codec="lbrq_4bit")
66
+ restored = vaezip.load("latents.vz.safetensors", device="cuda")
67
+ ```
68
+
69
+ The codec config is stored in the file metadata, so `load()` needs no codec.
70
+ Pass `save_metadata=False` to drop it, then `load()` requires an explicit `codec=`.
71
+
72
+ ## Key concepts
73
+
74
+ **Codec** is a compression algorithm configured at construction.
75
+ `encode()` returns an `EncodedTensor`, `decode()` returns a `float32` tensor of the original shape
76
+ (or another floating dtype via `decode(encoded, dtype=...)`).
77
+
78
+ ```python
79
+ from vaezip.codecs import BlockRangeQuantCodec
80
+
81
+ codec = BlockRangeQuantCodec(
82
+ value_bits=4, range_bits=4, channel_dim=1, block_size=(8, 8)
83
+ )
84
+ encoded = codec.encode(latents)
85
+ restored = codec.decode(encoded)
86
+ ```
87
+
88
+ **EncodedTensor** holds named tensors plus string metadata with the codec config.
89
+ It serializes to `.safetensors` (default) or `.pth`:
90
+
91
+ ```python
92
+ data = encoded.serialize() # or vaezip.serialize(encoded)
93
+ encoded = vaezip.deserialize(data)
94
+ data = encoded.serialize(save_metadata=False, format="pth")
95
+ ```
96
+
97
+ **Configs** are diffusers-style JSON files and can be created from files, shortcut names or dicts.
98
+ Keyword arguments override config values:
99
+
100
+ ```python
101
+ from vaezip.codecs import AutoCodec
102
+
103
+ codec.save_config("codec.json")
104
+ codec = AutoCodec.from_config("codec.json")
105
+ codec = AutoCodec.from_config("brq_8bit", block_size=(4, 4, 4))
106
+ ```
107
+
108
+ ## Codecs
109
+
110
+ | Codec | Description |
111
+ |---|---|
112
+ | `CastCodec(cast_dtype)` | Cast to a floating dtype, e.g. `torch.float16`, `torch.float8_e4m3fn`. |
113
+ | `RangeQuantCodec(bits, channel_dim)` | Per-channel min/max normalization, `bits`-bit integers. |
114
+ | `BlockRangeQuantCodec(value_bits, range_bits, channel_dim, block_size)` | Min/max per block of a channel, `value_bits` inside the block range, block ranges stored with `range_bits`. |
115
+ | `LloydBlockRangeQuantCodec(..., lloyd_fast, cache_table)` | Same with Lloyd-Max level tables instead of uniform levels. |
116
+
117
+ The first tensor dimension is always the batch. Block codecs take one more dimension as the channel
118
+ (`channel_dim`, negative values count from the end) and treat the rest as spatial, `block_size` has one entry per spatial dimension:
119
+
120
+ ```python
121
+ # [B, C, H, W]
122
+ BlockRangeQuantCodec(value_bits=4, range_bits=4, channel_dim=1, block_size=(8, 8))
123
+ # [B, C, T, H, W], no temporal blocks
124
+ BlockRangeQuantCodec(value_bits=4, range_bits=4, channel_dim=1, block_size=(1, 8, 8))
125
+ # [B, T, C, H, W]
126
+ BlockRangeQuantCodec(value_bits=4, range_bits=4, channel_dim=2, block_size=(4, 8, 8))
127
+ ```
128
+
129
+ Sizes that are not divisible by the block size are padded internally, decoded tensors keep the original shape.
130
+ Low-bit values are bit-packed, so the size follows the number of bits.
131
+ Quantization ranges are computed per sample, samples in a batch are encoded independently.
132
+
133
+ `LloydBlockRangeQuantCodec` always stores its level table in the encoded tensor.
134
+ `cache_table=True` fits the table once on the first batch and reuses it to speed up encoding,
135
+ `codec.flush_cache()` resets it.
136
+
137
+ ## Shortcuts
138
+
139
+ | Name | Codec | Approx. bits per value |
140
+ |---|---|---|
141
+ | `cast_fp32` (default), `cast_fp16`, `cast_bf16`, `cast_fp8_e4m3` | `CastCodec` | 32, 16, 16, 8 |
142
+ | `rq_8bit`, `rq_6bit`, `rq_4bit` | `RangeQuantCodec` | 8, 6, 4 |
143
+ | `brq_8bit`, `brq_6bit`, `brq_5bit`, `brq_4bit`, `brq_3bit`, `brq_2bit` | `BlockRangeQuantCodec` | 8.1, 6.1, 5.1, 4.1, 3.1, 2.1 |
144
+ | `lbrq_8bit`, `lbrq_6bit`, `lbrq_5bit`, `lbrq_4bit`, `lbrq_3bit`, `lbrq_2bit` | `LloydBlockRangeQuantCodec` | 8.1, 6.1, 5.1, 4.1, 3.1, 2.1 |
145
+
146
+ The block shortcuts use `value_bits` from the name, `range_bits=4`, `block_size=(8, 8)` and `channel_dim=1`.
147
+ These settings are the points of the MSE Pareto front on FLUX.2 latents (benchmark run 1.2) closest to the target bit count.
148
+ `vaezip.codecs.list_shortcuts()` lists all names.
149
+
150
+ ## Development
151
+
152
+ ```bash
153
+ uv sync
154
+ uv run pytest
155
+ uv run ruff check . && uv run ruff format --check . && uv run mypy
156
+ ```
157
+
158
+ ## License
159
+
160
+ [Unlicense](LICENSE)
@@ -0,0 +1,24 @@
1
+ vaezip/__init__.py,sha256=WUX4-5GhUmr8696GkeR5f4kerXiphGiRna9ThWQTNho,344
2
+ vaezip/_version.py,sha256=ZXJqehvwFXAGJKgzeyjtkk4Q4Zm39gPOgD2cEGPL0wM,190
3
+ vaezip/api.py,sha256=4NtwuyRFRox7UVDDpbgV1YHWKC-9Rn5O2ctdL8luPCY,4422
4
+ vaezip/encoded_tensor.py,sha256=Q_7JnVk1Htq0FyxijD_wWq3TzKXd7maf3sXSPVD-6UI,4343
5
+ vaezip/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ vaezip/codecs/__init__.py,sha256=9__t5zGCkUTb2f1myzz7VcBZrB1egKw64kbHSpVu8j4,621
7
+ vaezip/codecs/auto.py,sha256=8-Ei9-HO9Evu8oFiwiPzNiw8ApnLDlPtxybZe_CzrYY,1561
8
+ vaezip/codecs/base.py,sha256=TvwcirA89mWhbB6Ul2BUBVWuyajBCFpXhnbQXtc7CJ4,4276
9
+ vaezip/codecs/block_range_quant.py,sha256=2dmzXj9UV29tyIKdM8buFIxn3rfnRf9PCWgiw5cFLFg,9259
10
+ vaezip/codecs/cast.py,sha256=cGPJgYTyOFk9WmvFMlcVN9FllPxSbBZzhjnFee872U0,2060
11
+ vaezip/codecs/config.py,sha256=eBreKKHrVpAgsX75we8Ub0vmPJGyP_-FlQdc9q0WiuI,1744
12
+ vaezip/codecs/lloyd_block_range_quant.py,sha256=QGs25sP6yBg3s_dXoXkuAbvEWZhAQCEU9TLQvnHbXko,4181
13
+ vaezip/codecs/range_quant.py,sha256=RRb8MLOtC1mTFJQEJl_Q1JJeAzZp_C0hujUSv2E4Yb8,3506
14
+ vaezip/codecs/shortcuts.py,sha256=nrtgJ95oJlRNJoFpbYELaPfvxDfF1HWQMk_-8EILOXk,1624
15
+ vaezip/utils/__init__.py,sha256=tntvtMeE1lu8n7XMAtZAGXy5MmHaecc3hsVKWBhDS4k,43
16
+ vaezip/utils/bit_packing.py,sha256=aJJj9uQJtI9UVUlLHsyajmFmX9TRX2UD_uolHxSkJ5o,2267
17
+ vaezip/utils/blocks.py,sha256=o_BKl8Vcw1t0VMBSo7orksKdV0X6bbvG06mnNBFZNBk,3147
18
+ vaezip/utils/layout.py,sha256=WIySLbmcdVa_iRYFTcs7w8Mz_xRbiukMBv2Bkb4kkQY,1817
19
+ vaezip/utils/lloyd.py,sha256=6AV1my6B69lOPbFRewnbmltTLxPEZnbCdha09wBb8tI,3594
20
+ vaezip-0.1.0.dist-info/licenses/LICENSE,sha256=b5ovsAkiXeXMocKiTf7XpovCJlfkVbSj1j8GUli0VdE,1211
21
+ vaezip-0.1.0.dist-info/METADATA,sha256=80BOroDlG8di_rM3aB5rCuK4ago3GvmwaQyH-CiVQGU,6699
22
+ vaezip-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
23
+ vaezip-0.1.0.dist-info/top_level.txt,sha256=QZ0uPyZhNWehXV3pZqVa3ZjEFQ232ONVszOYzgva4r8,7
24
+ vaezip-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org/>
@@ -0,0 +1 @@
1
+ vaezip