ternary-quant 0.1.6__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 (38) hide show
  1. ternary_quant-0.1.6/LICENSE +184 -0
  2. ternary_quant-0.1.6/PKG-INFO +214 -0
  3. ternary_quant-0.1.6/README.md +173 -0
  4. ternary_quant-0.1.6/pyproject.toml +56 -0
  5. ternary_quant-0.1.6/setup.cfg +4 -0
  6. ternary_quant-0.1.6/ternary_quant/__init__.py +58 -0
  7. ternary_quant-0.1.6/ternary_quant/cli.py +1872 -0
  8. ternary_quant-0.1.6/ternary_quant/conditional_experts.py +1171 -0
  9. ternary_quant-0.1.6/ternary_quant/cuda_kernels.py +751 -0
  10. ternary_quant-0.1.6/ternary_quant/data.py +87 -0
  11. ternary_quant-0.1.6/ternary_quant/eval.py +494 -0
  12. ternary_quant-0.1.6/ternary_quant/generative_adapters.py +1139 -0
  13. ternary_quant-0.1.6/ternary_quant/inference.py +1416 -0
  14. ternary_quant-0.1.6/ternary_quant/mac_kernels.py +817 -0
  15. ternary_quant-0.1.6/ternary_quant/pipeline.py +465 -0
  16. ternary_quant-0.1.6/ternary_quant/ptq_families.py +571 -0
  17. ternary_quant-0.1.6/ternary_quant/quantizer.py +7 -0
  18. ternary_quant-0.1.6/ternary_quant/quantizer_experimental.py +395 -0
  19. ternary_quant-0.1.6/ternary_quant/quantizer_groupwise.py +2156 -0
  20. ternary_quant-0.1.6/ternary_quant/quantizer_perrow.py +366 -0
  21. ternary_quant-0.1.6/ternary_quant/quantizer_small.py +7 -0
  22. ternary_quant-0.1.6/ternary_quant/quantizer_v2.py +7 -0
  23. ternary_quant-0.1.6/ternary_quant/storage.py +613 -0
  24. ternary_quant-0.1.6/ternary_quant/toolkit.py +308 -0
  25. ternary_quant-0.1.6/ternary_quant/vllm_backend.py +227 -0
  26. ternary_quant-0.1.6/ternary_quant.egg-info/PKG-INFO +214 -0
  27. ternary_quant-0.1.6/ternary_quant.egg-info/SOURCES.txt +36 -0
  28. ternary_quant-0.1.6/ternary_quant.egg-info/dependency_links.txt +1 -0
  29. ternary_quant-0.1.6/ternary_quant.egg-info/entry_points.txt +2 -0
  30. ternary_quant-0.1.6/ternary_quant.egg-info/requires.txt +26 -0
  31. ternary_quant-0.1.6/ternary_quant.egg-info/top_level.txt +1 -0
  32. ternary_quant-0.1.6/tests/test_codex_small_models.py +284 -0
  33. ternary_quant-0.1.6/tests/test_linear_like_adapters.py +81 -0
  34. ternary_quant-0.1.6/tests/test_models.py +238 -0
  35. ternary_quant-0.1.6/tests/test_runtime_modes.py +278 -0
  36. ternary_quant-0.1.6/tests/test_toolkit_surface.py +37 -0
  37. ternary_quant-0.1.6/tests/test_v2.py +286 -0
  38. ternary_quant-0.1.6/tests/test_v3.py +432 -0
@@ -0,0 +1,184 @@
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, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and
27
+ configuration files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object
31
+ code, generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work (an example is provided in the Appendix
36
+ below).
37
+
38
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
39
+ is based on (or derived from) the Work and for which the editorial revisions,
40
+ annotations, elaborations, or other modifications represent, as a whole, an
41
+ original work of authorship. For the purposes of this License, Derivative Works
42
+ shall not include works that remain separable from, or merely link (or bind by
43
+ name) to the interfaces of, the Work and Derivative Works thereof.
44
+
45
+ "Contribution" shall mean any work of authorship, including the original
46
+ version of the Work and any modifications or additions to that Work or
47
+ Derivative Works thereof, that is intentionally submitted to Licensor for
48
+ inclusion in the Work by the copyright owner or by an individual or Legal
49
+ Entity authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal, or
51
+ written communication sent to the Licensor or its representatives, including
52
+ but not limited to communication on electronic mailing lists, source code
53
+ control systems, and issue tracking systems that are managed by, or on behalf
54
+ of, the Licensor for the purpose of discussing and improving the Work, but
55
+ excluding communication that is conspicuously marked or otherwise designated in
56
+ writing by the copyright owner as "Not a Contribution."
57
+
58
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
59
+ of whom a Contribution has been received by Licensor and subsequently
60
+ incorporated within the Work.
61
+
62
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
63
+ License, each Contributor hereby grants to You a perpetual, worldwide,
64
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
65
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
66
+ sublicense, and distribute the Work and such Derivative Works in Source or
67
+ Object form.
68
+
69
+ 3. Grant of Patent License. Subject to the terms and conditions of this
70
+ License, each Contributor hereby grants to You a perpetual, worldwide,
71
+ non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this
72
+ section) patent license to make, have made, use, offer to sell, sell, import,
73
+ and otherwise transfer the Work, where such license applies only to those
74
+ patent claims licensable by such Contributor that are necessarily infringed by
75
+ their Contribution(s) alone or by combination of their Contribution(s) with the
76
+ Work to which such Contribution(s) was submitted. If You institute patent
77
+ litigation against any entity (including a cross-claim or counterclaim in a
78
+ lawsuit) alleging that the Work or a Contribution incorporated within the Work
79
+ constitutes direct or contributory patent infringement, then any patent
80
+ licenses granted to You under this License for that Work shall terminate as of
81
+ the date such litigation is filed.
82
+
83
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
84
+ Derivative Works thereof in any medium, with or without modifications, and in
85
+ Source or Object form, provided that You meet the following conditions:
86
+
87
+ (a) You must give any other recipients of the Work or Derivative Works a copy
88
+ of this License; and
89
+
90
+ (b) You must cause any modified files to carry prominent notices stating that
91
+ You changed the files; and
92
+
93
+ (c) You must retain, in the Source form of any Derivative Works that You
94
+ distribute, all copyright, patent, trademark, and attribution notices from the
95
+ Source form of the Work, excluding those notices that do not pertain to any
96
+ part of the Derivative Works; and
97
+
98
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
99
+ any Derivative Works that You distribute must include a readable copy of the
100
+ attribution notices contained within such NOTICE file, excluding those notices
101
+ that do not pertain to any part of the Derivative Works, in at least one of the
102
+ following places: within a NOTICE text file distributed as part of the
103
+ Derivative Works; within the Source form or documentation, if provided along
104
+ with the Derivative Works; or, within a display generated by the Derivative
105
+ Works, if and wherever such third-party notices normally appear. The contents
106
+ of the NOTICE file are for informational purposes only and do not modify the
107
+ License. You may add Your own attribution notices within Derivative Works that
108
+ You distribute, alongside or as an addendum to the NOTICE text from the Work,
109
+ provided that such additional attribution notices cannot be construed as
110
+ modifying the License.
111
+
112
+ You may add Your own copyright statement to Your modifications and may provide
113
+ additional or different license terms and conditions for use, reproduction, or
114
+ distribution of Your modifications, or for any such Derivative Works as a
115
+ whole, provided Your use, reproduction, and distribution of the Work otherwise
116
+ complies with the conditions stated in this License.
117
+
118
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
119
+ Contribution intentionally submitted for inclusion in the Work by You to the
120
+ Licensor shall be under the terms and conditions of this License, without any
121
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
122
+ supersede or modify the terms of any separate license agreement you may have
123
+ executed with Licensor regarding such Contributions.
124
+
125
+ 6. Trademarks. This License does not grant permission to use the trade names,
126
+ trademarks, service marks, or product names of the Licensor, except as required
127
+ for reasonable and customary use in describing the origin of the Work and
128
+ reproducing the content of the NOTICE file.
129
+
130
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
131
+ writing, Licensor provides the Work (and each Contributor provides its
132
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
133
+ KIND, either express or implied, including, without limitation, any warranties
134
+ or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
135
+ PARTICULAR PURPOSE. You are solely responsible for determining the
136
+ appropriateness of using or redistributing the Work and assume any risks
137
+ associated with Your exercise of permissions under this License.
138
+
139
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
140
+ tort (including negligence), contract, or otherwise, unless required by
141
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
142
+ writing, shall any Contributor be liable to You for damages, including any
143
+ direct, indirect, special, incidental, or consequential damages of any
144
+ character arising as a result of this License or out of the use or inability to
145
+ use the Work (including but not limited to damages for loss of goodwill, work
146
+ stoppage, computer failure or malfunction, or any and all other commercial
147
+ damages or losses), even if such Contributor has been advised of the
148
+ possibility of such damages.
149
+
150
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
151
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
152
+ acceptance of support, warranty, indemnity, or other liability obligations
153
+ and/or rights consistent with this License. However, in accepting such
154
+ obligations, You may act only on Your own behalf and on Your sole
155
+ responsibility, not on behalf of any other Contributor, and only if You agree
156
+ to indemnify, defend, and hold each Contributor harmless for any liability
157
+ incurred by, or claims asserted against, such Contributor by reason of your
158
+ accepting any such warranty or additional liability.
159
+
160
+ END OF TERMS AND CONDITIONS
161
+
162
+ APPENDIX: How to apply the Apache License to your work.
163
+
164
+ To apply the Apache License to your work, attach the following boilerplate
165
+ notice, with the fields enclosed by brackets "[]" replaced with your own
166
+ identifying information. (Don't include the brackets!) The text should be
167
+ enclosed in the appropriate comment syntax for the file format. We also
168
+ recommend that a file or class name and description of purpose be included on
169
+ the same "printed page" as the copyright notice for easier identification
170
+ within third-party archives.
171
+
172
+ Copyright 2026 Asad Ismail
173
+
174
+ Licensed under the Apache License, Version 2.0 (the "License");
175
+ you may not use this file except in compliance with the License.
176
+ You may obtain a copy of the License at
177
+
178
+ http://www.apache.org/licenses/LICENSE-2.0
179
+
180
+ Unless required by applicable law or agreed to in writing, software
181
+ distributed under the License is distributed on an "AS IS" BASIS,
182
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
183
+ See the License for the specific language governing permissions and
184
+ limitations under the License.
@@ -0,0 +1,214 @@
1
+ Metadata-Version: 2.4
2
+ Name: ternary-quant
3
+ Version: 0.1.6
4
+ Summary: Post-training ternary quantization for HuggingFace generative models
5
+ Author: Asad Ismail
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/Asad-Ismail/ternary-quant
8
+ Project-URL: Issues, https://github.com/Asad-Ismail/ternary-quant/issues
9
+ Keywords: quantization,ternary,llm,vlm,post-training-quantization,generative-models
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: torch>=2.1.0
20
+ Requires-Dist: transformers>=4.46.0
21
+ Requires-Dist: accelerate>=0.28.0
22
+ Requires-Dist: datasets>=2.18.0
23
+ Requires-Dist: safetensors>=0.4.0
24
+ Requires-Dist: tqdm
25
+ Requires-Dist: numpy
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest; extra == "dev"
28
+ Requires-Dist: ruff; extra == "dev"
29
+ Provides-Extra: paper
30
+ Requires-Dist: hqq>=0.2.8.post1; extra == "paper"
31
+ Requires-Dist: matplotlib>=3.7.0; extra == "paper"
32
+ Provides-Extra: multimodal
33
+ Requires-Dist: pillow; extra == "multimodal"
34
+ Requires-Dist: num2words; extra == "multimodal"
35
+ Requires-Dist: torchvision; extra == "multimodal"
36
+ Provides-Extra: eval
37
+ Requires-Dist: lm-eval>=0.4.0; extra == "eval"
38
+ Provides-Extra: serving
39
+ Requires-Dist: vllm>=0.4.0; extra == "serving"
40
+ Dynamic: license-file
41
+
42
+ <div align="center">
43
+
44
+ ```
45
+ _____ ___ _
46
+ |_ _|__ / _ \ _ _ __ _ _ _| |_
47
+ | ||___| (_) | || / _` | ' \ _|
48
+ |_| \__\_\\_,_\__,_|_||_\__|
49
+ ```
50
+
51
+ **Component-first post-training ternary quantization for HuggingFace models.
52
+ HF-native PTQ for VLMs, seq2seq, and audio — with packed runtime modes for selected 7B-class models.**
53
+
54
+ [![CI](https://github.com/Asad-Ismail/ternary-quant/actions/workflows/ci.yml/badge.svg)](https://github.com/Asad-Ismail/ternary-quant/actions/workflows/ci.yml)
55
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
56
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
57
+ [![PyPI version](https://img.shields.io/pypi/v/ternary-quant.svg)](https://pypi.org/project/ternary-quant/)
58
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Asad-Ismail/ternary-quant/blob/main/notebooks/quickstart.ipynb)
59
+ [![Demo](https://img.shields.io/badge/🤗%20Space-Live%20Demo-blue)](https://huggingface.co/spaces/AsadIsmail/ternary-quant-demo)
60
+
61
+ **[Try the live demo](https://huggingface.co/spaces/AsadIsmail/ternary-quant-demo)** &nbsp;|&nbsp; Pre-quantized: [Qwen3-1.7B](https://huggingface.co/AsadIsmail/Qwen3-1.7B-ternary) &middot; [Qwen2-VL-2B](https://huggingface.co/AsadIsmail/Qwen2-VL-2B-ternary) &middot; [Gemma4-E2B](https://huggingface.co/AsadIsmail/Gemma4-E2B-ternary)
62
+
63
+ </div>
64
+
65
+ GGUF/llama.cpp is the strongest default for local deployment of supported models,
66
+ and current llama.cpp builds support selected multimodal models through
67
+ `libmtmd` (including image input and experimental audio input). `ternary-quant`
68
+ targets a different gap: HuggingFace/Python-native, component-first
69
+ post-training ternary quantization of existing FP16 checkpoints. Decoder-LLM
70
+ benchmarks retain 95–99% of FP16 quality (97.7% mean across seven models);
71
+ multimodal/audio quality is model-card and validation-suite dependent.
72
+
73
+ ```
74
+ Qwen2.5-7B: 15.2 GB FP16 → 9.6 GB triton_memory ✓ fits 12 GB GPU (RTX 4070/3080)
75
+ Phi-3.5-mini: 7.6 GB FP16 → 4.6 GB triton_memory ✓ fits 6 GB GPU (RTX 3060/GTX 1060)
76
+ Mistral-7B: 14.0 GB FP16 → 5.0 GB stored (98.7% ARC quality, stays in Python/HF)
77
+ FLAN-T5-small:154 MB FP16 → 125 MB stored (5.1× decoder component)
78
+ ```
79
+
80
+ ---
81
+
82
+ ## Quickstart
83
+
84
+ ```bash
85
+ pip install ternary-quant
86
+ # or with uv
87
+ uv pip install ternary-quant
88
+
89
+ # Vision-Language Model
90
+ ternary-quant quantize-broad Qwen/Qwen2-VL-2B-Instruct \
91
+ --output ./qwen2vl-quant \
92
+ --components text_backbone vision_backbone \
93
+ --scheme tritplane3
94
+
95
+ # Causal LM
96
+ ternary-quant quantize-broad Qwen/Qwen3-4B \
97
+ --output ./qwen3-4b-quant --components text_backbone --scheme tritplane3
98
+
99
+ # Seq2seq / Audio
100
+ ternary-quant quantize-broad openai/whisper-small \
101
+ --output ./whisper-quant --components decoder
102
+
103
+ # Generate
104
+ ternary-quant generate ./qwen2vl-quant --prompt "Describe this image" --runtime-mode cached
105
+ ```
106
+
107
+ Or use a pre-quantized model directly:
108
+
109
+ ```python
110
+ from ternary_quant.inference import load_ternary_model, generate_text
111
+
112
+ model, tokenizer = load_ternary_model("AsadIsmail/Qwen3-1.7B-ternary", device="cuda", runtime_mode="cached")
113
+ print(generate_text(model, tokenizer, "What is ternary quantization?", max_new_tokens=100))
114
+ ```
115
+
116
+ ---
117
+
118
+ ## What it does
119
+
120
+ `ternary-quant` is **post-training quantization (PTQ)** — it takes supported
121
+ existing FP16 HuggingFace checkpoints and pushes selected transformer weights
122
+ toward {-1, 0, +1} (ternary). No retraining required.
123
+
124
+ **PTQ ternary vs trained ternary (BitNet):** BitNet-style models are trained
125
+ from scratch to operate with ternary weights, which is different from converting
126
+ an existing FP16 checkpoint after training. `ternary-quant` does PTQ: take an
127
+ existing FP16 model (Qwen, Mistral, Whisper, VLMs) and quantize selected
128
+ components without retraining. GGUF/llama.cpp supports trained ternary formats
129
+ for compatible models, but not this repo's HF-native component-first PTQ
130
+ workflow for arbitrary checkpoints.
131
+
132
+ ---
133
+
134
+ ## Key results
135
+
136
+ **95–99% decoder-LLM quality retention** across 7 models (0.5B-7B), measured with lm-eval 0-shot (ARC, HellaSwag, WinoGrande):
137
+
138
+ | Model | Avg retain | Compression |
139
+ |---|---|---|
140
+ | Phi-2 (2.7B) | **99.2%** | 1.8x |
141
+ | Qwen2.5-0.5B | **99.1%** | 1.8x |
142
+ | Mistral-7B | **98.7%** | 2.8x |
143
+ | Qwen3-4B | **98.1%** | 1.3x |
144
+ | Qwen3-1.7B | **97.5%** | 2.7x |
145
+
146
+ Full results: [docs/KNOWN_GOOD_MODELS.md](docs/KNOWN_GOOD_MODELS.md)
147
+
148
+ Validated paths cover decoder LLMs, selected VLMs (Qwen2-VL, Gemma-4,
149
+ SmolVLM), seq2seq (FLAN-T5), and audio (Whisper).
150
+
151
+ ---
152
+
153
+ ## How it compares
154
+
155
+ | Tool | LLMs | VLMs | Seq2seq / Audio | PTQ ternary | Component selection | Stays in Python/HF |
156
+ |---|---|---|---|---|---|---|
157
+ | GGUF / llama.cpp | ✓✓✓ | ✓ (selected models via libmtmd) | partial / experimental | trained only | partial | ✗ |
158
+ | bitsandbytes | ✓✓ | partial | ✗ | ✗ | ✗ | ✓ |
159
+ | GPTQ / AWQ | ✓✓ | partial | ✗ | ✗ | ✗ | ✓ |
160
+ | PT²-LLM / PTQTP | ✓✓ | ✗ | ✗ | ✓ | ✗ | ✗ |
161
+ | **ternary-quant** | **✓✓** | **✓✓** | **✓✓** | **✓** | **✓** | **✓** |
162
+
163
+ **Choose the right tool:**
164
+ - Standard decoder LLM, want max speed locally → **GGUF** (llama.cpp is faster on CPU, better ecosystem)
165
+ - PTQ ternary on decoder LLMs, care about peak quality → **PT²-LLM** (ICLR 2026, strongest ternary PTQ results on decoder LLMs)
166
+ - Need HF-native component-first ternary PTQ for a VLM, seq2seq, audio, or custom model → **ternary-quant**
167
+ - 4-bit LLM with best quality-per-bit → **HQQ-4** (outperforms ternary-quant on standard LLMs)
168
+
169
+ ---
170
+
171
+ ## Runtime modes
172
+
173
+ | Mode | Hardware | Weights | Speed | Use case |
174
+ |---|---|---|---|---|
175
+ | `cached` | CPU / GPU / MPS | FP16 in memory | **fastest** | Default — dequantizes once at load |
176
+ | `triton_memory` | NVIDIA GPU | **packed 2-bit** | ~3-6x slower | Fit oversized models on small GPUs |
177
+ | `metal` | Apple Silicon | **packed 2-bit** | ~3-4x slower | Fit oversized models on Mac |
178
+
179
+ `triton_memory` and `metal` keep weights as packed 2-bit ternary codes throughout inference — no FP16 weight matrix is ever materialized. This trades speed for memory, enabling models that don't fit otherwise.
180
+
181
+ > **`metal` mode requires torch ≥ 2.7** (for `torch.mps.compile_shader`). On older torch it degrades to `cached`. Apple-Silicon MPS generation also needs torch ≥ 2.7 to avoid a GQA matmul crash present in 2.6.
182
+
183
+ | Model | FP16 VRAM | triton_memory | Fits on |
184
+ |---|---|---|---|
185
+ | Phi-3.5-mini (3.8B) | 7.6 GB | **4.6 GB** | RTX 3060 6GB |
186
+ | Qwen2.5-7B (7.6B) | 15.2 GB | **9.6 GB** | RTX 4070 12GB |
187
+
188
+ | Model | Cached (Mac) | Metal (Mac) | Memory saved |
189
+ |---|---|---|---|
190
+ | Qwen3-1.7B | 10.4 GB / 46 tok/s | 4.6 GB / 12 tok/s | 2.3x |
191
+ | Qwen2-VL-2B | 16.8 GB / 52 tok/s | 7.4 GB / 13 tok/s | 2.3x |
192
+
193
+ Full details: [docs/RUNTIME_MODES.md](docs/RUNTIME_MODES.md)
194
+
195
+ ---
196
+
197
+ ## Learn more
198
+
199
+ - [Known good models](docs/KNOWN_GOOD_MODELS.md) — measured results and commands for validated architecture families
200
+ - [Runtime modes](docs/RUNTIME_MODES.md) — triton_memory, metal, CPU inference details
201
+ - [Research track](docs/RESEARCH_ADVANCED_TERNARY.md) — RAST + CCRE for true 1.58-bit compression
202
+ - [Examples](examples/README.md) — text, seq2seq, VLM walkthroughs
203
+ - [Paper](paper/paper.tex) — full experimental results and method description (LaTeX)
204
+ - [Release notes](releases/v0.1.6.md) — what changed in this version
205
+
206
+ ---
207
+
208
+ ## Honest positioning
209
+
210
+ - **HQQ-4 beats ternary-quant on quality-per-bit** for standard LLMs — use it when quality is the priority
211
+ - **PT²-LLM and PTQTP** achieve strong PTQ ternary results on decoder-only LLMs — ternary-quant's algorithmic contribution on that axis is parallel, not superior
212
+ - The broad path is a ternary PTQ research/runtime path, not a general replacement for strong INT4 deployments
213
+ - The research track achieves true near-ternary weights with a real quality cost — this is the active research frontier, not a production-ready path
214
+ - GGUF is better for local deployment of supported standard LLMs and selected multimodal models; ternary-quant's value is component-first ternary PTQ in the HuggingFace ecosystem
@@ -0,0 +1,173 @@
1
+ <div align="center">
2
+
3
+ ```
4
+ _____ ___ _
5
+ |_ _|__ / _ \ _ _ __ _ _ _| |_
6
+ | ||___| (_) | || / _` | ' \ _|
7
+ |_| \__\_\\_,_\__,_|_||_\__|
8
+ ```
9
+
10
+ **Component-first post-training ternary quantization for HuggingFace models.
11
+ HF-native PTQ for VLMs, seq2seq, and audio — with packed runtime modes for selected 7B-class models.**
12
+
13
+ [![CI](https://github.com/Asad-Ismail/ternary-quant/actions/workflows/ci.yml/badge.svg)](https://github.com/Asad-Ismail/ternary-quant/actions/workflows/ci.yml)
14
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
15
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
16
+ [![PyPI version](https://img.shields.io/pypi/v/ternary-quant.svg)](https://pypi.org/project/ternary-quant/)
17
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Asad-Ismail/ternary-quant/blob/main/notebooks/quickstart.ipynb)
18
+ [![Demo](https://img.shields.io/badge/🤗%20Space-Live%20Demo-blue)](https://huggingface.co/spaces/AsadIsmail/ternary-quant-demo)
19
+
20
+ **[Try the live demo](https://huggingface.co/spaces/AsadIsmail/ternary-quant-demo)** &nbsp;|&nbsp; Pre-quantized: [Qwen3-1.7B](https://huggingface.co/AsadIsmail/Qwen3-1.7B-ternary) &middot; [Qwen2-VL-2B](https://huggingface.co/AsadIsmail/Qwen2-VL-2B-ternary) &middot; [Gemma4-E2B](https://huggingface.co/AsadIsmail/Gemma4-E2B-ternary)
21
+
22
+ </div>
23
+
24
+ GGUF/llama.cpp is the strongest default for local deployment of supported models,
25
+ and current llama.cpp builds support selected multimodal models through
26
+ `libmtmd` (including image input and experimental audio input). `ternary-quant`
27
+ targets a different gap: HuggingFace/Python-native, component-first
28
+ post-training ternary quantization of existing FP16 checkpoints. Decoder-LLM
29
+ benchmarks retain 95–99% of FP16 quality (97.7% mean across seven models);
30
+ multimodal/audio quality is model-card and validation-suite dependent.
31
+
32
+ ```
33
+ Qwen2.5-7B: 15.2 GB FP16 → 9.6 GB triton_memory ✓ fits 12 GB GPU (RTX 4070/3080)
34
+ Phi-3.5-mini: 7.6 GB FP16 → 4.6 GB triton_memory ✓ fits 6 GB GPU (RTX 3060/GTX 1060)
35
+ Mistral-7B: 14.0 GB FP16 → 5.0 GB stored (98.7% ARC quality, stays in Python/HF)
36
+ FLAN-T5-small:154 MB FP16 → 125 MB stored (5.1× decoder component)
37
+ ```
38
+
39
+ ---
40
+
41
+ ## Quickstart
42
+
43
+ ```bash
44
+ pip install ternary-quant
45
+ # or with uv
46
+ uv pip install ternary-quant
47
+
48
+ # Vision-Language Model
49
+ ternary-quant quantize-broad Qwen/Qwen2-VL-2B-Instruct \
50
+ --output ./qwen2vl-quant \
51
+ --components text_backbone vision_backbone \
52
+ --scheme tritplane3
53
+
54
+ # Causal LM
55
+ ternary-quant quantize-broad Qwen/Qwen3-4B \
56
+ --output ./qwen3-4b-quant --components text_backbone --scheme tritplane3
57
+
58
+ # Seq2seq / Audio
59
+ ternary-quant quantize-broad openai/whisper-small \
60
+ --output ./whisper-quant --components decoder
61
+
62
+ # Generate
63
+ ternary-quant generate ./qwen2vl-quant --prompt "Describe this image" --runtime-mode cached
64
+ ```
65
+
66
+ Or use a pre-quantized model directly:
67
+
68
+ ```python
69
+ from ternary_quant.inference import load_ternary_model, generate_text
70
+
71
+ model, tokenizer = load_ternary_model("AsadIsmail/Qwen3-1.7B-ternary", device="cuda", runtime_mode="cached")
72
+ print(generate_text(model, tokenizer, "What is ternary quantization?", max_new_tokens=100))
73
+ ```
74
+
75
+ ---
76
+
77
+ ## What it does
78
+
79
+ `ternary-quant` is **post-training quantization (PTQ)** — it takes supported
80
+ existing FP16 HuggingFace checkpoints and pushes selected transformer weights
81
+ toward {-1, 0, +1} (ternary). No retraining required.
82
+
83
+ **PTQ ternary vs trained ternary (BitNet):** BitNet-style models are trained
84
+ from scratch to operate with ternary weights, which is different from converting
85
+ an existing FP16 checkpoint after training. `ternary-quant` does PTQ: take an
86
+ existing FP16 model (Qwen, Mistral, Whisper, VLMs) and quantize selected
87
+ components without retraining. GGUF/llama.cpp supports trained ternary formats
88
+ for compatible models, but not this repo's HF-native component-first PTQ
89
+ workflow for arbitrary checkpoints.
90
+
91
+ ---
92
+
93
+ ## Key results
94
+
95
+ **95–99% decoder-LLM quality retention** across 7 models (0.5B-7B), measured with lm-eval 0-shot (ARC, HellaSwag, WinoGrande):
96
+
97
+ | Model | Avg retain | Compression |
98
+ |---|---|---|
99
+ | Phi-2 (2.7B) | **99.2%** | 1.8x |
100
+ | Qwen2.5-0.5B | **99.1%** | 1.8x |
101
+ | Mistral-7B | **98.7%** | 2.8x |
102
+ | Qwen3-4B | **98.1%** | 1.3x |
103
+ | Qwen3-1.7B | **97.5%** | 2.7x |
104
+
105
+ Full results: [docs/KNOWN_GOOD_MODELS.md](docs/KNOWN_GOOD_MODELS.md)
106
+
107
+ Validated paths cover decoder LLMs, selected VLMs (Qwen2-VL, Gemma-4,
108
+ SmolVLM), seq2seq (FLAN-T5), and audio (Whisper).
109
+
110
+ ---
111
+
112
+ ## How it compares
113
+
114
+ | Tool | LLMs | VLMs | Seq2seq / Audio | PTQ ternary | Component selection | Stays in Python/HF |
115
+ |---|---|---|---|---|---|---|
116
+ | GGUF / llama.cpp | ✓✓✓ | ✓ (selected models via libmtmd) | partial / experimental | trained only | partial | ✗ |
117
+ | bitsandbytes | ✓✓ | partial | ✗ | ✗ | ✗ | ✓ |
118
+ | GPTQ / AWQ | ✓✓ | partial | ✗ | ✗ | ✗ | ✓ |
119
+ | PT²-LLM / PTQTP | ✓✓ | ✗ | ✗ | ✓ | ✗ | ✗ |
120
+ | **ternary-quant** | **✓✓** | **✓✓** | **✓✓** | **✓** | **✓** | **✓** |
121
+
122
+ **Choose the right tool:**
123
+ - Standard decoder LLM, want max speed locally → **GGUF** (llama.cpp is faster on CPU, better ecosystem)
124
+ - PTQ ternary on decoder LLMs, care about peak quality → **PT²-LLM** (ICLR 2026, strongest ternary PTQ results on decoder LLMs)
125
+ - Need HF-native component-first ternary PTQ for a VLM, seq2seq, audio, or custom model → **ternary-quant**
126
+ - 4-bit LLM with best quality-per-bit → **HQQ-4** (outperforms ternary-quant on standard LLMs)
127
+
128
+ ---
129
+
130
+ ## Runtime modes
131
+
132
+ | Mode | Hardware | Weights | Speed | Use case |
133
+ |---|---|---|---|---|
134
+ | `cached` | CPU / GPU / MPS | FP16 in memory | **fastest** | Default — dequantizes once at load |
135
+ | `triton_memory` | NVIDIA GPU | **packed 2-bit** | ~3-6x slower | Fit oversized models on small GPUs |
136
+ | `metal` | Apple Silicon | **packed 2-bit** | ~3-4x slower | Fit oversized models on Mac |
137
+
138
+ `triton_memory` and `metal` keep weights as packed 2-bit ternary codes throughout inference — no FP16 weight matrix is ever materialized. This trades speed for memory, enabling models that don't fit otherwise.
139
+
140
+ > **`metal` mode requires torch ≥ 2.7** (for `torch.mps.compile_shader`). On older torch it degrades to `cached`. Apple-Silicon MPS generation also needs torch ≥ 2.7 to avoid a GQA matmul crash present in 2.6.
141
+
142
+ | Model | FP16 VRAM | triton_memory | Fits on |
143
+ |---|---|---|---|
144
+ | Phi-3.5-mini (3.8B) | 7.6 GB | **4.6 GB** | RTX 3060 6GB |
145
+ | Qwen2.5-7B (7.6B) | 15.2 GB | **9.6 GB** | RTX 4070 12GB |
146
+
147
+ | Model | Cached (Mac) | Metal (Mac) | Memory saved |
148
+ |---|---|---|---|
149
+ | Qwen3-1.7B | 10.4 GB / 46 tok/s | 4.6 GB / 12 tok/s | 2.3x |
150
+ | Qwen2-VL-2B | 16.8 GB / 52 tok/s | 7.4 GB / 13 tok/s | 2.3x |
151
+
152
+ Full details: [docs/RUNTIME_MODES.md](docs/RUNTIME_MODES.md)
153
+
154
+ ---
155
+
156
+ ## Learn more
157
+
158
+ - [Known good models](docs/KNOWN_GOOD_MODELS.md) — measured results and commands for validated architecture families
159
+ - [Runtime modes](docs/RUNTIME_MODES.md) — triton_memory, metal, CPU inference details
160
+ - [Research track](docs/RESEARCH_ADVANCED_TERNARY.md) — RAST + CCRE for true 1.58-bit compression
161
+ - [Examples](examples/README.md) — text, seq2seq, VLM walkthroughs
162
+ - [Paper](paper/paper.tex) — full experimental results and method description (LaTeX)
163
+ - [Release notes](releases/v0.1.6.md) — what changed in this version
164
+
165
+ ---
166
+
167
+ ## Honest positioning
168
+
169
+ - **HQQ-4 beats ternary-quant on quality-per-bit** for standard LLMs — use it when quality is the priority
170
+ - **PT²-LLM and PTQTP** achieve strong PTQ ternary results on decoder-only LLMs — ternary-quant's algorithmic contribution on that axis is parallel, not superior
171
+ - The broad path is a ternary PTQ research/runtime path, not a general replacement for strong INT4 deployments
172
+ - The research track achieves true near-ternary weights with a real quality cost — this is the active research frontier, not a production-ready path
173
+ - GGUF is better for local deployment of supported standard LLMs and selected multimodal models; ternary-quant's value is component-first ternary PTQ in the HuggingFace ecosystem
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ternary-quant"
7
+ version = "0.1.6"
8
+ description = "Post-training ternary quantization for HuggingFace generative models"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [{name = "Asad Ismail"}]
13
+ keywords = ["quantization", "ternary", "llm", "vlm", "post-training-quantization", "generative-models"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
21
+ ]
22
+ dependencies = [
23
+ "torch>=2.1.0",
24
+ "transformers>=4.46.0",
25
+ "accelerate>=0.28.0",
26
+ "datasets>=2.18.0",
27
+ "safetensors>=0.4.0",
28
+ "tqdm",
29
+ "numpy",
30
+ ]
31
+
32
+ [project.urls]
33
+ Repository = "https://github.com/Asad-Ismail/ternary-quant"
34
+ Issues = "https://github.com/Asad-Ismail/ternary-quant/issues"
35
+
36
+ [project.optional-dependencies]
37
+ dev = ["pytest", "ruff"]
38
+ paper = ["hqq>=0.2.8.post1", "matplotlib>=3.7.0"]
39
+ multimodal = ["pillow", "num2words", "torchvision"]
40
+ eval = ["lm-eval>=0.4.0"]
41
+ serving = ["vllm>=0.4.0"]
42
+
43
+ [project.scripts]
44
+ ternary-quant = "ternary_quant.cli:main"
45
+
46
+ [tool.setuptools]
47
+ license-files = ["LICENSE"]
48
+
49
+ [tool.setuptools.packages.find]
50
+ include = ["ternary_quant*"]
51
+
52
+ [tool.ruff]
53
+ line-length = 100
54
+
55
+ [tool.ruff.lint]
56
+ select = ["F"] # pyflakes: unused imports, undefined names, unused variables
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+