tcache 0.2.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.
@@ -0,0 +1,37 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.pyo
5
+ *.pyd
6
+ *.egg-info/
7
+ dist/
8
+ build/
9
+ *.whl
10
+ .venv/
11
+ .venv-mdv6/
12
+ .pytest_cache/
13
+ *.egg
14
+
15
+ # Data / large binaries
16
+ *.tgz
17
+ *.tar
18
+ *.zip
19
+ data/
20
+ *_int8.bin
21
+ *_scales.bin
22
+ *_zp.bin
23
+ *_pixels.bin
24
+ *_meta.json
25
+ *_pixel_meta.json
26
+ !compression_benchmark_results.json
27
+
28
+ # IDE
29
+ .vscode/
30
+ .idea/
31
+ *.swp
32
+ *.swo
33
+ .DS_Store
34
+ Thumbs.db
35
+
36
+ # Triton cache
37
+ triton_cache/
tcache-0.2.0/AGENTS.md ADDED
@@ -0,0 +1,133 @@
1
+ # AGENTS.md — TensorCache
2
+
3
+ > Guidance for AI coding agents working in this repo. Keep this file concise, factual, and up-to-date.
4
+
5
+ ## 1. Project Overview
6
+
7
+ **TensorCache** (`tensorcache`, v0.1.0) — Ultra-fast, high-fidelity block-wise INT8 feature & pixel cache engine for PyTorch.
8
+
9
+ Two bottlenecks solved:
10
+ 1. **Feature Cache Bloat:** Block-wise microscaled INT8 (`G=32`, BF16 scales) — `1.88×` compression vs BF16, `0.54%` rel RMSE (see `compression_benchmark_results.json:190-201`, `README.md:77-81`).
11
+ 2. **JPEG/PNG CPU Decode:** Zero-copy `np.memmap` + GPU stream prefetching — `>2000 MB/s` throughput (`README.md:6-7`, `src/tensorcache/pixel_cache.py:95-137`, `src/tensorcache/feature_cache.py:112-210`).
12
+
13
+ Installation: `pip install tensorcache` or `pip install -e .` from repo root. Python `>=3.9`, `torch>=2.0`, `numpy>=1.20` (`pyproject.toml:16-18`). Optional `fast` extras: `triton`, `zstandard`, `blosc2`, `safetensors` (`pyproject.toml:21-27`) — note `triton` is skipped on Windows (`platform_system != 'Windows'`).
14
+
15
+ ## 2. Repo Structure
16
+
17
+ ```
18
+ /
19
+ ├── src/tensorcache/
20
+ │ ├── __init__.py # public API re-exports
21
+ │ ├── codec.py # BlockwiseInt8Codec, quantize/dequantize (core)
22
+ │ ├── fused_ops.py # Triton fused kernels (requires CUDA/ROCm + Triton)
23
+ │ ├── feature_cache.py # FeatureCacheWriter / FeatureCacheDataset (mmap .bin + .json)
24
+ │ ├── pixel_cache.py # PixelCacheWriter / PixelCacheDataset (raw uint8 mmap)
25
+ │ ├── prefetcher.py # AsyncGPUPrefetcher (double-buffered CUDA stream)
26
+ │ └── streamer.py # ZeroCopyTensorStreamer (pinned + ring-buffered)
27
+ ├── tests/
28
+ │ ├── test_codec.py # codec + feature/pixel disk I/O tests
29
+ │ └── test_fused_ops.py # GPU-only, skipped if !torch.cuda.is_available()
30
+ ├── benchmarks/
31
+ │ ├── bench_memory_opt.py
32
+ │ ├── benchmark_dual_gpu.py
33
+ │ ├── speed_test_rigorous.py
34
+ │ └── tune_dequant.py
35
+ ├── analyze_compression_error.py # full pixel+feature benchmark (tabulate)
36
+ ├── experiment_blockwise_int8.py # G-sweep, symmetric/asymmetric, bitwidth
37
+ ├── download_test_dataset.py # Imagenette-320 fetcher -> data/test_images
38
+ ├── pyproject.toml
39
+ └── README.md
40
+ ```
41
+
42
+ Data dirs: `data/` (contains `imagenette2-320.tgz`, `flowers-102/102flowers.tgz` — do not commit large binaries). Cache files are runtime-generated (`*_int8.bin`, `*_scales.bin`, `*_pixels.bin`, `*_meta.json`, `*_pixel_meta.json`) — gitignore them.
43
+
44
+ ## 3. Build / Run / Test Commands
45
+
46
+ ```bash
47
+ # install (dev)
48
+ pip install -e ".[fast,dev]"
49
+
50
+ # run all tests (fused tests auto-skip on CPU/Windows)
51
+ pytest -v
52
+ pytest tests/test_codec.py -v
53
+ pytest tests/test_fused_ops.py -v # requires CUDA + Triton
54
+
55
+ # single-file direct run (no pytest)
56
+ python tests/test_codec.py
57
+
58
+ # benchmarks / analysis (require data images)
59
+ python analyze_compression_error.py # needs Plant dataset or data/test_images fallback
60
+ python experiment_blockwise_int8.py # needs CUDA + timm + Plant data
61
+ python download_test_dataset.py # fetches Imagenette-320 (~326 MB) to data/test_images
62
+ python benchmarks/speed_test_rigorous.py
63
+ python benchmarks/tune_dequant.py
64
+
65
+ # Windows note: Triton unavailable -> codec falls back to vectorized PyTorch path (codec.py:167-177)
66
+ ```
67
+
68
+ No `Makefile`, no `opencode.json` yet, no CI config in repo. Use `pytest>=7.0` (`pyproject.toml:29`).
69
+
70
+ ## 4. Core Architecture — Read Before Editing
71
+
72
+ ### 4.1 Codec (`src/tensorcache/codec.py:40-202`)
73
+ - `quantize_int8_g32(x, group_size=32)` — flatten, pad to multiple of `G`, `view(-1,G)`, `amax`, `scales = max/127 -> BF16`, `round(x/scale) clamp [-128,127] -> int8`. Returns `(q_int8 (flat 1D), scales (1D BF16), orig_shape)` (`codec.py:40-75`).
74
+ - `quantize_int8_adaptive` — AdaRound-style parallel candidate search over `linspace(0.90,1.05,31)` per block, picks min L2 error (`codec.py:78-126`). ~10% lower error, heavier.
75
+ - `dequantize_int8_g32` — Triton path if `HAS_TRITON and device.type in (cuda,hip)` using `_triton_dequant_kernel` (`codec.py:22-37`, `150-165`) else padded `view(-1,G) * scales` + copy into `out_buffer` (`codec.py:167-177`). `out_buffer` avoids allocator overhead — preserve this API.
76
+ - `BlockwiseInt8Codec` wrapper (`codec.py:180-202`) — `group_size` + `adaptive` flag. Keep `group_size=32` as default; benchmarks assume it.
77
+
78
+ **Invariants:**
79
+ - Scales stored as BF16 (`torch.bfloat16`) on disk as `uint16` bitcast: `scales.view(torch.int16).cpu().numpy().view(np.uint16)` (`feature_cache.py:80`) and restored via `view(np.int16).copy()).view(torch.bfloat16)` (`feature_cache.py:153`). Do not change dtype without migrating file format.
80
+ - Padding is trimmed on return (`flatten()[:numel]`). Keep.
81
+ - Storage cost: `1 + 2/32 = 1.0625 B/elem` (`analyze_compression_error.py:515`, `559`).
82
+
83
+ ### 4.2 Feature Cache (`src/tensorcache/feature_cache.py:21-211`)
84
+ - **Writer:** pre-allocates `np.memmap` `w+` with shape `(num_samples, seq_len, dim)` int8 and `(num_samples, scales_per_sample)` uint16 (`feature_cache.py:53-60`). `append` handles both `[seq_len,dim]` and `[B,seq_len,dim]` (`feature_cache.py:63-81`). `close()` flushes, closes `_mmap`, writes `_meta.json` with `num_samples = current_idx` (`feature_cache.py:83-109`). Must call `close()` — Windows holds file lock otherwise.
85
+ - **Dataset:** read-only mmap `mode="r"` (`feature_cache.py:134-142`). `__getitem__` copies via `arr.copy()` before `torch.from_numpy` to avoid memmap lifetime issues, then optional `auto_dequant_device` fused dequant (`feature_cache.py:147-163`). `iter_batches` does C-level batch slice `mmap[batch_idx]` → `torch.from_numpy(...).to(device)` (`feature_cache.py:165-197`).
86
+ - `close()` releases `_mmap` handles (`feature_cache.py:199-210`) — critical on Windows.
87
+
88
+ ### 4.3 Pixel Cache (`src/tensorcache/pixel_cache.py:25-137`)
89
+ - Raw `uint8` mmap `(N,H,W,C)` (`pixel_cache.py:48-51`). `append_image` accepts `np.ndarray | PIL.Image | torch.Tensor | str|Path` and resizes to `(width,height)` via `BILINEAR` (`pixel_cache.py:54-74`). `PixelCacheDataset.__getitem__` returns `torch.uint8 [H,W,C]` with `arr.copy()` (`pixel_cache.py:122-129`).
90
+
91
+ ### 4.4 Fused Ops (`src/tensorcache/fused_ops.py:1-233`)
92
+ - **Requires Triton + CUDA/ROCm** — hard import `import triton` at top (`fused_ops.py:17-18`) will fail on Windows/CPU. Guard imports or make optional if editing.
93
+ - Three kernels: `_fused_quant_kernel` (`fused_ops.py:24-52`), `_fused_dequant_kernel` (`fused_ops.py:82-96`), `_fused_dequant_matmul_kernel` (`fused_ops.py:119-184`). `FusedDequantLinear` (`fused_ops.py:187-233`) fuses `Dequant + GEMM + bias` in registers — zero intermediate VRAM.
94
+ - Tests skip if `!torch.cuda.is_available()` (`tests/test_fused_ops.py:15,32`).
95
+
96
+ ### 4.5 Prefetcher & Streamer
97
+ - `AsyncGPUPrefetcher` (`src/tensorcache/prefetcher.py:11-67`) — wraps any `DataLoader`, uses `torch.cuda.Stream` + `non_blocking=True` double buffer. `device.type in (cuda,hip)` check; `stream=None` on CPU.
98
+ - `ZeroCopyTensorStreamer` (`src/tensorcache/streamer.py:19-163`) — pinnned CPU buffers `pin_memory=True` + GPU ring buffers `out_bf16_0/1` (`streamer.py:62-77`), `np.copyto` into pinned, async `copy_(non_blocking=True)`, `wait_stream`, dequant into ring target (`streamer.py:96-117`). Fixed ~45 MB footprint. `close()` synchronizes and deletes buffers (`streamer.py:129-163`).
99
+
100
+ ## 5. Conventions & Pitfalls
101
+
102
+ - **Paths:** Windows dev machine (`win32`, `C:\Users\armor\Desktop\AI pipeline\...`). Use `pathlib.Path`, `os.path`, never hardcode `/`. Prefix handling: `str(prefix)+"_int8.bin"` etc. (`feature_cache.py:48-50`).
103
+ - **Dtype discipline:** Features are `bfloat16` throughout; scales are BF16 on wire; raw pixels are `uint8`. Don't silently upcast to FP32 except in metrics (`analyze_compression_error.py:170-205`).
104
+ - **Triton fallback:** Any change to `codec.py` dequant must keep both Triton and PyTorch fallback paths bit-identical. Test on CPU.
105
+ - **Memmap lifecycle:** Always provide `close()` and call it in tests (`tests/test_codec.py:78-80,102-104`). On Windows, open mmap prevents deletion.
106
+ - **No dynamic allocations in hot path:** Streamer/prefetcher are designed for zero allocation — avoid `torch.empty` inside loops without `out_buffer`.
107
+ - **Benchmark thresholds:** Rel RMSE `<1.0%` is the pass criterion (`tests/test_codec.py:36,51`, `tests/test_fused_ops.py:28`). Real Block-32 RMSE ~0.54% vs Naive FP8 ~2.6-5.2% (`compression_benchmark_results.json:126-148`, `190-201`).
108
+ - **Security:** `tar.extractall` in `download_test_dataset.py:28` — keep as is for now but don't expand without validation if hardening.
109
+ - **Formatting:** No enforced formatter; follow existing style (4-space indent, `from __future__ import annotations`, type hints).
110
+
111
+ ## 6. Editing Guidelines for Agents
112
+
113
+ - Prefer `Read`/`Edit` over `bash` for files; use `bash` only for `pytest`, `python`, `git` ops.
114
+ - Verify with `pytest tests/test_codec.py -v` after codec/cache edits; run `python tests/test_codec.py` as quick sanity.
115
+ - If touching `fused_ops.py`, guard `import triton` with try/except like `codec.py:13-19` or ensure CI skips gracefully.
116
+ - When adding new cache formats, bump `meta.json` fields and handle backward compat in `FeatureCacheDataset.__init__`.
117
+ - Don't commit `data/*.tgz`, `*_int8.bin`, `*_scales.bin`, `*_pixels.bin`, `__pycache__`.
118
+ - Keep `src/tensorcache/__init__.py:1-42` exports in sync when adding public symbols (update `__all__`).
119
+
120
+ ## 7. Useful References
121
+
122
+ - API docs & benchmarks: `README.md:1-86`
123
+ - Public API: `src/tensorcache/__init__.py:5-42`
124
+ - Error metrics: `analyze_compression_error.py:170-205`, `experiment_blockwise_int8.py:20-40`
125
+ - Compression tables: `compression_benchmark_results.json:2-216` (pixel + feature)
126
+ - Dataset prep: `download_test_dataset.py:7-44`
127
+
128
+ ## 8. Agent Context — Current Environment
129
+
130
+ - **OS:** Windows (`win32`), PowerShell 7+ (`pwsh`), `workdir` param preferred over `cd`.
131
+ - **Python:** `>=3.9`, `torch>=2.0` installed; Triton unavailable on Windows (fallback path active).
132
+ - **No git repo** at workspace root (`Is directory a git repo: no`) — `git` commands will fail until `git init`.
133
+ - **Today:** 2026-08-29 (use for searches).
tcache-0.2.0/LICENSE ADDED
@@ -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 TensorCache Authors
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.
tcache-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.5
2
+ Name: tcache
3
+ Version: 0.2.0
4
+ Summary: Ultra-fast, high-fidelity block-wise INT8 feature & pixel cache engine for ML pipelines
5
+ Author: TensorCache Authors
6
+ License: Apache-2.0
7
+ License-File: LICENSE
8
+ Keywords: caching,cnn,compression,cuda,gpu,int8,pytorch,quantization,rocm,triton,vit
9
+ Requires-Python: >=3.9
10
+ Requires-Dist: numpy>=1.20.0
11
+ Requires-Dist: torch>=2.0.0
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest>=7.0.0; extra == 'dev'
14
+ Requires-Dist: rich>=13.0.0; extra == 'dev'
15
+ Requires-Dist: tabulate>=0.9.0; extra == 'dev'
16
+ Provides-Extra: fast
17
+ Requires-Dist: blosc2>=2.0.0; extra == 'fast'
18
+ Requires-Dist: safetensors>=0.4.0; extra == 'fast'
19
+ Requires-Dist: triton>=2.0.0; (platform_system != 'Windows') and extra == 'fast'
20
+ Requires-Dist: zstandard>=0.20.0; extra == 'fast'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # TensorCache ⚡
24
+
25
+ **Ultra-fast, high-fidelity block-wise INT8 feature & pixel cache engine for PyTorch.**
26
+
27
+ `tensorcache` eliminates two bottlenecks:
28
+ 1. **Feature Cache Bloat:** `AMO-BQ` asymmetric MSE-optimal `G32` `1.09B` `1.83x` vs BF16 `0.47%` `rel RMSE` (`sym 1.06B 0.54%`) — near `G16` floor `0.39%`.
29
+ 2. **JPEG/PNG CPU Decode:** Zero-copy `mmap` + `GPU` stream prefetch `>2,000 MB/s`, ring-buffer `6.8MB` `VRAM` `batch8 128x768`.
30
+
31
+ ---
32
+
33
+ ## 🚀 Key Features
34
+
35
+ * **AMO-BQ (Asymmetric MSE-Optimal, G32):** `min-max + zp uint8 + 48×` clipping search `[0.95,1.10]` — `0.47%` `hetero 0.54%` vs `sym 0.74%` (`-26%`), `per-token 1.73%` (`cache\dtype_comparison.json`). Presets `fast/balanced/accurate/max`.
36
+ * **Microsecond Dequant:** `Triton` `(q-zp)*scale -> BF16` `0.06ms 5.4M 337GB/s` (`codec.py:40`), `FusedDequantLinear` `0` intermediate `fused_ops.py:119`.
37
+ * **Minimal VRAM:** `q 5.22MB + scales 0.32MB + zp 0.16MB + out 10.45MB` `5.4M`; `Streamer` fixed `~43MB` `double-buffer` `out_buffer` reuse, `G64` halves `scales/zp`.
38
+ * **Cross-Platform:** `CUDA`/`ROCm` `Triton` else `PyTorch` fallback, `Windows` `mmap` safe `close()`.
39
+ * **CLI + Python one-liners:** `tc.compress` / `tc.benchmark_tensor` / `tensorcache benchmark`.
40
+
41
+ ---
42
+
43
+ ## 📦 Installation
44
+
45
+ ```bash
46
+ pip install tensor-cache # PyPI (import tensorcache)
47
+ pip install -e . # dev
48
+ pip install -e ".[fast]" # triton+zstd+blosc2 (Linux)
49
+ ```
50
+
51
+ ---
52
+
53
+ ## ⚡ Quick Start
54
+
55
+ ### 1. In-Memory (one-liners)
56
+ ```python
57
+ import torch, tensorcache as tc
58
+
59
+ x = torch.randn(16,446,768, dtype=torch.bfloat16, device="cuda")
60
+
61
+ # AMO-BQ presets: fast (16,0.95-1.05) 6.9ms 0.49%, balanced (32,0.95-1.05) 13ms 0.478% (default), accurate (48,0.95-1.10) 49ms 0.473%
62
+ q,s,zp,shape = tc.compress(x, mode="balanced") # or "fast"/"accurate"/"max"/"sym"/"adaptive"
63
+ rec = tc.decompress(q,s,shape,zp) # <0.1ms BF16
64
+ tc.benchmark_tensor(x) # rich table
65
+ tc.estimate_compression(x.shape, group_size=32) # 1.09375 B 1.83x
66
+ tc.auto_select_mode(x, target_rmse=0.5) # -> "balanced"
67
+ tc.help() # python help
68
+
69
+ # Codec object
70
+ codec = tc.BlockwiseInt8Codec(group_size=32, amo_bq=True, amo_mode="balanced")
71
+ print(codec) # G=32, amo_bq=balanced 1.0938B 1:1.83x
72
+ ```
73
+
74
+ ### 2. Feature Cache to Disk (mmap)
75
+ ```python
76
+ import tensorcache as tc
77
+ from torch.utils.data import DataLoader
78
+
79
+ # Write (amo_bq, G32 default balanced, G64 for minimal VRAM 1.046B 0.55%)
80
+ writer = tc.FeatureCacheWriter("./cache/dinov3", 10000,446,768, group_size=32, amo_bq=True, amo_mode="balanced")
81
+ writer.append(x) # [seq,dim] or [B,seq,dim]
82
+ writer.close() # writes _int8.bin (uint8) _scales.bin _zp.bin _meta.json
83
+
84
+ # Load
85
+ ds = tc.FeatureCacheDataset("./cache/dinov3") # -> (q uint8, s BF16, zp uint8)
86
+ ds = tc.FeatureCacheDataset("./cache/dinov3", auto_dequant_device="cuda") # -> BF16 directly
87
+ for q,s,zp in tc.AsyncGPUPrefetcher(DataLoader(ds,batch_size=256,pin_memory=True), device="cuda"):
88
+ batch = tc.dequantize_int8_amo_bq(q,s,zp, shape, group_size=32)
89
+
90
+ # Minimal VRAM streamer (fixed ~43MB, zero alloc)
91
+ streamer = tc.ZeroCopyTensorStreamer("./cache/dinov3", batch_size=32, device="cuda")
92
+ for batch in streamer: # BF16 [B,seq,dim] from ring buffer out_bf16_0/1
93
+ train(batch)
94
+ streamer.close()
95
+
96
+ # Fused head (no BF16 intermediate)
97
+ from tensorcache import FusedDequantLinear
98
+ head = FusedDequantLinear(768, num_classes, group_size=32).cuda()
99
+ logits = head(q, s) # dequant+GEMM in regs
100
+ ```
101
+
102
+ ### 3. CLI
103
+ ```bash
104
+ python -m tensorcache info
105
+ python -m tensorcache benchmark --shape 16,446,768 --device cuda
106
+ python -m tensorcache cache-info --prefix ./cache/dinov3
107
+ python -m tensorcache compress-demo --shape 4,197,768 --mode balanced
108
+ tensorcache --help
109
+ ```
110
+
111
+ ---
112
+
113
+ ## 📊 Benchmark (DINOv3 ViT-Base, 5.4M randn + RSNA hetero)
114
+
115
+ | Format | B/elem | vs BF16 | rel RMSE |Outlier 0.1%| Dequant |
116
+ |---|:---:|---|:---:|:---:|---|
117
+ | Raw BF16 |2.00|1.00x|0.167%|0.119%|—|
118
+ | Naive FP8 E5M2 |1.00|2.00x|5.24%|6.81%|—|
119
+ | Naive FP8 E4M3 |1.00|2.00x|2.63%|3.19%|—|
120
+ | MXFP8 G32 |1.09|1.83x|2.38%|—|—|
121
+ | **Sym G32** |**1.06**|**1.88x**|**0.540%**|**0.11%**|**0.036ms 435GB/s**|
122
+ | **AMO-BQ fast G32** |1.093|1.83x|0.490%|0.15%|0.06ms 337GB/s|
123
+ | **AMO-BQ balanced G32** |**1.093**|**1.83x**|**0.478%**|0.15%|13ms quant|
124
+ | **AMO-BQ accurate G32** |1.093|1.83x|0.473%|—|49ms quant|
125
+ | **AMO-BQ G16** |1.187|1.68x|**0.395%**|—|13ms|
126
+ | **Sym G64** |1.046|1.91x|0.55%|—|—|
127
+
128
+ ---
129
+
130
+ ## 📜 License
131
+ Apache 2.0 — see `LICENSE`.
tcache-0.2.0/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # TensorCache ⚡
2
+
3
+ **Ultra-fast, high-fidelity block-wise INT8 feature & pixel cache engine for PyTorch.**
4
+
5
+ `tensorcache` eliminates two bottlenecks:
6
+ 1. **Feature Cache Bloat:** `AMO-BQ` asymmetric MSE-optimal `G32` `1.09B` `1.83x` vs BF16 `0.47%` `rel RMSE` (`sym 1.06B 0.54%`) — near `G16` floor `0.39%`.
7
+ 2. **JPEG/PNG CPU Decode:** Zero-copy `mmap` + `GPU` stream prefetch `>2,000 MB/s`, ring-buffer `6.8MB` `VRAM` `batch8 128x768`.
8
+
9
+ ---
10
+
11
+ ## 🚀 Key Features
12
+
13
+ * **AMO-BQ (Asymmetric MSE-Optimal, G32):** `min-max + zp uint8 + 48×` clipping search `[0.95,1.10]` — `0.47%` `hetero 0.54%` vs `sym 0.74%` (`-26%`), `per-token 1.73%` (`cache\dtype_comparison.json`). Presets `fast/balanced/accurate/max`.
14
+ * **Microsecond Dequant:** `Triton` `(q-zp)*scale -> BF16` `0.06ms 5.4M 337GB/s` (`codec.py:40`), `FusedDequantLinear` `0` intermediate `fused_ops.py:119`.
15
+ * **Minimal VRAM:** `q 5.22MB + scales 0.32MB + zp 0.16MB + out 10.45MB` `5.4M`; `Streamer` fixed `~43MB` `double-buffer` `out_buffer` reuse, `G64` halves `scales/zp`.
16
+ * **Cross-Platform:** `CUDA`/`ROCm` `Triton` else `PyTorch` fallback, `Windows` `mmap` safe `close()`.
17
+ * **CLI + Python one-liners:** `tc.compress` / `tc.benchmark_tensor` / `tensorcache benchmark`.
18
+
19
+ ---
20
+
21
+ ## 📦 Installation
22
+
23
+ ```bash
24
+ pip install tensor-cache # PyPI (import tensorcache)
25
+ pip install -e . # dev
26
+ pip install -e ".[fast]" # triton+zstd+blosc2 (Linux)
27
+ ```
28
+
29
+ ---
30
+
31
+ ## ⚡ Quick Start
32
+
33
+ ### 1. In-Memory (one-liners)
34
+ ```python
35
+ import torch, tensorcache as tc
36
+
37
+ x = torch.randn(16,446,768, dtype=torch.bfloat16, device="cuda")
38
+
39
+ # AMO-BQ presets: fast (16,0.95-1.05) 6.9ms 0.49%, balanced (32,0.95-1.05) 13ms 0.478% (default), accurate (48,0.95-1.10) 49ms 0.473%
40
+ q,s,zp,shape = tc.compress(x, mode="balanced") # or "fast"/"accurate"/"max"/"sym"/"adaptive"
41
+ rec = tc.decompress(q,s,shape,zp) # <0.1ms BF16
42
+ tc.benchmark_tensor(x) # rich table
43
+ tc.estimate_compression(x.shape, group_size=32) # 1.09375 B 1.83x
44
+ tc.auto_select_mode(x, target_rmse=0.5) # -> "balanced"
45
+ tc.help() # python help
46
+
47
+ # Codec object
48
+ codec = tc.BlockwiseInt8Codec(group_size=32, amo_bq=True, amo_mode="balanced")
49
+ print(codec) # G=32, amo_bq=balanced 1.0938B 1:1.83x
50
+ ```
51
+
52
+ ### 2. Feature Cache to Disk (mmap)
53
+ ```python
54
+ import tensorcache as tc
55
+ from torch.utils.data import DataLoader
56
+
57
+ # Write (amo_bq, G32 default balanced, G64 for minimal VRAM 1.046B 0.55%)
58
+ writer = tc.FeatureCacheWriter("./cache/dinov3", 10000,446,768, group_size=32, amo_bq=True, amo_mode="balanced")
59
+ writer.append(x) # [seq,dim] or [B,seq,dim]
60
+ writer.close() # writes _int8.bin (uint8) _scales.bin _zp.bin _meta.json
61
+
62
+ # Load
63
+ ds = tc.FeatureCacheDataset("./cache/dinov3") # -> (q uint8, s BF16, zp uint8)
64
+ ds = tc.FeatureCacheDataset("./cache/dinov3", auto_dequant_device="cuda") # -> BF16 directly
65
+ for q,s,zp in tc.AsyncGPUPrefetcher(DataLoader(ds,batch_size=256,pin_memory=True), device="cuda"):
66
+ batch = tc.dequantize_int8_amo_bq(q,s,zp, shape, group_size=32)
67
+
68
+ # Minimal VRAM streamer (fixed ~43MB, zero alloc)
69
+ streamer = tc.ZeroCopyTensorStreamer("./cache/dinov3", batch_size=32, device="cuda")
70
+ for batch in streamer: # BF16 [B,seq,dim] from ring buffer out_bf16_0/1
71
+ train(batch)
72
+ streamer.close()
73
+
74
+ # Fused head (no BF16 intermediate)
75
+ from tensorcache import FusedDequantLinear
76
+ head = FusedDequantLinear(768, num_classes, group_size=32).cuda()
77
+ logits = head(q, s) # dequant+GEMM in regs
78
+ ```
79
+
80
+ ### 3. CLI
81
+ ```bash
82
+ python -m tensorcache info
83
+ python -m tensorcache benchmark --shape 16,446,768 --device cuda
84
+ python -m tensorcache cache-info --prefix ./cache/dinov3
85
+ python -m tensorcache compress-demo --shape 4,197,768 --mode balanced
86
+ tensorcache --help
87
+ ```
88
+
89
+ ---
90
+
91
+ ## 📊 Benchmark (DINOv3 ViT-Base, 5.4M randn + RSNA hetero)
92
+
93
+ | Format | B/elem | vs BF16 | rel RMSE |Outlier 0.1%| Dequant |
94
+ |---|:---:|---|:---:|:---:|---|
95
+ | Raw BF16 |2.00|1.00x|0.167%|0.119%|—|
96
+ | Naive FP8 E5M2 |1.00|2.00x|5.24%|6.81%|—|
97
+ | Naive FP8 E4M3 |1.00|2.00x|2.63%|3.19%|—|
98
+ | MXFP8 G32 |1.09|1.83x|2.38%|—|—|
99
+ | **Sym G32** |**1.06**|**1.88x**|**0.540%**|**0.11%**|**0.036ms 435GB/s**|
100
+ | **AMO-BQ fast G32** |1.093|1.83x|0.490%|0.15%|0.06ms 337GB/s|
101
+ | **AMO-BQ balanced G32** |**1.093**|**1.83x**|**0.478%**|0.15%|13ms quant|
102
+ | **AMO-BQ accurate G32** |1.093|1.83x|0.473%|—|49ms quant|
103
+ | **AMO-BQ G16** |1.187|1.68x|**0.395%**|—|13ms|
104
+ | **Sym G64** |1.046|1.91x|0.55%|—|—|
105
+
106
+ ---
107
+
108
+ ## 📜 License
109
+ Apache 2.0 — see `LICENSE`.