bigsmall 1.0.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 (42) hide show
  1. bigsmall-1.0.0/LICENSE +201 -0
  2. bigsmall-1.0.0/PKG-INFO +234 -0
  3. bigsmall-1.0.0/README.md +194 -0
  4. bigsmall-1.0.0/bigsmall/__init__.py +45 -0
  5. bigsmall-1.0.0/bigsmall/cli.py +124 -0
  6. bigsmall-1.0.0/bigsmall/codecs/__init__.py +19 -0
  7. bigsmall-1.0.0/bigsmall/codecs/bf16.py +170 -0
  8. bigsmall-1.0.0/bigsmall/codecs/fp16.py +135 -0
  9. bigsmall-1.0.0/bigsmall/codecs/fp32.py +119 -0
  10. bigsmall-1.0.0/bigsmall/codecs/fp4.py +76 -0
  11. bigsmall-1.0.0/bigsmall/codecs/fp8.py +56 -0
  12. bigsmall-1.0.0/bigsmall/codecs/generic.py +44 -0
  13. bigsmall-1.0.0/bigsmall/codecs/special.py +156 -0
  14. bigsmall-1.0.0/bigsmall/container.py +110 -0
  15. bigsmall-1.0.0/bigsmall/decoder.py +243 -0
  16. bigsmall-1.0.0/bigsmall/delta.py +32 -0
  17. bigsmall-1.0.0/bigsmall/encoder.py +413 -0
  18. bigsmall-1.0.0/bigsmall/formats.py +59 -0
  19. bigsmall-1.0.0/bigsmall/hub.py +286 -0
  20. bigsmall-1.0.0/bigsmall/hub_index.py +141 -0
  21. bigsmall-1.0.0/bigsmall/integrations/__init__.py +1 -0
  22. bigsmall-1.0.0/bigsmall/integrations/diffusion.py +99 -0
  23. bigsmall-1.0.0/bigsmall/integrations/huggingface.py +99 -0
  24. bigsmall-1.0.0/bigsmall/integrations/vllm.py +151 -0
  25. bigsmall-1.0.0/bigsmall/streaming.py +237 -0
  26. bigsmall-1.0.0/bigsmall/streaming_model.py +176 -0
  27. bigsmall-1.0.0/bigsmall/tensor_analysis.py +143 -0
  28. bigsmall-1.0.0/bigsmall/verify.py +50 -0
  29. bigsmall-1.0.0/bigsmall.egg-info/PKG-INFO +234 -0
  30. bigsmall-1.0.0/bigsmall.egg-info/SOURCES.txt +40 -0
  31. bigsmall-1.0.0/bigsmall.egg-info/dependency_links.txt +1 -0
  32. bigsmall-1.0.0/bigsmall.egg-info/entry_points.txt +2 -0
  33. bigsmall-1.0.0/bigsmall.egg-info/requires.txt +22 -0
  34. bigsmall-1.0.0/bigsmall.egg-info/top_level.txt +1 -0
  35. bigsmall-1.0.0/setup.cfg +4 -0
  36. bigsmall-1.0.0/setup.py +42 -0
  37. bigsmall-1.0.0/tests/test_delta.py +55 -0
  38. bigsmall-1.0.0/tests/test_diffusion.py +47 -0
  39. bigsmall-1.0.0/tests/test_hf_integration.py +110 -0
  40. bigsmall-1.0.0/tests/test_inference.py +52 -0
  41. bigsmall-1.0.0/tests/test_roundtrip.py +66 -0
  42. bigsmall-1.0.0/tests/test_streaming.py +124 -0
bigsmall-1.0.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 describing the origin of the Work and
141
+ 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 or system failure, or any and all other
162
+ commercial damages or losses), even if such Contributor has been
163
+ advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
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 BigSmall contributors
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
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
@@ -0,0 +1,234 @@
1
+ Metadata-Version: 2.4
2
+ Name: bigsmall
3
+ Version: 1.0.0
4
+ Summary: Lossless neural network weight compression
5
+ Home-page: https://github.com/wpferrell/bigsmall
6
+ Author: BigSmall contributors
7
+ Author-email: wpferrell@gmail.com
8
+ License: Apache-2.0
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: numpy>=1.24
13
+ Requires-Dist: constriction>=0.4
14
+ Requires-Dist: zstandard>=0.21
15
+ Requires-Dist: blosc2>=2.0
16
+ Requires-Dist: safetensors>=0.4
17
+ Provides-Extra: torch
18
+ Requires-Dist: torch>=2.0; extra == "torch"
19
+ Provides-Extra: hf
20
+ Requires-Dist: transformers>=4.30; extra == "hf"
21
+ Provides-Extra: diffusion
22
+ Requires-Dist: diffusers>=0.20; extra == "diffusion"
23
+ Provides-Extra: vllm
24
+ Requires-Dist: vllm>=0.4; extra == "vllm"
25
+ Provides-Extra: all
26
+ Requires-Dist: torch>=2.0; extra == "all"
27
+ Requires-Dist: transformers>=4.30; extra == "all"
28
+ Requires-Dist: diffusers>=0.20; extra == "all"
29
+ Dynamic: author
30
+ Dynamic: author-email
31
+ Dynamic: description
32
+ Dynamic: description-content-type
33
+ Dynamic: home-page
34
+ Dynamic: license
35
+ Dynamic: license-file
36
+ Dynamic: provides-extra
37
+ Dynamic: requires-dist
38
+ Dynamic: requires-python
39
+ Dynamic: summary
40
+
41
+ # BigSmall
42
+
43
+ Lossless neural network weight compression. One package, every float format,
44
+ every model. Compress big models so they fit (or load faster) on small hardware.
45
+
46
+ ## Why BigSmall
47
+
48
+ BigSmall is **lossless**, not quantization. After decompression the weights are
49
+ bit-for-bit identical to the original (md5-verified on every shard). You get the
50
+ same inference outputs as the uncompressed model — no quality degradation, no
51
+ fine-tune drift, no surprise accuracy regression on long-tail prompts.
52
+
53
+ Existing tools force a tradeoff: ZipNN (~83% ratio, FP32 only), DFloat11 (~68%,
54
+ BF16 only, ~2× slower inference at batch=1), ZipServ (~70%, BF16 only, H100-style
55
+ GPUs only). BigSmall covers FP32/BF16/FP16/FP8/FP4 in a single package, hits the
56
+ proven mathematical floor on each format, and adds no inference overhead — you
57
+ decompress once at load time and run at native speed.
58
+
59
+ It is the right tool when reproducibility, fine-tuning, or production quality
60
+ matters. Ollama-style 4-bit quantization gives you a smaller, **worse** version of
61
+ the model. BigSmall gives you a smaller version of **the same** model.
62
+
63
+ ## Install
64
+
65
+ ```bash
66
+ pip install bigsmall
67
+ ```
68
+
69
+ Optional extras: `pip install "bigsmall[torch]"`, `[hf]`, `[diffusion]`, `[vllm]`, `[all]`.
70
+
71
+ Requirements: Python 3.9+, PyTorch 2.0+, safetensors, numpy, zstandard, constriction.
72
+
73
+ ## Quick start
74
+
75
+ ```python
76
+ import bigsmall
77
+
78
+ # 1. Compress a safetensors model
79
+ bigsmall.compress("model.safetensors", "model.bs")
80
+
81
+ # 2. Load it back as a torch state_dict (one line, works on local path or HF repo)
82
+ sd = bigsmall.from_pretrained("./model.bs")
83
+ my_model.load_state_dict(sd, strict=False)
84
+
85
+ # 3. Stream layer-by-layer for models bigger than RAM
86
+ with bigsmall.StreamingLoader("model.bs", device="cuda") as L:
87
+ non_layer = L.load_non_layer_tensors()
88
+ for i, layer in L.iter_layers():
89
+ ... # one layer's tensors in memory at a time
90
+ ```
91
+
92
+ ## Benchmarks
93
+
94
+ All results are bit-exact md5-verified lossless. Source safetensors → `.bs`.
95
+
96
+ | Model | Format | Source | Compressed | Ratio |
97
+ |-------|--------|--------|------------|-------|
98
+ | GPT-2 117M | FP32 | 548 MB | 414 MB | **75.53%** |
99
+ | GPT-2 117M | BF16 | 274 MB | 165 MB | **60.11%** |
100
+ | GPT-2 117M | FP16 | 274 MB | 215 MB | **78.50%** |
101
+ | Mistral 7B Instruct v0.3 (shard) | BF16 | 4.55 GB | 2.98 GB | **65.56%** |
102
+ | Llama 3.1 8B (shard) | BF16 | 1.17 GB | 768 MB | **65.73%** |
103
+ | Qwen 2.5 14B (shard) | BF16 | 1.70 GB | 1.12 GB | **65.75%** |
104
+ | Stable Diffusion 1.5 VAE | FP32 | 335 MB | 278 MB | **83.20%** |
105
+ | Stable Diffusion 1.5 UNet | FP16 | 1.72 GB | 1.48 GB | **85.92%** |
106
+
107
+ Delta compression (fine-tune vs base) on GPT-2 with a simulated fine-tune:
108
+ **6.95%** of source — fine-tunes ship as tiny diffs against the base.
109
+
110
+ Streaming peak RAM on GPT-2 117M is **29.6%** lower than full load. The win
111
+ grows with depth: a 70B BF16 model normally needs 132 GB to load; with the
112
+ streaming loader the peak is `non_layer + one layer` ≈ a few GB.
113
+
114
+ ## CLI
115
+
116
+ ```bash
117
+ # Compress / decompress
118
+ bigsmall compress model.safetensors # balanced (default)
119
+ bigsmall compress model.safetensors --storage # max ratio, slow decode
120
+ bigsmall compress model.safetensors --inference # fastest decode
121
+ bigsmall decompress model.bs -o /path/to/output.safetensors
122
+
123
+ # Info / verify / benchmark
124
+ bigsmall info model.bs
125
+ bigsmall verify model.bs
126
+ bigsmall benchmark model.safetensors
127
+
128
+ # Delta compression
129
+ bigsmall compress finetune.safetensors --base base.safetensors -o delta.bs
130
+ bigsmall decompress delta.bs --base base.safetensors -o reconstructed.safetensors
131
+ ```
132
+
133
+ ## Python API
134
+
135
+ ```python
136
+ import bigsmall
137
+
138
+ # Standard compress / decompress
139
+ bigsmall.compress("model.safetensors", "model.bs", mode="balanced")
140
+ tensors = bigsmall.decompress("model.bs") # dict[str, np.ndarray]
141
+ torch_tensors = bigsmall.load("model.bs", device="cuda")
142
+
143
+ # Inspect a .bs file
144
+ info = bigsmall.info("model.bs")
145
+ print(info["ratio_pct"], info["format"], info["tensor_count"])
146
+
147
+ # Verify
148
+ ok = bigsmall.verify("model.bs")
149
+
150
+ # Delta compression
151
+ bigsmall.compress_delta("ft.safetensors", "base.safetensors", "delta.bs")
152
+ tensors = bigsmall.decompress_delta("delta.bs", "base.safetensors")
153
+
154
+ # Hub integration
155
+ bigsmall.compress_for_hub("gpt2", output_dir="./gpt2_bs")
156
+ bigsmall.upload_to_hub("./gpt2_bs", "user/gpt2-bigsmall")
157
+ sd = bigsmall.from_pretrained("user/gpt2-bigsmall")
158
+ ```
159
+
160
+ ## HuggingFace integration
161
+
162
+ ```python
163
+ from bigsmall.integrations.huggingface import from_pretrained, install_hook
164
+
165
+ # Drop-in loader that returns a transformers model
166
+ from transformers import AutoModelForCausalLM
167
+ model = from_pretrained("model.bs", model_class=AutoModelForCausalLM,
168
+ config_dir="/path/to/hf/model_dir")
169
+
170
+ # Or patch safetensors globally so any from_pretrained call understands .bs
171
+ install_hook()
172
+ ```
173
+
174
+ ## vLLM integration
175
+
176
+ ```python
177
+ from bigsmall.integrations.vllm import decompress_to_temp, get_loader_class
178
+
179
+ # Portable: decompress to temp dir, then point vLLM at it
180
+ out_dir = decompress_to_temp("model.bs", config_dir="/path/to/hf_dir")
181
+
182
+ # Or use the BigSmallModelLoader subclass directly (vLLM 0.4+)
183
+ LoaderClass = get_loader_class()
184
+ ```
185
+
186
+ ## Diffusion model support
187
+
188
+ ```python
189
+ from bigsmall.integrations.diffusion import (
190
+ compress_diffusion, decompress_diffusion, load_pipeline, is_diffusion_model
191
+ )
192
+
193
+ compress_diffusion("unet.safetensors", "unet.bs")
194
+ pipe = load_pipeline("unet.bs", config_dir="/path/to/diffusers_dir")
195
+ ```
196
+
197
+ ## Container format
198
+
199
+ `.bs` files are self-describing:
200
+
201
+ | Bytes | Field |
202
+ |-------|-------|
203
+ | 0..3 | Magic `BGSM` |
204
+ | 4..5 | Version (uint16, currently 1) |
205
+ | 6..9 | Header JSON length (uint32) |
206
+ | 10.. | Header JSON (utf-8) |
207
+ | ... | Concatenated compressed blobs |
208
+
209
+ Header JSON encodes per-tensor `name`, `shape`, `dtype`, `codec`, `special`,
210
+ `compressed_bytes`, `offset`, `md5`, and any codec-specific extras.
211
+
212
+ ## Codecs
213
+
214
+ | Format | Codec | Notes |
215
+ |--------|-------|-------|
216
+ | FP32 | per-tensor (sign,exp) AC + zstd byte-plane mantissa | 75-83% ratio |
217
+ | BF16 | per-tensor (sign,exp) AC + per-(exp) mantissa AC | 60-66% ratio |
218
+ | FP16 | per-tensor (sign,exp) AC + per-(exp) mantissa AC | 77-86% ratio |
219
+ | FP8 | per-tensor Categorical AC on byte stream | 71-72% ratio |
220
+ | FP4 | per-tensor Categorical AC on 4-bit indices | 30% ratio (huge savings) |
221
+
222
+ Special tensors (auto-detected, architecture-agnostic):
223
+ - **lowcard**: tensors with ≤16 unique values (e.g. attention masks) → tiny lookup table
224
+ - **wpe_delta**: 2D embeddings with high row-row correlation → delta + blosc2
225
+ - **tied**: tensors with identical bytes (embed_tokens / lm_head) → stored once
226
+
227
+ ## Paper
228
+
229
+ Technical paper with full research records and floor proofs across all five
230
+ float formats: **coming soon (arXiv preprint in preparation)**.
231
+
232
+ ## License
233
+
234
+ Apache 2.0. See `LICENSE`.
@@ -0,0 +1,194 @@
1
+ # BigSmall
2
+
3
+ Lossless neural network weight compression. One package, every float format,
4
+ every model. Compress big models so they fit (or load faster) on small hardware.
5
+
6
+ ## Why BigSmall
7
+
8
+ BigSmall is **lossless**, not quantization. After decompression the weights are
9
+ bit-for-bit identical to the original (md5-verified on every shard). You get the
10
+ same inference outputs as the uncompressed model — no quality degradation, no
11
+ fine-tune drift, no surprise accuracy regression on long-tail prompts.
12
+
13
+ Existing tools force a tradeoff: ZipNN (~83% ratio, FP32 only), DFloat11 (~68%,
14
+ BF16 only, ~2× slower inference at batch=1), ZipServ (~70%, BF16 only, H100-style
15
+ GPUs only). BigSmall covers FP32/BF16/FP16/FP8/FP4 in a single package, hits the
16
+ proven mathematical floor on each format, and adds no inference overhead — you
17
+ decompress once at load time and run at native speed.
18
+
19
+ It is the right tool when reproducibility, fine-tuning, or production quality
20
+ matters. Ollama-style 4-bit quantization gives you a smaller, **worse** version of
21
+ the model. BigSmall gives you a smaller version of **the same** model.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pip install bigsmall
27
+ ```
28
+
29
+ Optional extras: `pip install "bigsmall[torch]"`, `[hf]`, `[diffusion]`, `[vllm]`, `[all]`.
30
+
31
+ Requirements: Python 3.9+, PyTorch 2.0+, safetensors, numpy, zstandard, constriction.
32
+
33
+ ## Quick start
34
+
35
+ ```python
36
+ import bigsmall
37
+
38
+ # 1. Compress a safetensors model
39
+ bigsmall.compress("model.safetensors", "model.bs")
40
+
41
+ # 2. Load it back as a torch state_dict (one line, works on local path or HF repo)
42
+ sd = bigsmall.from_pretrained("./model.bs")
43
+ my_model.load_state_dict(sd, strict=False)
44
+
45
+ # 3. Stream layer-by-layer for models bigger than RAM
46
+ with bigsmall.StreamingLoader("model.bs", device="cuda") as L:
47
+ non_layer = L.load_non_layer_tensors()
48
+ for i, layer in L.iter_layers():
49
+ ... # one layer's tensors in memory at a time
50
+ ```
51
+
52
+ ## Benchmarks
53
+
54
+ All results are bit-exact md5-verified lossless. Source safetensors → `.bs`.
55
+
56
+ | Model | Format | Source | Compressed | Ratio |
57
+ |-------|--------|--------|------------|-------|
58
+ | GPT-2 117M | FP32 | 548 MB | 414 MB | **75.53%** |
59
+ | GPT-2 117M | BF16 | 274 MB | 165 MB | **60.11%** |
60
+ | GPT-2 117M | FP16 | 274 MB | 215 MB | **78.50%** |
61
+ | Mistral 7B Instruct v0.3 (shard) | BF16 | 4.55 GB | 2.98 GB | **65.56%** |
62
+ | Llama 3.1 8B (shard) | BF16 | 1.17 GB | 768 MB | **65.73%** |
63
+ | Qwen 2.5 14B (shard) | BF16 | 1.70 GB | 1.12 GB | **65.75%** |
64
+ | Stable Diffusion 1.5 VAE | FP32 | 335 MB | 278 MB | **83.20%** |
65
+ | Stable Diffusion 1.5 UNet | FP16 | 1.72 GB | 1.48 GB | **85.92%** |
66
+
67
+ Delta compression (fine-tune vs base) on GPT-2 with a simulated fine-tune:
68
+ **6.95%** of source — fine-tunes ship as tiny diffs against the base.
69
+
70
+ Streaming peak RAM on GPT-2 117M is **29.6%** lower than full load. The win
71
+ grows with depth: a 70B BF16 model normally needs 132 GB to load; with the
72
+ streaming loader the peak is `non_layer + one layer` ≈ a few GB.
73
+
74
+ ## CLI
75
+
76
+ ```bash
77
+ # Compress / decompress
78
+ bigsmall compress model.safetensors # balanced (default)
79
+ bigsmall compress model.safetensors --storage # max ratio, slow decode
80
+ bigsmall compress model.safetensors --inference # fastest decode
81
+ bigsmall decompress model.bs -o /path/to/output.safetensors
82
+
83
+ # Info / verify / benchmark
84
+ bigsmall info model.bs
85
+ bigsmall verify model.bs
86
+ bigsmall benchmark model.safetensors
87
+
88
+ # Delta compression
89
+ bigsmall compress finetune.safetensors --base base.safetensors -o delta.bs
90
+ bigsmall decompress delta.bs --base base.safetensors -o reconstructed.safetensors
91
+ ```
92
+
93
+ ## Python API
94
+
95
+ ```python
96
+ import bigsmall
97
+
98
+ # Standard compress / decompress
99
+ bigsmall.compress("model.safetensors", "model.bs", mode="balanced")
100
+ tensors = bigsmall.decompress("model.bs") # dict[str, np.ndarray]
101
+ torch_tensors = bigsmall.load("model.bs", device="cuda")
102
+
103
+ # Inspect a .bs file
104
+ info = bigsmall.info("model.bs")
105
+ print(info["ratio_pct"], info["format"], info["tensor_count"])
106
+
107
+ # Verify
108
+ ok = bigsmall.verify("model.bs")
109
+
110
+ # Delta compression
111
+ bigsmall.compress_delta("ft.safetensors", "base.safetensors", "delta.bs")
112
+ tensors = bigsmall.decompress_delta("delta.bs", "base.safetensors")
113
+
114
+ # Hub integration
115
+ bigsmall.compress_for_hub("gpt2", output_dir="./gpt2_bs")
116
+ bigsmall.upload_to_hub("./gpt2_bs", "user/gpt2-bigsmall")
117
+ sd = bigsmall.from_pretrained("user/gpt2-bigsmall")
118
+ ```
119
+
120
+ ## HuggingFace integration
121
+
122
+ ```python
123
+ from bigsmall.integrations.huggingface import from_pretrained, install_hook
124
+
125
+ # Drop-in loader that returns a transformers model
126
+ from transformers import AutoModelForCausalLM
127
+ model = from_pretrained("model.bs", model_class=AutoModelForCausalLM,
128
+ config_dir="/path/to/hf/model_dir")
129
+
130
+ # Or patch safetensors globally so any from_pretrained call understands .bs
131
+ install_hook()
132
+ ```
133
+
134
+ ## vLLM integration
135
+
136
+ ```python
137
+ from bigsmall.integrations.vllm import decompress_to_temp, get_loader_class
138
+
139
+ # Portable: decompress to temp dir, then point vLLM at it
140
+ out_dir = decompress_to_temp("model.bs", config_dir="/path/to/hf_dir")
141
+
142
+ # Or use the BigSmallModelLoader subclass directly (vLLM 0.4+)
143
+ LoaderClass = get_loader_class()
144
+ ```
145
+
146
+ ## Diffusion model support
147
+
148
+ ```python
149
+ from bigsmall.integrations.diffusion import (
150
+ compress_diffusion, decompress_diffusion, load_pipeline, is_diffusion_model
151
+ )
152
+
153
+ compress_diffusion("unet.safetensors", "unet.bs")
154
+ pipe = load_pipeline("unet.bs", config_dir="/path/to/diffusers_dir")
155
+ ```
156
+
157
+ ## Container format
158
+
159
+ `.bs` files are self-describing:
160
+
161
+ | Bytes | Field |
162
+ |-------|-------|
163
+ | 0..3 | Magic `BGSM` |
164
+ | 4..5 | Version (uint16, currently 1) |
165
+ | 6..9 | Header JSON length (uint32) |
166
+ | 10.. | Header JSON (utf-8) |
167
+ | ... | Concatenated compressed blobs |
168
+
169
+ Header JSON encodes per-tensor `name`, `shape`, `dtype`, `codec`, `special`,
170
+ `compressed_bytes`, `offset`, `md5`, and any codec-specific extras.
171
+
172
+ ## Codecs
173
+
174
+ | Format | Codec | Notes |
175
+ |--------|-------|-------|
176
+ | FP32 | per-tensor (sign,exp) AC + zstd byte-plane mantissa | 75-83% ratio |
177
+ | BF16 | per-tensor (sign,exp) AC + per-(exp) mantissa AC | 60-66% ratio |
178
+ | FP16 | per-tensor (sign,exp) AC + per-(exp) mantissa AC | 77-86% ratio |
179
+ | FP8 | per-tensor Categorical AC on byte stream | 71-72% ratio |
180
+ | FP4 | per-tensor Categorical AC on 4-bit indices | 30% ratio (huge savings) |
181
+
182
+ Special tensors (auto-detected, architecture-agnostic):
183
+ - **lowcard**: tensors with ≤16 unique values (e.g. attention masks) → tiny lookup table
184
+ - **wpe_delta**: 2D embeddings with high row-row correlation → delta + blosc2
185
+ - **tied**: tensors with identical bytes (embed_tokens / lm_head) → stored once
186
+
187
+ ## Paper
188
+
189
+ Technical paper with full research records and floor proofs across all five
190
+ float formats: **coming soon (arXiv preprint in preparation)**.
191
+
192
+ ## License
193
+
194
+ Apache 2.0. See `LICENSE`.
@@ -0,0 +1,45 @@
1
+ """BigSmall - Lossless neural network weight compression.
2
+
3
+ Public API:
4
+ bigsmall.compress(src, dst, mode="balanced") - compress safetensors -> .bs
5
+ bigsmall.decompress(src, dst=None) -> dict[str, ndarray]
6
+ bigsmall.load(src, device="cpu") -> dict[str, torch.Tensor]
7
+ bigsmall.info(src) -> dict
8
+ bigsmall.verify(src) -> bool
9
+ bigsmall.compress_delta(finetune, base, dst, mode="balanced")
10
+ bigsmall.decompress_delta(delta_src, base_src, dst=None) -> dict[str, ndarray]
11
+
12
+ HuggingFace Hub round-trip (Phase 4):
13
+ bigsmall.compress_for_hub(source, output_dir) - compress any HF model
14
+ bigsmall.upload_to_hub(output_dir, repo_id) - push to the Hub
15
+ bigsmall.from_pretrained(repo_or_path) - download + decompress -> state_dict
16
+ bigsmall.install_hook() - monkey-patch safetensors.load_file
17
+
18
+ Streaming loader (Phase 4 cont.):
19
+ bigsmall.StreamingLoader(path, device="cuda") - layer-by-layer decompression
20
+ """
21
+ __version__ = "1.0.0"
22
+
23
+ from .encoder import compress, compress_delta
24
+ from .decoder import decompress, decompress_delta, load
25
+ from .verify import verify
26
+ from .container import info
27
+ from .hub import compress_for_hub, upload_to_hub, from_pretrained
28
+ from .integrations.huggingface import install_hook
29
+ from .streaming import StreamingLoader
30
+
31
+ __all__ = [
32
+ "compress",
33
+ "decompress",
34
+ "load",
35
+ "info",
36
+ "verify",
37
+ "compress_delta",
38
+ "decompress_delta",
39
+ "compress_for_hub",
40
+ "upload_to_hub",
41
+ "from_pretrained",
42
+ "install_hook",
43
+ "StreamingLoader",
44
+ "__version__",
45
+ ]