mlx-quant-fidelity 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. mlx_quant_fidelity-0.1.0/.github/workflows/ci.yml +21 -0
  2. mlx_quant_fidelity-0.1.0/.github/workflows/release.yml +20 -0
  3. mlx_quant_fidelity-0.1.0/.gitignore +16 -0
  4. mlx_quant_fidelity-0.1.0/.python-version +1 -0
  5. mlx_quant_fidelity-0.1.0/CHANGELOG.md +19 -0
  6. mlx_quant_fidelity-0.1.0/LICENSE +202 -0
  7. mlx_quant_fidelity-0.1.0/NOTICE +4 -0
  8. mlx_quant_fidelity-0.1.0/PKG-INFO +122 -0
  9. mlx_quant_fidelity-0.1.0/README.md +89 -0
  10. mlx_quant_fidelity-0.1.0/ROADMAP.md +17 -0
  11. mlx_quant_fidelity-0.1.0/_artifacts/samples/llama-3.2-1b-4bit-kv4.json +37 -0
  12. mlx_quant_fidelity-0.1.0/_artifacts/samples/llama-3.2-1b-4bit-kv4.md +16 -0
  13. mlx_quant_fidelity-0.1.0/_artifacts/samples/llama-3.2-1b-4bit-kv8.json +37 -0
  14. mlx_quant_fidelity-0.1.0/_artifacts/samples/llama-3.2-1b-4bit-kv8.md +16 -0
  15. mlx_quant_fidelity-0.1.0/_artifacts/samples/llama-3.2-3b-4bit-kv4.json +37 -0
  16. mlx_quant_fidelity-0.1.0/_artifacts/samples/llama-3.2-3b-4bit-kv4.md +16 -0
  17. mlx_quant_fidelity-0.1.0/_artifacts/samples/llama-3.2-3b-4bit-kv8.json +37 -0
  18. mlx_quant_fidelity-0.1.0/_artifacts/samples/llama-3.2-3b-4bit-kv8.md +16 -0
  19. mlx_quant_fidelity-0.1.0/_artifacts/samples/qwen2.5-7b-4bit-kv4.json +37 -0
  20. mlx_quant_fidelity-0.1.0/_artifacts/samples/qwen2.5-7b-4bit-kv4.md +16 -0
  21. mlx_quant_fidelity-0.1.0/_artifacts/samples/qwen2.5-7b-4bit-kv8.json +37 -0
  22. mlx_quant_fidelity-0.1.0/_artifacts/samples/qwen2.5-7b-4bit-kv8.md +16 -0
  23. mlx_quant_fidelity-0.1.0/pyproject.toml +126 -0
  24. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/__init__.py +7 -0
  25. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/_memory_caps.py +51 -0
  26. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/_version.py +24 -0
  27. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/cli.py +74 -0
  28. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/corpora/__init__.py +6 -0
  29. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/corpora/provenance.py +28 -0
  30. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/corpora/wikitext.py +130 -0
  31. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/errors.py +21 -0
  32. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/metrics/__init__.py +16 -0
  33. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/metrics/aggregate.py +26 -0
  34. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/metrics/flip.py +10 -0
  35. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/metrics/kl.py +18 -0
  36. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/metrics/perplexity.py +23 -0
  37. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/policy.py +26 -0
  38. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/probes/__init__.py +1 -0
  39. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/probes/kv.py +235 -0
  40. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/py.typed +0 -0
  41. mlx_quant_fidelity-0.1.0/src/mlx_quant_fidelity/report.py +75 -0
  42. mlx_quant_fidelity-0.1.0/tests/conftest.py +71 -0
  43. mlx_quant_fidelity-0.1.0/tests/corpora/__init__.py +0 -0
  44. mlx_quant_fidelity-0.1.0/tests/corpora/test_chunking.py +93 -0
  45. mlx_quant_fidelity-0.1.0/tests/metrics/__init__.py +0 -0
  46. mlx_quant_fidelity-0.1.0/tests/metrics/test_aggregate.py +16 -0
  47. mlx_quant_fidelity-0.1.0/tests/metrics/test_flip.py +17 -0
  48. mlx_quant_fidelity-0.1.0/tests/metrics/test_kl.py +40 -0
  49. mlx_quant_fidelity-0.1.0/tests/metrics/test_perplexity.py +32 -0
  50. mlx_quant_fidelity-0.1.0/tests/probes/__init__.py +0 -0
  51. mlx_quant_fidelity-0.1.0/tests/probes/test_kv_fakeforward.py +194 -0
  52. mlx_quant_fidelity-0.1.0/tests/probes/test_kv_oracles.py +103 -0
  53. mlx_quant_fidelity-0.1.0/tests/test_cli.py +63 -0
  54. mlx_quant_fidelity-0.1.0/tests/test_errors.py +17 -0
  55. mlx_quant_fidelity-0.1.0/tests/test_markers.py +12 -0
  56. mlx_quant_fidelity-0.1.0/tests/test_memory_caps.py +50 -0
  57. mlx_quant_fidelity-0.1.0/tests/test_policy.py +17 -0
  58. mlx_quant_fidelity-0.1.0/tests/test_report.py +49 -0
  59. mlx_quant_fidelity-0.1.0/uv.lock +1336 -0
@@ -0,0 +1,21 @@
1
+ name: CI
2
+ on:
3
+ push:
4
+ branches: [main, "feature/**"]
5
+ pull_request:
6
+ branches: [main]
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: macos-15
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ with:
14
+ fetch-depth: 0 # hatch-vcs needs tags/history
15
+ - uses: astral-sh/setup-uv@v5
16
+ - run: uv sync --group dev
17
+ - run: uv run python -c "import mlx.core, mlx_lm; print('mlx import OK')"
18
+ - run: uv run ruff check .
19
+ - run: uv run ruff format --check .
20
+ - run: uv run mypy
21
+ - run: uv run pytest --cov=mlx_quant_fidelity --cov-report=term-missing --cov-fail-under=85
@@ -0,0 +1,20 @@
1
+ name: release
2
+ on:
3
+ push:
4
+ tags: ["v*"]
5
+
6
+ jobs:
7
+ build-and-publish:
8
+ # ubuntu, not macOS: pypa/gh-action-pypi-publish is Linux-only, and the package is a
9
+ # pure-Python (py3-none-any) wheel, so the build is platform-independent.
10
+ runs-on: ubuntu-latest
11
+ environment: pypi
12
+ permissions:
13
+ id-token: write # PyPI Trusted Publishing
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ with:
17
+ fetch-depth: 0 # hatch-vcs derives the version from the tag
18
+ - uses: astral-sh/setup-uv@v5
19
+ - run: uv build
20
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,16 @@
1
+ .codegraph/
2
+ .hypothesis/
3
+ docs/superpowers/
4
+ docs/backlog/
5
+ /CLAUDE.md
6
+ /_spike/
7
+ .coverage
8
+ .mypy_cache/
9
+ .pytest_cache/
10
+ .ruff_cache/
11
+ .venv/
12
+ __pycache__/
13
+ build/
14
+ dist/
15
+ *.egg-info/
16
+ src/mlx_quant_fidelity/_version.py
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
4
+ this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
+
6
+ ## [0.1.0]
7
+
8
+ First release. Measures how much quality a KV-cache quantization costs on MLX.
9
+
10
+ ### Added
11
+
12
+ - KV-cache fidelity probe: teacher-forced paired scoring of a quantized KV cache against full precision on the same model, on identical corpus tokens. Per-chunk reduction to scalars keeps a long corpus from holding full distributions in memory.
13
+ - Metrics in fp32: full-vocab KL divergence (mean, median, p99, max), top-token flip rate, and perplexity delta.
14
+ - `mlx-quant-fidelity kv <model>` CLI and `measure_kv_fidelity(...)` Python API, with JSON and Markdown reports that record the corpus provenance, model revision, and quantize-start mode.
15
+ - Stress mode (quantize from token 0) with an exact-zero guard that refuses to report a silent "perfect fidelity" when quantization never engaged.
16
+ - Cache-capability gate that flags models whose KV cache cannot be quantized instead of crashing mid-run.
17
+ - WikiText-2 test-split loader with a pinned, reproducible chunking contract.
18
+ - Device-derived wired-memory cap installed before any model load, on both the CLI and test paths.
19
+ - Committed sample reports for Llama-3.2-1B, Llama-3.2-3B, and Qwen2.5-7B at 4-bit and 8-bit KV.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ mlx-quant-fidelity
2
+ Copyright 2026 Denis Ineshin
3
+
4
+ Licensed under the Apache License, Version 2.0.
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: mlx-quant-fidelity
3
+ Version: 0.1.0
4
+ Summary: Measure MLX quantization quality loss — KL divergence, perplexity, top-token agreement for KV cache and weights
5
+ Project-URL: Homepage, https://github.com/IonDen/mlx-quant-fidelity
6
+ Project-URL: Source, https://github.com/IonDen/mlx-quant-fidelity
7
+ Project-URL: Issues, https://github.com/IonDen/mlx-quant-fidelity/issues
8
+ Project-URL: Changelog, https://github.com/IonDen/mlx-quant-fidelity/blob/main/CHANGELOG.md
9
+ Project-URL: Roadmap, https://github.com/IonDen/mlx-quant-fidelity/blob/main/ROADMAP.md
10
+ Author-email: Denis Ineshin <denis.ineshin@gmail.com>
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Keywords: apple-silicon,eval,kl-divergence,kv-cache,mlx,perplexity,quality,quantization
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: Science/Research
18
+ Classifier: License :: OSI Approved :: Apache Software License
19
+ Classifier: Operating System :: MacOS :: MacOS X
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.11
27
+ Requires-Dist: huggingface-hub>=0.24
28
+ Requires-Dist: mlx-lm>=0.31.3
29
+ Requires-Dist: mlx>=0.21
30
+ Requires-Dist: numpy>=1.26
31
+ Requires-Dist: pyarrow>=14
32
+ Description-Content-Type: text/markdown
33
+
34
+ # mlx-quant-fidelity
35
+
36
+ Measure how much quality a quantization costs on Apple Silicon. `mlx-quant-fidelity` scores a quantized KV cache against full precision on the same model and reports the drift as numbers you can act on: KL divergence, top-token flip rate, perplexity delta. No more choosing a bit-width by file size.
37
+
38
+ The CUDA/GGUF world has had this for years: llama.cpp's `--kl-divergence-base`, EleutherAI's `lm-evaluation-harness`. MLX had nothing. This is the MLX version, and it covers the KV-cache and attention angle those tools skip.
39
+
40
+ Version 0.1.0 measures **KV-cache quantization**. Weight-quantization fidelity is next; see the [roadmap](ROADMAP.md).
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install mlx-quant-fidelity
46
+ ```
47
+
48
+ Apple Silicon (MLX), Python 3.11+.
49
+
50
+ ## Use it
51
+
52
+ ```bash
53
+ mlx-quant-fidelity kv mlx-community/Llama-3.2-3B-Instruct-4bit --kv-bits 8
54
+ ```
55
+
56
+ Prints a Markdown report. Add `--format json` for JSON, `--kv-bits 4`, `--kv-group-size 64`, or `--max-chunks N` to bound the corpus.
57
+
58
+ ```python
59
+ from mlx_quant_fidelity import measure_kv_fidelity
60
+
61
+ report = measure_kv_fidelity("mlx-community/Llama-3.2-3B-Instruct-4bit", kv_bits=8)
62
+ print(report.kl.mean, report.flip_rate, report.verdict)
63
+ ```
64
+
65
+ ## What a report looks like
66
+
67
+ ```markdown
68
+ # KV-fidelity: `mlx-community/Llama-3.2-3B-Instruct-4bit` @ 8-bit (group 64)
69
+
70
+ **Verdict:** good · **mode:** stress (quantize_start=0)
71
+
72
+ | metric | value |
73
+ |---|---|
74
+ | KL mean | 0.0002 nats |
75
+ | KL median | 0.0001 nats |
76
+ | KL p99 | 0.0015 nats |
77
+ | KL max | 0.1129 nats |
78
+ | flip rate | 0.0065 |
79
+ | perplexity Δ | +0.0054 (17.722 → 17.728) |
80
+
81
+ Measured on **wikitext-2-raw/test**, 51100 positions across 100 chunks of length 512 ...
82
+ ```
83
+
84
+ ## How much does KV quantization cost?
85
+
86
+ M1 Max, WikiText-2 test (100 chunks of 512 tokens), stress mode (quantize from token 0). Reproduce any row with `mlx-quant-fidelity kv <model> --kv-bits <bits> --max-chunks 100`; the full committed reports are under [`_artifacts/samples/`](_artifacts/samples).
87
+
88
+ | Model | KV bits | KL mean (nats) | flip rate | verdict |
89
+ |---|---|---|---|---|
90
+ | Llama-3.2-1B | 4 | 0.148 | 0.20 | bad |
91
+ | Llama-3.2-1B | 8 | 0.0004 | 0.013 | marginal |
92
+ | Llama-3.2-3B | 4 | 0.051 | 0.11 | bad |
93
+ | Llama-3.2-3B | 8 | 0.0002 | 0.007 | good |
94
+ | Qwen2.5-7B | 4 | 9.36 | 0.99 | bad |
95
+ | Qwen2.5-7B | 8 | 0.009 | 0.032 | marginal |
96
+
97
+ 8-bit KV is near-lossless on all three models. 4-bit is another matter, and Qwen2.5-7B at 4-bit in stress mode falls apart: nearly every token flips. That is the attention sink at work: stress mode quantizes the cache from token 0, including the first tokens attention leans on most, and Qwen2.5 does not tolerate it. mlx-lm's own default keeps the first 5000 tokens full-precision for exactly this reason. The point of the tool is that you can see this for your model before you pick a bit-width.
98
+
99
+ ## How it works
100
+
101
+ Teacher-forced scoring, not generation. For each fixed-length corpus chunk the model runs twice on the *same* tokens — once with a full-precision KV cache, once with a quantized one — and the two next-token distributions are compared position by position. Generation would let the runs diverge in their own inputs the moment quantization changed a sampled token, turning the measurement into trajectory drift instead of cache cost. Logits collapse to per-position scalars inside the chunk loop and are released before the next chunk, so a long corpus never holds full distributions in memory.
102
+
103
+ Two modes:
104
+
105
+ - **stress** (`--quantize-start 0`, the default): quantize from token 0. The harsh, apples-to-apples quantizer test.
106
+ - **deployment** (`quantize_start > 0`): what mlx-lm users actually run, with the first N tokens kept full-precision. Planned for 0.2.0.
107
+
108
+ A run that returns exactly zero drift raises instead of reporting a silent "perfect fidelity." That almost always means quantization never engaged, not that it was free.
109
+
110
+ ## What the numbers don't say
111
+
112
+ - A fidelity number is **corpus- and context-length-specific**. WikiText-2 at temperature 0 measures short-prose distributional drift; the paper this builds on, *Accuracy Is Not All You Need*, shows that under-predicts task-specific and long-context degradation. Every report records the corpus and the token count so the number is never read as a bare score.
113
+ - Perplexity delta is reported for continuity with llama.cpp. It correlates with mean KLD by construction, so treat it as a familiar restatement, not independent corroboration.
114
+ - The measured drift bundles the quantizer's error with the quantized-attention kernel's numerics. That is the real end-to-end cost; a quantizer-only control is on the roadmap.
115
+
116
+ ## Status
117
+
118
+ 0.1.0, released on PyPI as `mlx-quant-fidelity` — the KV-cache fidelity probe (CLI + Python API, JSON and Markdown reports). Weight-quantization fidelity, downstream-task accuracy, and memory-normalized method ranking are on the [roadmap](ROADMAP.md).
119
+
120
+ ## License
121
+
122
+ [Apache-2.0](LICENSE).
@@ -0,0 +1,89 @@
1
+ # mlx-quant-fidelity
2
+
3
+ Measure how much quality a quantization costs on Apple Silicon. `mlx-quant-fidelity` scores a quantized KV cache against full precision on the same model and reports the drift as numbers you can act on: KL divergence, top-token flip rate, perplexity delta. No more choosing a bit-width by file size.
4
+
5
+ The CUDA/GGUF world has had this for years: llama.cpp's `--kl-divergence-base`, EleutherAI's `lm-evaluation-harness`. MLX had nothing. This is the MLX version, and it covers the KV-cache and attention angle those tools skip.
6
+
7
+ Version 0.1.0 measures **KV-cache quantization**. Weight-quantization fidelity is next; see the [roadmap](ROADMAP.md).
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install mlx-quant-fidelity
13
+ ```
14
+
15
+ Apple Silicon (MLX), Python 3.11+.
16
+
17
+ ## Use it
18
+
19
+ ```bash
20
+ mlx-quant-fidelity kv mlx-community/Llama-3.2-3B-Instruct-4bit --kv-bits 8
21
+ ```
22
+
23
+ Prints a Markdown report. Add `--format json` for JSON, `--kv-bits 4`, `--kv-group-size 64`, or `--max-chunks N` to bound the corpus.
24
+
25
+ ```python
26
+ from mlx_quant_fidelity import measure_kv_fidelity
27
+
28
+ report = measure_kv_fidelity("mlx-community/Llama-3.2-3B-Instruct-4bit", kv_bits=8)
29
+ print(report.kl.mean, report.flip_rate, report.verdict)
30
+ ```
31
+
32
+ ## What a report looks like
33
+
34
+ ```markdown
35
+ # KV-fidelity: `mlx-community/Llama-3.2-3B-Instruct-4bit` @ 8-bit (group 64)
36
+
37
+ **Verdict:** good · **mode:** stress (quantize_start=0)
38
+
39
+ | metric | value |
40
+ |---|---|
41
+ | KL mean | 0.0002 nats |
42
+ | KL median | 0.0001 nats |
43
+ | KL p99 | 0.0015 nats |
44
+ | KL max | 0.1129 nats |
45
+ | flip rate | 0.0065 |
46
+ | perplexity Δ | +0.0054 (17.722 → 17.728) |
47
+
48
+ Measured on **wikitext-2-raw/test**, 51100 positions across 100 chunks of length 512 ...
49
+ ```
50
+
51
+ ## How much does KV quantization cost?
52
+
53
+ M1 Max, WikiText-2 test (100 chunks of 512 tokens), stress mode (quantize from token 0). Reproduce any row with `mlx-quant-fidelity kv <model> --kv-bits <bits> --max-chunks 100`; the full committed reports are under [`_artifacts/samples/`](_artifacts/samples).
54
+
55
+ | Model | KV bits | KL mean (nats) | flip rate | verdict |
56
+ |---|---|---|---|---|
57
+ | Llama-3.2-1B | 4 | 0.148 | 0.20 | bad |
58
+ | Llama-3.2-1B | 8 | 0.0004 | 0.013 | marginal |
59
+ | Llama-3.2-3B | 4 | 0.051 | 0.11 | bad |
60
+ | Llama-3.2-3B | 8 | 0.0002 | 0.007 | good |
61
+ | Qwen2.5-7B | 4 | 9.36 | 0.99 | bad |
62
+ | Qwen2.5-7B | 8 | 0.009 | 0.032 | marginal |
63
+
64
+ 8-bit KV is near-lossless on all three models. 4-bit is another matter, and Qwen2.5-7B at 4-bit in stress mode falls apart: nearly every token flips. That is the attention sink at work: stress mode quantizes the cache from token 0, including the first tokens attention leans on most, and Qwen2.5 does not tolerate it. mlx-lm's own default keeps the first 5000 tokens full-precision for exactly this reason. The point of the tool is that you can see this for your model before you pick a bit-width.
65
+
66
+ ## How it works
67
+
68
+ Teacher-forced scoring, not generation. For each fixed-length corpus chunk the model runs twice on the *same* tokens — once with a full-precision KV cache, once with a quantized one — and the two next-token distributions are compared position by position. Generation would let the runs diverge in their own inputs the moment quantization changed a sampled token, turning the measurement into trajectory drift instead of cache cost. Logits collapse to per-position scalars inside the chunk loop and are released before the next chunk, so a long corpus never holds full distributions in memory.
69
+
70
+ Two modes:
71
+
72
+ - **stress** (`--quantize-start 0`, the default): quantize from token 0. The harsh, apples-to-apples quantizer test.
73
+ - **deployment** (`quantize_start > 0`): what mlx-lm users actually run, with the first N tokens kept full-precision. Planned for 0.2.0.
74
+
75
+ A run that returns exactly zero drift raises instead of reporting a silent "perfect fidelity." That almost always means quantization never engaged, not that it was free.
76
+
77
+ ## What the numbers don't say
78
+
79
+ - A fidelity number is **corpus- and context-length-specific**. WikiText-2 at temperature 0 measures short-prose distributional drift; the paper this builds on, *Accuracy Is Not All You Need*, shows that under-predicts task-specific and long-context degradation. Every report records the corpus and the token count so the number is never read as a bare score.
80
+ - Perplexity delta is reported for continuity with llama.cpp. It correlates with mean KLD by construction, so treat it as a familiar restatement, not independent corroboration.
81
+ - The measured drift bundles the quantizer's error with the quantized-attention kernel's numerics. That is the real end-to-end cost; a quantizer-only control is on the roadmap.
82
+
83
+ ## Status
84
+
85
+ 0.1.0, released on PyPI as `mlx-quant-fidelity` — the KV-cache fidelity probe (CLI + Python API, JSON and Markdown reports). Weight-quantization fidelity, downstream-task accuracy, and memory-normalized method ranking are on the [roadmap](ROADMAP.md).
86
+
87
+ ## License
88
+
89
+ [Apache-2.0](LICENSE).
@@ -0,0 +1,17 @@
1
+ # Roadmap
2
+
3
+ `mlx-quant-fidelity` measures how much quality a quantization costs on Apple Silicon / MLX.
4
+
5
+ ## Released
6
+
7
+ - **0.1.0** — KV-cache quantization fidelity: KL divergence, top-token flip rate, perplexity delta; CLI and Python API; JSON/Markdown reports; WikiText-2 corpus.
8
+
9
+ ## Next
10
+
11
+ - **Weight-quantization fidelity** — the same drift metrics for q4/q6/q8 weight quantization, with reference-logit handling that respects the full-vocab KLD requirement (stream or recompute rather than persist truncated top-k).
12
+ - **Deployment mode** — `quantize_start > 0`, matching what mlx-lm users run, with the first N tokens kept full-precision.
13
+ - **Downstream-task accuracy** — EleutherAI's lm-evaluation-harness (MMLU, ARC, HellaSwag, GSM8K, HumanEval) alongside distributional drift.
14
+ - **Method comparison** — rank quantization methods on one yardstick, memory-normalized (quality vs KV bytes per token) as a Pareto view, never a raw-metric sort.
15
+ - **Quantizer-only control** — an optional dequantize-then-standard-attention path that separates quantizer error from quantized-kernel numerics.
16
+ - **Wider attention coverage** — MLA and sliding-window caches beyond flag-don't-crash.
17
+ - **Fidelity badge** — a model-card badge driven by an explicit, documented threshold policy.
@@ -0,0 +1,37 @@
1
+ {
2
+ "cache_supported": true,
3
+ "corpus": {
4
+ "bos_policy": "none",
5
+ "chunk_length": 512,
6
+ "final_chunk_policy": "drop",
7
+ "n_tokens": 51200,
8
+ "name": "wikitext-2-raw",
9
+ "normalization": "raw",
10
+ "split": "test",
11
+ "stride": 512,
12
+ "tokenizer_id": "mlx-community/Llama-3.2-1B-Instruct-4bit"
13
+ },
14
+ "flip_rate": 0.20483365949119373,
15
+ "kl": {
16
+ "max": 6.249123573303223,
17
+ "mean": 0.14773540842612012,
18
+ "median": 0.09692534431815147,
19
+ "p99": 0.9224590277671838
20
+ },
21
+ "kv_bits": 4,
22
+ "kv_group_size": 64,
23
+ "mlx_lm_version": "0.31.3",
24
+ "mlx_version": "0.31.2",
25
+ "model_id": "mlx-community/Llama-3.2-1B-Instruct-4bit",
26
+ "model_revision": "08231374eeacb049a0eade7922910865b8fce912",
27
+ "n_chunks": 100,
28
+ "n_positions": 51100,
29
+ "peak_memory_bytes": 2552171857,
30
+ "perplexity_delta": 4.121097638366695,
31
+ "perplexity_quant": 27.06214792192995,
32
+ "perplexity_ref": 22.941050283563253,
33
+ "quantize_mode": "stress",
34
+ "quantize_start": 0,
35
+ "verdict": "bad",
36
+ "warnings": []
37
+ }
@@ -0,0 +1,16 @@
1
+ # KV-fidelity: `mlx-community/Llama-3.2-1B-Instruct-4bit` @ 4-bit (group 64)
2
+
3
+ **Verdict:** bad · **mode:** stress (quantize_start=0)
4
+
5
+ | metric | value |
6
+ |---|---|
7
+ | KL mean | 0.1477 nats |
8
+ | KL median | 0.0969 nats |
9
+ | KL p99 | 0.9225 nats |
10
+ | KL max | 6.2491 nats |
11
+ | flip rate | 0.2048 |
12
+ | perplexity Δ | +4.1211 (22.941 → 27.062) |
13
+
14
+ Measured on **wikitext-2-raw/test**, 51100 positions across 100 chunks of length 512 (tokenizer `mlx-community/Llama-3.2-1B-Instruct-4bit`). Fidelity is corpus- and context-length-specific; short-prose temp-0 drift under-predicts long-context/code degradation.
15
+
16
+ _mlx 0.31.2, mlx-lm 0.31.3, model rev `08231374eeacb049a0eade7922910865b8fce912`, peak 2.55 GB._
@@ -0,0 +1,37 @@
1
+ {
2
+ "cache_supported": true,
3
+ "corpus": {
4
+ "bos_policy": "none",
5
+ "chunk_length": 512,
6
+ "final_chunk_policy": "drop",
7
+ "n_tokens": 51200,
8
+ "name": "wikitext-2-raw",
9
+ "normalization": "raw",
10
+ "split": "test",
11
+ "stride": 512,
12
+ "tokenizer_id": "mlx-community/Llama-3.2-1B-Instruct-4bit"
13
+ },
14
+ "flip_rate": 0.012583170254403132,
15
+ "kl": {
16
+ "max": 0.04656221345067024,
17
+ "mean": 0.0004305653305290256,
18
+ "median": 0.00027623827918432653,
19
+ "p99": 0.002857390865683556
20
+ },
21
+ "kv_bits": 8,
22
+ "kv_group_size": 64,
23
+ "mlx_lm_version": "0.31.3",
24
+ "mlx_version": "0.31.2",
25
+ "model_id": "mlx-community/Llama-3.2-1B-Instruct-4bit",
26
+ "model_revision": "08231374eeacb049a0eade7922910865b8fce912",
27
+ "n_chunks": 100,
28
+ "n_positions": 51100,
29
+ "peak_memory_bytes": 2556678370,
30
+ "perplexity_delta": 0.015172139713783395,
31
+ "perplexity_quant": 22.956222423277037,
32
+ "perplexity_ref": 22.941050283563253,
33
+ "quantize_mode": "stress",
34
+ "quantize_start": 0,
35
+ "verdict": "marginal",
36
+ "warnings": []
37
+ }
@@ -0,0 +1,16 @@
1
+ # KV-fidelity: `mlx-community/Llama-3.2-1B-Instruct-4bit` @ 8-bit (group 64)
2
+
3
+ **Verdict:** marginal · **mode:** stress (quantize_start=0)
4
+
5
+ | metric | value |
6
+ |---|---|
7
+ | KL mean | 0.0004 nats |
8
+ | KL median | 0.0003 nats |
9
+ | KL p99 | 0.0029 nats |
10
+ | KL max | 0.0466 nats |
11
+ | flip rate | 0.0126 |
12
+ | perplexity Δ | +0.0152 (22.941 → 22.956) |
13
+
14
+ Measured on **wikitext-2-raw/test**, 51100 positions across 100 chunks of length 512 (tokenizer `mlx-community/Llama-3.2-1B-Instruct-4bit`). Fidelity is corpus- and context-length-specific; short-prose temp-0 drift under-predicts long-context/code degradation.
15
+
16
+ _mlx 0.31.2, mlx-lm 0.31.3, model rev `08231374eeacb049a0eade7922910865b8fce912`, peak 2.56 GB._