vaezip 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.
- vaezip-0.1.0/LICENSE +24 -0
- vaezip-0.1.0/PKG-INFO +160 -0
- vaezip-0.1.0/README.md +131 -0
- vaezip-0.1.0/pyproject.toml +78 -0
- vaezip-0.1.0/setup.cfg +4 -0
- vaezip-0.1.0/src/vaezip/__init__.py +16 -0
- vaezip-0.1.0/src/vaezip/_version.py +8 -0
- vaezip-0.1.0/src/vaezip/api.py +139 -0
- vaezip-0.1.0/src/vaezip/codecs/__init__.py +20 -0
- vaezip-0.1.0/src/vaezip/codecs/auto.py +44 -0
- vaezip-0.1.0/src/vaezip/codecs/base.py +119 -0
- vaezip-0.1.0/src/vaezip/codecs/block_range_quant.py +232 -0
- vaezip-0.1.0/src/vaezip/codecs/cast.py +62 -0
- vaezip-0.1.0/src/vaezip/codecs/config.py +55 -0
- vaezip-0.1.0/src/vaezip/codecs/lloyd_block_range_quant.py +112 -0
- vaezip-0.1.0/src/vaezip/codecs/range_quant.py +88 -0
- vaezip-0.1.0/src/vaezip/codecs/shortcuts.py +49 -0
- vaezip-0.1.0/src/vaezip/encoded_tensor.py +132 -0
- vaezip-0.1.0/src/vaezip/py.typed +0 -0
- vaezip-0.1.0/src/vaezip/utils/__init__.py +1 -0
- vaezip-0.1.0/src/vaezip/utils/bit_packing.py +58 -0
- vaezip-0.1.0/src/vaezip/utils/blocks.py +91 -0
- vaezip-0.1.0/src/vaezip/utils/layout.py +50 -0
- vaezip-0.1.0/src/vaezip/utils/lloyd.py +97 -0
- vaezip-0.1.0/src/vaezip.egg-info/PKG-INFO +160 -0
- vaezip-0.1.0/src/vaezip.egg-info/SOURCES.txt +36 -0
- vaezip-0.1.0/src/vaezip.egg-info/dependency_links.txt +1 -0
- vaezip-0.1.0/src/vaezip.egg-info/requires.txt +3 -0
- vaezip-0.1.0/src/vaezip.egg-info/top_level.txt +1 -0
- vaezip-0.1.0/tests/test_api.py +142 -0
- vaezip-0.1.0/tests/test_block_range_quant_codec.py +201 -0
- vaezip-0.1.0/tests/test_cast_codec.py +88 -0
- vaezip-0.1.0/tests/test_config.py +153 -0
- vaezip-0.1.0/tests/test_encoded_tensor.py +96 -0
- vaezip-0.1.0/tests/test_lloyd_block_range_quant_codec.py +93 -0
- vaezip-0.1.0/tests/test_package.py +5 -0
- vaezip-0.1.0/tests/test_range_quant_codec.py +112 -0
- vaezip-0.1.0/tests/test_utils.py +77 -0
vaezip-0.1.0/LICENSE
ADDED
|
@@ -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/>
|
vaezip-0.1.0/PKG-INFO
ADDED
|
@@ -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
|
+

|
|
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
|
+

|
|
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)
|
vaezip-0.1.0/README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
**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).
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
The codecs were selected from the results of the
|
|
8
|
+
[LatentStorageBenchmark](https://github.com/tensorforger/LatentStorageBenchmark),
|
|
9
|
+
which compares many latent storage schemes by reconstruction quality, size and I/O time.
|
|
10
|
+
|
|
11
|
+

|
|
12
|
+
|
|
13
|
+
*10x file size reduction with almost no quality loss. [reproduce these results](https://github.com/tensorforger/VaeZip/blob/main/examples/demo_reproduction.ipynb)*.
|
|
14
|
+
|
|
15
|
+
**Use cases**:
|
|
16
|
+
* Storage of large-scale encoded datasets for pretraining.
|
|
17
|
+
* Network transfer of latents in efficient inference pipelines, where VAE and generative transformer/VLM are on different nodes.
|
|
18
|
+
* Pipeline parallelism: Transfer activations/latents between pipeline stages over slow interconnects (PCIe, Ethernet, cross-datacenter).
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install vaezip
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Requires Python 3.10+ and PyTorch 2.2+. Install PyTorch for your platform first if you need a specific build.
|
|
27
|
+
|
|
28
|
+
## Quick start
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
import torch
|
|
32
|
+
import vaezip
|
|
33
|
+
|
|
34
|
+
latents = torch.randn([4, 32, 128, 128], device="cuda")
|
|
35
|
+
|
|
36
|
+
vaezip.save(latents, "latents.vz.safetensors", codec="lbrq_4bit")
|
|
37
|
+
restored = vaezip.load("latents.vz.safetensors", device="cuda")
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The codec config is stored in the file metadata, so `load()` needs no codec.
|
|
41
|
+
Pass `save_metadata=False` to drop it, then `load()` requires an explicit `codec=`.
|
|
42
|
+
|
|
43
|
+
## Key concepts
|
|
44
|
+
|
|
45
|
+
**Codec** is a compression algorithm configured at construction.
|
|
46
|
+
`encode()` returns an `EncodedTensor`, `decode()` returns a `float32` tensor of the original shape
|
|
47
|
+
(or another floating dtype via `decode(encoded, dtype=...)`).
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from vaezip.codecs import BlockRangeQuantCodec
|
|
51
|
+
|
|
52
|
+
codec = BlockRangeQuantCodec(
|
|
53
|
+
value_bits=4, range_bits=4, channel_dim=1, block_size=(8, 8)
|
|
54
|
+
)
|
|
55
|
+
encoded = codec.encode(latents)
|
|
56
|
+
restored = codec.decode(encoded)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
**EncodedTensor** holds named tensors plus string metadata with the codec config.
|
|
60
|
+
It serializes to `.safetensors` (default) or `.pth`:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
data = encoded.serialize() # or vaezip.serialize(encoded)
|
|
64
|
+
encoded = vaezip.deserialize(data)
|
|
65
|
+
data = encoded.serialize(save_metadata=False, format="pth")
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**Configs** are diffusers-style JSON files and can be created from files, shortcut names or dicts.
|
|
69
|
+
Keyword arguments override config values:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from vaezip.codecs import AutoCodec
|
|
73
|
+
|
|
74
|
+
codec.save_config("codec.json")
|
|
75
|
+
codec = AutoCodec.from_config("codec.json")
|
|
76
|
+
codec = AutoCodec.from_config("brq_8bit", block_size=(4, 4, 4))
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Codecs
|
|
80
|
+
|
|
81
|
+
| Codec | Description |
|
|
82
|
+
|---|---|
|
|
83
|
+
| `CastCodec(cast_dtype)` | Cast to a floating dtype, e.g. `torch.float16`, `torch.float8_e4m3fn`. |
|
|
84
|
+
| `RangeQuantCodec(bits, channel_dim)` | Per-channel min/max normalization, `bits`-bit integers. |
|
|
85
|
+
| `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`. |
|
|
86
|
+
| `LloydBlockRangeQuantCodec(..., lloyd_fast, cache_table)` | Same with Lloyd-Max level tables instead of uniform levels. |
|
|
87
|
+
|
|
88
|
+
The first tensor dimension is always the batch. Block codecs take one more dimension as the channel
|
|
89
|
+
(`channel_dim`, negative values count from the end) and treat the rest as spatial, `block_size` has one entry per spatial dimension:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
# [B, C, H, W]
|
|
93
|
+
BlockRangeQuantCodec(value_bits=4, range_bits=4, channel_dim=1, block_size=(8, 8))
|
|
94
|
+
# [B, C, T, H, W], no temporal blocks
|
|
95
|
+
BlockRangeQuantCodec(value_bits=4, range_bits=4, channel_dim=1, block_size=(1, 8, 8))
|
|
96
|
+
# [B, T, C, H, W]
|
|
97
|
+
BlockRangeQuantCodec(value_bits=4, range_bits=4, channel_dim=2, block_size=(4, 8, 8))
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Sizes that are not divisible by the block size are padded internally, decoded tensors keep the original shape.
|
|
101
|
+
Low-bit values are bit-packed, so the size follows the number of bits.
|
|
102
|
+
Quantization ranges are computed per sample, samples in a batch are encoded independently.
|
|
103
|
+
|
|
104
|
+
`LloydBlockRangeQuantCodec` always stores its level table in the encoded tensor.
|
|
105
|
+
`cache_table=True` fits the table once on the first batch and reuses it to speed up encoding,
|
|
106
|
+
`codec.flush_cache()` resets it.
|
|
107
|
+
|
|
108
|
+
## Shortcuts
|
|
109
|
+
|
|
110
|
+
| Name | Codec | Approx. bits per value |
|
|
111
|
+
|---|---|---|
|
|
112
|
+
| `cast_fp32` (default), `cast_fp16`, `cast_bf16`, `cast_fp8_e4m3` | `CastCodec` | 32, 16, 16, 8 |
|
|
113
|
+
| `rq_8bit`, `rq_6bit`, `rq_4bit` | `RangeQuantCodec` | 8, 6, 4 |
|
|
114
|
+
| `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 |
|
|
115
|
+
| `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 |
|
|
116
|
+
|
|
117
|
+
The block shortcuts use `value_bits` from the name, `range_bits=4`, `block_size=(8, 8)` and `channel_dim=1`.
|
|
118
|
+
These settings are the points of the MSE Pareto front on FLUX.2 latents (benchmark run 1.2) closest to the target bit count.
|
|
119
|
+
`vaezip.codecs.list_shortcuts()` lists all names.
|
|
120
|
+
|
|
121
|
+
## Development
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
uv sync
|
|
125
|
+
uv run pytest
|
|
126
|
+
uv run ruff check . && uv run ruff format --check . && uv run mypy
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
[Unlicense](LICENSE)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "vaezip"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Compression of VAE latents: low-bit quantization codecs on PyTorch and safetensors"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Unlicense"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
keywords = [
|
|
14
|
+
"vae",
|
|
15
|
+
"latents",
|
|
16
|
+
"compression",
|
|
17
|
+
"quantization",
|
|
18
|
+
"pytorch",
|
|
19
|
+
"safetensors",
|
|
20
|
+
]
|
|
21
|
+
classifiers = [
|
|
22
|
+
"Development Status :: 3 - Alpha",
|
|
23
|
+
"Intended Audience :: Developers",
|
|
24
|
+
"Operating System :: OS Independent",
|
|
25
|
+
"Programming Language :: Python :: 3",
|
|
26
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
27
|
+
"Programming Language :: Python :: 3.10",
|
|
28
|
+
"Programming Language :: Python :: 3.11",
|
|
29
|
+
"Programming Language :: Python :: 3.12",
|
|
30
|
+
"Programming Language :: Python :: 3.13",
|
|
31
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
32
|
+
"Typing :: Typed",
|
|
33
|
+
]
|
|
34
|
+
dependencies = [
|
|
35
|
+
"torch>=2.2",
|
|
36
|
+
"safetensors>=0.4.3",
|
|
37
|
+
"numpy>=1.24",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[project.urls]
|
|
41
|
+
Homepage = "https://github.com/tensorforger/VaeZip"
|
|
42
|
+
Issues = "https://github.com/tensorforger/VaeZip/issues"
|
|
43
|
+
Changelog = "https://github.com/tensorforger/VaeZip/blob/main/CHANGELOG.md"
|
|
44
|
+
Benchmark = "https://github.com/tensorforger/LatentStorageBenchmark"
|
|
45
|
+
|
|
46
|
+
[dependency-groups]
|
|
47
|
+
dev = [
|
|
48
|
+
"build>=1.2",
|
|
49
|
+
"mypy>=1.10",
|
|
50
|
+
"pre-commit>=3.7",
|
|
51
|
+
"pytest>=8.0",
|
|
52
|
+
"ruff>=0.5",
|
|
53
|
+
"twine>=5.1",
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
[tool.setuptools.packages.find]
|
|
57
|
+
where = ["src"]
|
|
58
|
+
|
|
59
|
+
[tool.setuptools.package-data]
|
|
60
|
+
vaezip = ["py.typed"]
|
|
61
|
+
|
|
62
|
+
[tool.ruff]
|
|
63
|
+
line-length = 88
|
|
64
|
+
target-version = "py310"
|
|
65
|
+
src = ["src", "tests"]
|
|
66
|
+
|
|
67
|
+
[tool.ruff.lint]
|
|
68
|
+
select = ["E", "F", "W", "I", "UP", "B", "SIM", "RUF"]
|
|
69
|
+
|
|
70
|
+
[tool.mypy]
|
|
71
|
+
strict = true
|
|
72
|
+
mypy_path = "src"
|
|
73
|
+
explicit_package_bases = true
|
|
74
|
+
files = ["src/vaezip"]
|
|
75
|
+
|
|
76
|
+
[tool.pytest.ini_options]
|
|
77
|
+
testpaths = ["tests"]
|
|
78
|
+
addopts = ["-ra", "--strict-markers", "--strict-config"]
|
vaezip-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""VaeZip: compression of VAE latents."""
|
|
2
|
+
|
|
3
|
+
from vaezip import codecs
|
|
4
|
+
from vaezip._version import __version__
|
|
5
|
+
from vaezip.api import load, save
|
|
6
|
+
from vaezip.encoded_tensor import EncodedTensor, deserialize, serialize
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"EncodedTensor",
|
|
10
|
+
"__version__",
|
|
11
|
+
"codecs",
|
|
12
|
+
"deserialize",
|
|
13
|
+
"load",
|
|
14
|
+
"save",
|
|
15
|
+
"serialize",
|
|
16
|
+
]
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""High level save and load of tensors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import overload
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
from vaezip.codecs.auto import AutoCodec
|
|
12
|
+
from vaezip.codecs.base import Codec
|
|
13
|
+
from vaezip.codecs.config import without_version
|
|
14
|
+
from vaezip.codecs.shortcuts import DEFAULT_SHORTCUT
|
|
15
|
+
from vaezip.encoded_tensor import (
|
|
16
|
+
PTH_FORMAT,
|
|
17
|
+
SAFETENSORS_FORMAT,
|
|
18
|
+
EncodedTensor,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
CodecSpecification = Codec | str | os.PathLike[str]
|
|
22
|
+
PTH_SUFFIXES = (".pth", ".pt")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _resolve_codec(codec: CodecSpecification | None) -> Codec:
|
|
26
|
+
if codec is None:
|
|
27
|
+
return AutoCodec.from_config(DEFAULT_SHORTCUT)
|
|
28
|
+
if isinstance(codec, Codec):
|
|
29
|
+
return codec
|
|
30
|
+
return AutoCodec.from_config(codec)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _infer_format(path: str | os.PathLike[str], format: str | None) -> str:
|
|
34
|
+
if format is not None:
|
|
35
|
+
return format
|
|
36
|
+
return PTH_FORMAT if Path(path).suffix in PTH_SUFFIXES else SAFETENSORS_FORMAT
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@overload
|
|
40
|
+
def save(
|
|
41
|
+
tensor: torch.Tensor,
|
|
42
|
+
path: None = None,
|
|
43
|
+
codec: CodecSpecification | None = None,
|
|
44
|
+
save_metadata: bool = True,
|
|
45
|
+
format: str | None = None,
|
|
46
|
+
) -> bytes: ...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@overload
|
|
50
|
+
def save(
|
|
51
|
+
tensor: torch.Tensor,
|
|
52
|
+
path: str | os.PathLike[str],
|
|
53
|
+
codec: CodecSpecification | None = None,
|
|
54
|
+
save_metadata: bool = True,
|
|
55
|
+
format: str | None = None,
|
|
56
|
+
) -> None: ...
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def save(
|
|
60
|
+
tensor: torch.Tensor,
|
|
61
|
+
path: str | os.PathLike[str] | None = None,
|
|
62
|
+
codec: CodecSpecification | None = None,
|
|
63
|
+
save_metadata: bool = True,
|
|
64
|
+
format: str | None = None,
|
|
65
|
+
) -> bytes | None:
|
|
66
|
+
"""
|
|
67
|
+
Encodes the tensor and writes it to a file, or returns bytes if there is no path.
|
|
68
|
+
|
|
69
|
+
args:
|
|
70
|
+
tensor: [B, ...], floating point
|
|
71
|
+
path: output file, `None` to return bytes
|
|
72
|
+
codec: codec object, shortcut name or config path, default is "cast_fp32"
|
|
73
|
+
save_metadata: store the codec config, required by `load()` without a codec
|
|
74
|
+
format: "safetensors" or "pth", by default inferred from the path suffix
|
|
75
|
+
(safetensors if unknown)
|
|
76
|
+
"""
|
|
77
|
+
resolved_codec = _resolve_codec(codec)
|
|
78
|
+
if path is None:
|
|
79
|
+
serialization_format = format or SAFETENSORS_FORMAT
|
|
80
|
+
else:
|
|
81
|
+
serialization_format = _infer_format(path, format)
|
|
82
|
+
data = resolved_codec.encode(tensor).serialize(
|
|
83
|
+
save_metadata=save_metadata, format=serialization_format
|
|
84
|
+
)
|
|
85
|
+
if path is None:
|
|
86
|
+
return data
|
|
87
|
+
Path(path).write_bytes(data)
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def load(
|
|
92
|
+
source: str | os.PathLike[str] | bytes | bytearray,
|
|
93
|
+
codec: CodecSpecification | None = None,
|
|
94
|
+
dtype: torch.dtype = torch.float32,
|
|
95
|
+
device: torch.device | str | None = None,
|
|
96
|
+
format: str | None = None,
|
|
97
|
+
) -> torch.Tensor:
|
|
98
|
+
"""
|
|
99
|
+
Reads a file or bytes written by `save()` and decodes the tensor.
|
|
100
|
+
|
|
101
|
+
args:
|
|
102
|
+
source: file path or bytes
|
|
103
|
+
codec: codec object, shortcut name or config path, by default the codec
|
|
104
|
+
from the metadata. If both are available they must have the same config.
|
|
105
|
+
dtype: floating point dtype of the result
|
|
106
|
+
device: device to decode on, default is CPU
|
|
107
|
+
format: "safetensors" or "pth", by default inferred from the path suffix
|
|
108
|
+
(safetensors for bytes)
|
|
109
|
+
returns:
|
|
110
|
+
tensor: [B, ...], original shape, dtype: dtype
|
|
111
|
+
"""
|
|
112
|
+
if isinstance(source, (bytes, bytearray)):
|
|
113
|
+
data = bytes(source)
|
|
114
|
+
serialization_format = format or SAFETENSORS_FORMAT
|
|
115
|
+
else:
|
|
116
|
+
data = Path(source).read_bytes()
|
|
117
|
+
serialization_format = _infer_format(source, format)
|
|
118
|
+
encoded = EncodedTensor.deserialize(data, format=serialization_format)
|
|
119
|
+
stored_config = encoded.codec_config
|
|
120
|
+
|
|
121
|
+
if codec is None:
|
|
122
|
+
if stored_config is None:
|
|
123
|
+
raise ValueError(
|
|
124
|
+
"The data has no codec config in its metadata, "
|
|
125
|
+
"pass the codec explicitly"
|
|
126
|
+
)
|
|
127
|
+
resolved_codec = AutoCodec.from_config(stored_config)
|
|
128
|
+
else:
|
|
129
|
+
resolved_codec = _resolve_codec(codec)
|
|
130
|
+
if stored_config is not None and without_version(
|
|
131
|
+
stored_config
|
|
132
|
+
) != without_version(resolved_codec.get_config()):
|
|
133
|
+
raise ValueError(
|
|
134
|
+
f"The codec {resolved_codec!r} does not match the config stored in the "
|
|
135
|
+
f"data: {stored_config}"
|
|
136
|
+
)
|
|
137
|
+
if device is not None:
|
|
138
|
+
encoded = encoded.to(device)
|
|
139
|
+
return resolved_codec.decode(encoded, dtype=dtype)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Codecs for compression of VAE latents."""
|
|
2
|
+
|
|
3
|
+
from vaezip.codecs.auto import AutoCodec
|
|
4
|
+
from vaezip.codecs.base import Codec
|
|
5
|
+
from vaezip.codecs.block_range_quant import BlockRangeQuantCodec
|
|
6
|
+
from vaezip.codecs.cast import CastCodec
|
|
7
|
+
from vaezip.codecs.lloyd_block_range_quant import LloydBlockRangeQuantCodec
|
|
8
|
+
from vaezip.codecs.range_quant import RangeQuantCodec
|
|
9
|
+
from vaezip.codecs.shortcuts import DEFAULT_SHORTCUT, list_shortcuts
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"DEFAULT_SHORTCUT",
|
|
13
|
+
"AutoCodec",
|
|
14
|
+
"BlockRangeQuantCodec",
|
|
15
|
+
"CastCodec",
|
|
16
|
+
"Codec",
|
|
17
|
+
"LloydBlockRangeQuantCodec",
|
|
18
|
+
"RangeQuantCodec",
|
|
19
|
+
"list_shortcuts",
|
|
20
|
+
]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Construction of codecs from configs without knowing the codec class."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from vaezip.codecs.base import Codec
|
|
6
|
+
from vaezip.codecs.block_range_quant import BlockRangeQuantCodec
|
|
7
|
+
from vaezip.codecs.cast import CastCodec
|
|
8
|
+
from vaezip.codecs.config import ConfigSource, split_config
|
|
9
|
+
from vaezip.codecs.lloyd_block_range_quant import LloydBlockRangeQuantCodec
|
|
10
|
+
from vaezip.codecs.range_quant import RangeQuantCodec
|
|
11
|
+
|
|
12
|
+
CODEC_CLASSES: dict[str, type[Codec]] = {
|
|
13
|
+
codec_class.__name__: codec_class
|
|
14
|
+
for codec_class in (
|
|
15
|
+
CastCodec,
|
|
16
|
+
RangeQuantCodec,
|
|
17
|
+
BlockRangeQuantCodec,
|
|
18
|
+
LloydBlockRangeQuantCodec,
|
|
19
|
+
)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class AutoCodec:
|
|
24
|
+
"""Builds the right codec class from a config."""
|
|
25
|
+
|
|
26
|
+
def __init__(self) -> None:
|
|
27
|
+
raise TypeError("AutoCodec is not instantiable, use AutoCodec.from_config()")
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def from_config(config: ConfigSource, **overrides: Any) -> Codec:
|
|
31
|
+
"""
|
|
32
|
+
args:
|
|
33
|
+
config: path to a JSON config, a shortcut name such as "cast_fp16",
|
|
34
|
+
or a config dict
|
|
35
|
+
overrides: constructor parameters that replace the ones from the config
|
|
36
|
+
"""
|
|
37
|
+
class_name, parameters = split_config(config, overrides)
|
|
38
|
+
if class_name is None:
|
|
39
|
+
raise ValueError("Config has no '_class_name' entry")
|
|
40
|
+
if class_name not in CODEC_CLASSES:
|
|
41
|
+
raise ValueError(
|
|
42
|
+
f"Unknown codec class {class_name!r}, available: {list(CODEC_CLASSES)}"
|
|
43
|
+
)
|
|
44
|
+
return CODEC_CLASSES[class_name](**parameters)
|