szl-quant-bench 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- szl_quant_bench-0.2.0/LICENSE +201 -0
- szl_quant_bench-0.2.0/PKG-INFO +81 -0
- szl_quant_bench-0.2.0/README.md +71 -0
- szl_quant_bench-0.2.0/pyproject.toml +17 -0
- szl_quant_bench-0.2.0/setup.cfg +4 -0
- szl_quant_bench-0.2.0/src/szl_quant_bench/__init__.py +2 -0
- szl_quant_bench-0.2.0/src/szl_quant_bench/harness.py +138 -0
- szl_quant_bench-0.2.0/src/szl_quant_bench/metrics.py +40 -0
- szl_quant_bench-0.2.0/src/szl_quant_bench/quant.py +21 -0
- szl_quant_bench-0.2.0/src/szl_quant_bench/receipts.py +39 -0
- szl_quant_bench-0.2.0/src/szl_quant_bench.egg-info/PKG-INFO +81 -0
- szl_quant_bench-0.2.0/src/szl_quant_bench.egg-info/SOURCES.txt +15 -0
- szl_quant_bench-0.2.0/src/szl_quant_bench.egg-info/dependency_links.txt +1 -0
- szl_quant_bench-0.2.0/src/szl_quant_bench.egg-info/top_level.txt +1 -0
- szl_quant_bench-0.2.0/tests/test_provenance.py +115 -0
- szl_quant_bench-0.2.0/tests/test_quant_bench.py +70 -0
- szl_quant_bench-0.2.0/tests/test_receipt_required.py +20 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 SZL Holdings
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: szl-quant-bench
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Honest quantization quality-curve bench: cosine/KL/top-1 degradation vs bit-width, hash-chained receipts. Fail closed.
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# szl-quant-bench
|
|
12
|
+
|
|
13
|
+
Honest quantization quality-curve bench for the SZL estate. Real uniform
|
|
14
|
+
absmax quantization (round-to-nearest, signed ints, 2–16 bits) with quality
|
|
15
|
+
metrics — cosine similarity, KL divergence over softmaxed rows, top-1
|
|
16
|
+
agreement, MSE — on the supplied logits. This measures logit quantization,
|
|
17
|
+
not weight quantization, GGUF behavior, inference speed, or model quality
|
|
18
|
+
after a weight conversion. Stdlib only; no downloads, no network.
|
|
19
|
+
|
|
20
|
+
Doctrine: empty or missing inputs return `BLOCKED` with a reason. The demo
|
|
21
|
+
fixture is synthetic and labeled as such. Nothing here claims to measure a
|
|
22
|
+
real model unless you pass real logits in. Run states:
|
|
23
|
+
`MEASURED | BLOCKED | INVALID | FAILED`.
|
|
24
|
+
|
|
25
|
+
## Install and verify
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
pip install -e . pytest
|
|
29
|
+
python -m pytest tests/ -q
|
|
30
|
+
python -m szl_quant_bench.harness # deterministic fixture curve + receipt
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Measured fixture curve (synthetic gaussian logits, seed 42 — NOT a real model)
|
|
34
|
+
|
|
35
|
+
| bits | cosine | KL (mean) | top-1 agreement | vs fp32 |
|
|
36
|
+
|---|---|---|---|---|
|
|
37
|
+
| 16 | 1.0000 | 0.00000 | 100.0% | 2.0x |
|
|
38
|
+
| 8 | 1.0000 | 0.00003 | 100.0% | 4.0x |
|
|
39
|
+
| 4 | 0.9882 | 0.01211 | 68.8% | 8.0x |
|
|
40
|
+
| 3 | 0.9420 | 0.06556 | 56.2% | 10.67x |
|
|
41
|
+
| 2 | 0.5715 | 0.57019 | 50.0% | 16.0x |
|
|
42
|
+
|
|
43
|
+
These numbers came out of `run_curve` in this repository, executed before the
|
|
44
|
+
initial push. Your model's curve will differ — run it on real logits.
|
|
45
|
+
|
|
46
|
+
## Measuring a real model
|
|
47
|
+
|
|
48
|
+
Capture a logit batch from the exact model revision and fixed evaluation
|
|
49
|
+
prompt set. Store a JSON object with `logits` (a rectangular finite numeric
|
|
50
|
+
matrix) and `provenance` containing:
|
|
51
|
+
|
|
52
|
+
- `source_kind`: `REAL_MODEL_LOGITS`
|
|
53
|
+
- `model_id`, `runtime`, `hardware`: nonempty identifiers
|
|
54
|
+
- `model_revision`: the exact 40-character lowercase commit
|
|
55
|
+
- `prompt_set_sha256`: the full lowercase SHA-256 of the saved prompt artifact
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
python -m szl_quant_bench.harness --input model-logits.json --output curve-receipt.json
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The output file must not already exist. Missing provenance, malformed matrices,
|
|
62
|
+
non-finite values and invalid bit widths fail closed with a nonzero exit.
|
|
63
|
+
With no input the CLI runs only the explicitly `SYNTHETIC` fixture.
|
|
64
|
+
The Python API accepts `run_curve(logits, chain=chain, provenance=provenance)`;
|
|
65
|
+
omitting provenance labels the source `UNVERIFIED_CALLER_INPUT`. Every
|
|
66
|
+
`MEASURED` API result carries a hash-chained receipt record. If no chain is
|
|
67
|
+
supplied, the API creates a fresh one-record chain for that measurement; pass
|
|
68
|
+
a caller-owned `ReceiptChain` to append the record to an existing chain.
|
|
69
|
+
|
|
70
|
+
Receipts bind the normalized float input matrix hash, complete provenance,
|
|
71
|
+
all quality records and the explicit measurement boundary. Provenance remains
|
|
72
|
+
`CALLER_DECLARED`: a hash cannot establish that the caller actually ran a model.
|
|
73
|
+
Preserve the raw logits and independent model execution evidence to support
|
|
74
|
+
that claim. Empty or malformed chains do not verify. KL is evaluated in log
|
|
75
|
+
space without silently clipping small probabilities.
|
|
76
|
+
|
|
77
|
+
Compare bit widths only on the same inputs, hardware and revision. A measured
|
|
78
|
+
logit curve does **not** authorize a GGUF export decision: actual quantized
|
|
79
|
+
model outputs and runtime evaluation are separately required.
|
|
80
|
+
|
|
81
|
+
Apache-2.0 · Doctrine v11 · SZL Holdings
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# szl-quant-bench
|
|
2
|
+
|
|
3
|
+
Honest quantization quality-curve bench for the SZL estate. Real uniform
|
|
4
|
+
absmax quantization (round-to-nearest, signed ints, 2–16 bits) with quality
|
|
5
|
+
metrics — cosine similarity, KL divergence over softmaxed rows, top-1
|
|
6
|
+
agreement, MSE — on the supplied logits. This measures logit quantization,
|
|
7
|
+
not weight quantization, GGUF behavior, inference speed, or model quality
|
|
8
|
+
after a weight conversion. Stdlib only; no downloads, no network.
|
|
9
|
+
|
|
10
|
+
Doctrine: empty or missing inputs return `BLOCKED` with a reason. The demo
|
|
11
|
+
fixture is synthetic and labeled as such. Nothing here claims to measure a
|
|
12
|
+
real model unless you pass real logits in. Run states:
|
|
13
|
+
`MEASURED | BLOCKED | INVALID | FAILED`.
|
|
14
|
+
|
|
15
|
+
## Install and verify
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
pip install -e . pytest
|
|
19
|
+
python -m pytest tests/ -q
|
|
20
|
+
python -m szl_quant_bench.harness # deterministic fixture curve + receipt
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Measured fixture curve (synthetic gaussian logits, seed 42 — NOT a real model)
|
|
24
|
+
|
|
25
|
+
| bits | cosine | KL (mean) | top-1 agreement | vs fp32 |
|
|
26
|
+
|---|---|---|---|---|
|
|
27
|
+
| 16 | 1.0000 | 0.00000 | 100.0% | 2.0x |
|
|
28
|
+
| 8 | 1.0000 | 0.00003 | 100.0% | 4.0x |
|
|
29
|
+
| 4 | 0.9882 | 0.01211 | 68.8% | 8.0x |
|
|
30
|
+
| 3 | 0.9420 | 0.06556 | 56.2% | 10.67x |
|
|
31
|
+
| 2 | 0.5715 | 0.57019 | 50.0% | 16.0x |
|
|
32
|
+
|
|
33
|
+
These numbers came out of `run_curve` in this repository, executed before the
|
|
34
|
+
initial push. Your model's curve will differ — run it on real logits.
|
|
35
|
+
|
|
36
|
+
## Measuring a real model
|
|
37
|
+
|
|
38
|
+
Capture a logit batch from the exact model revision and fixed evaluation
|
|
39
|
+
prompt set. Store a JSON object with `logits` (a rectangular finite numeric
|
|
40
|
+
matrix) and `provenance` containing:
|
|
41
|
+
|
|
42
|
+
- `source_kind`: `REAL_MODEL_LOGITS`
|
|
43
|
+
- `model_id`, `runtime`, `hardware`: nonempty identifiers
|
|
44
|
+
- `model_revision`: the exact 40-character lowercase commit
|
|
45
|
+
- `prompt_set_sha256`: the full lowercase SHA-256 of the saved prompt artifact
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
python -m szl_quant_bench.harness --input model-logits.json --output curve-receipt.json
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The output file must not already exist. Missing provenance, malformed matrices,
|
|
52
|
+
non-finite values and invalid bit widths fail closed with a nonzero exit.
|
|
53
|
+
With no input the CLI runs only the explicitly `SYNTHETIC` fixture.
|
|
54
|
+
The Python API accepts `run_curve(logits, chain=chain, provenance=provenance)`;
|
|
55
|
+
omitting provenance labels the source `UNVERIFIED_CALLER_INPUT`. Every
|
|
56
|
+
`MEASURED` API result carries a hash-chained receipt record. If no chain is
|
|
57
|
+
supplied, the API creates a fresh one-record chain for that measurement; pass
|
|
58
|
+
a caller-owned `ReceiptChain` to append the record to an existing chain.
|
|
59
|
+
|
|
60
|
+
Receipts bind the normalized float input matrix hash, complete provenance,
|
|
61
|
+
all quality records and the explicit measurement boundary. Provenance remains
|
|
62
|
+
`CALLER_DECLARED`: a hash cannot establish that the caller actually ran a model.
|
|
63
|
+
Preserve the raw logits and independent model execution evidence to support
|
|
64
|
+
that claim. Empty or malformed chains do not verify. KL is evaluated in log
|
|
65
|
+
space without silently clipping small probabilities.
|
|
66
|
+
|
|
67
|
+
Compare bit widths only on the same inputs, hardware and revision. A measured
|
|
68
|
+
logit curve does **not** authorize a GGUF export decision: actual quantized
|
|
69
|
+
model outputs and runtime evaluation are separately required.
|
|
70
|
+
|
|
71
|
+
Apache-2.0 · Doctrine v11 · SZL Holdings
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "szl-quant-bench"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Honest quantization quality-curve bench: cosine/KL/top-1 degradation vs bit-width, hash-chained receipts. Fail closed."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = {text = "Apache-2.0"}
|
|
12
|
+
|
|
13
|
+
[tool.setuptools.packages.find]
|
|
14
|
+
where = ["src"]
|
|
15
|
+
|
|
16
|
+
[tool.pytest.ini_options]
|
|
17
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Quantization quality-curve harness. MEASURED only from real math; else BLOCKED.
|
|
2
|
+
|
|
3
|
+
Run states: MEASURED | BLOCKED | INVALID | FAILED. Never fabricate a number.
|
|
4
|
+
"""
|
|
5
|
+
import argparse
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import re
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from .metrics import cosine, kl_divergence, mse, top1_agreement
|
|
13
|
+
from .quant import dequantize, quantize
|
|
14
|
+
from .receipts import ReceiptChain
|
|
15
|
+
|
|
16
|
+
STATES = ("MEASURED", "BLOCKED", "INVALID", "FAILED")
|
|
17
|
+
DEFAULT_BITS = (16, 8, 4, 3, 2)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _canonical(value):
|
|
21
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"),
|
|
22
|
+
ensure_ascii=False, allow_nan=False)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _provenance(value):
|
|
26
|
+
if value is None:
|
|
27
|
+
return {"source_kind": "UNVERIFIED_CALLER_INPUT"}
|
|
28
|
+
if not isinstance(value, dict):
|
|
29
|
+
raise ValueError("provenance must be an object")
|
|
30
|
+
result = json.loads(_canonical(value))
|
|
31
|
+
if result.get("source_kind") not in ("SYNTHETIC", "REAL_MODEL_LOGITS"):
|
|
32
|
+
raise ValueError("source_kind must be SYNTHETIC or REAL_MODEL_LOGITS")
|
|
33
|
+
if result["source_kind"] == "REAL_MODEL_LOGITS":
|
|
34
|
+
for key in ("model_id", "runtime", "hardware"):
|
|
35
|
+
if not isinstance(result.get(key), str) or not result[key].strip():
|
|
36
|
+
raise ValueError(f"real-model provenance requires {key}")
|
|
37
|
+
if not re.fullmatch(r"[0-9a-f]{40}", result.get("model_revision", "")):
|
|
38
|
+
raise ValueError("model_revision must be an exact 40-character commit")
|
|
39
|
+
if not re.fullmatch(r"[0-9a-f]{64}", result.get("prompt_set_sha256", "")):
|
|
40
|
+
raise ValueError("prompt_set_sha256 must be a full SHA-256")
|
|
41
|
+
return result
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def run_curve(logits, bits=DEFAULT_BITS, chain=None, *, provenance=None):
|
|
45
|
+
"""logits: list of rows (list of float), e.g. output logits for a token batch.
|
|
46
|
+
|
|
47
|
+
Returns per-bit quality records computed from actual quantize/dequantize.
|
|
48
|
+
Synthetic-fixture results are labeled as such by the caller; nothing here
|
|
49
|
+
claims to measure a real model unless real logits were passed in.
|
|
50
|
+
"""
|
|
51
|
+
if logits is None or (isinstance(logits, (list, tuple)) and
|
|
52
|
+
(not logits or all(isinstance(row, (list, tuple)) and not row
|
|
53
|
+
for row in logits))):
|
|
54
|
+
return {"state": "BLOCKED", "reason": "empty logits matrix"}
|
|
55
|
+
try:
|
|
56
|
+
if not isinstance(logits, (list, tuple)) or not logits:
|
|
57
|
+
raise ValueError("logits must be a nonempty rectangular matrix")
|
|
58
|
+
if any(not isinstance(row, (list, tuple)) or not row for row in logits):
|
|
59
|
+
raise ValueError("each logits row must be a nonempty array")
|
|
60
|
+
n_cols = len(logits[0])
|
|
61
|
+
if any(len(row) != n_cols for row in logits):
|
|
62
|
+
raise ValueError("logits rows must have equal length")
|
|
63
|
+
if any(isinstance(x, bool) or not isinstance(x, (int, float))
|
|
64
|
+
or not math.isfinite(float(x)) for row in logits for x in row):
|
|
65
|
+
raise ValueError("logits must contain only finite real numbers")
|
|
66
|
+
if not isinstance(bits, (list, tuple)) or not bits:
|
|
67
|
+
raise ValueError("bits must be a nonempty array")
|
|
68
|
+
if any(type(b) is not int or not 2 <= b <= 16 for b in bits):
|
|
69
|
+
raise ValueError("each bit width must be an integer in 2..16")
|
|
70
|
+
if len(set(bits)) != len(bits):
|
|
71
|
+
raise ValueError("duplicate bit widths are not allowed")
|
|
72
|
+
origin = _provenance(provenance)
|
|
73
|
+
logits = [[float(x) for x in row] for row in logits]
|
|
74
|
+
input_hash = hashlib.sha256(_canonical(logits).encode()).hexdigest()
|
|
75
|
+
flat = [x for row in logits for x in row]
|
|
76
|
+
records = []
|
|
77
|
+
for b in bits:
|
|
78
|
+
ints, scale = quantize(flat, b)
|
|
79
|
+
deq = dequantize(ints, scale)
|
|
80
|
+
rows_dq = [deq[i * n_cols:(i + 1) * n_cols] for i in range(len(logits))]
|
|
81
|
+
records.append({
|
|
82
|
+
"bits": b,
|
|
83
|
+
"mse": round(mse(flat, deq), 8),
|
|
84
|
+
"cosine": round(sum(cosine(a, d) for a, d in zip(logits, rows_dq)) / len(logits), 6),
|
|
85
|
+
"kl_mean": round(sum(kl_divergence(a, d) for a, d in zip(logits, rows_dq)) / len(logits), 8),
|
|
86
|
+
"top1_agreement": round(top1_agreement(logits, rows_dq), 6),
|
|
87
|
+
"compression_vs_fp32": round(32.0 / b, 2),
|
|
88
|
+
})
|
|
89
|
+
_canonical(records) # reject overflow or any non-finite computed metric
|
|
90
|
+
except (ValueError, TypeError, OverflowError, ZeroDivisionError) as exc:
|
|
91
|
+
return {"state": "INVALID", "reason": str(exc)}
|
|
92
|
+
result = {"state": "MEASURED", "lane": "quant-curve", "rows": len(logits),
|
|
93
|
+
"cols": n_cols, "curve": records, "input_sha256": input_hash,
|
|
94
|
+
"provenance": origin, "provenance_authority": "CALLER_DECLARED",
|
|
95
|
+
"measurement": "UNIFORM_LOGIT_QUANTIZATION",
|
|
96
|
+
"weight_quantization_measured": False,
|
|
97
|
+
"gguf_export_authorized": False}
|
|
98
|
+
receipt_chain = chain if chain is not None else ReceiptChain()
|
|
99
|
+
result["receipt"] = receipt_chain.emit({"type": "quant_curve", **result})
|
|
100
|
+
return result
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def main():
|
|
104
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
105
|
+
parser.add_argument("--input", type=Path, help="JSON object with logits and provenance")
|
|
106
|
+
parser.add_argument("--output", type=Path, help="new receipt JSON file; never overwritten")
|
|
107
|
+
args = parser.parse_args()
|
|
108
|
+
from random import Random
|
|
109
|
+
rng = Random(42) # deterministic synthetic fixture, honestly labeled
|
|
110
|
+
logits = [[rng.gauss(0, 1) for _ in range(64)] for _ in range(16)]
|
|
111
|
+
origin = {"source_kind": "SYNTHETIC", "fixture": "gaussian seed 42"}
|
|
112
|
+
chain = ReceiptChain()
|
|
113
|
+
try:
|
|
114
|
+
if args.input:
|
|
115
|
+
if args.input.stat().st_size > 128 * 1024 * 1024:
|
|
116
|
+
raise ValueError("input exceeds 128 MiB")
|
|
117
|
+
envelope = json.loads(args.input.read_text(encoding="utf-8"))
|
|
118
|
+
if not isinstance(envelope, dict) or "provenance" not in envelope:
|
|
119
|
+
raise ValueError("input requires logits and provenance")
|
|
120
|
+
logits, origin = envelope.get("logits"), envelope["provenance"]
|
|
121
|
+
out = run_curve(logits, chain=chain, provenance=origin)
|
|
122
|
+
except (OSError, ValueError, TypeError) as exc:
|
|
123
|
+
out = {"state": "INVALID", "reason": str(exc)}
|
|
124
|
+
out["chain"] = chain.chain
|
|
125
|
+
out["chain_valid"] = chain.verify()
|
|
126
|
+
encoded = json.dumps(out, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
|
|
127
|
+
if args.output:
|
|
128
|
+
try:
|
|
129
|
+
with args.output.open("x", encoding="utf-8") as destination:
|
|
130
|
+
destination.write(encoded)
|
|
131
|
+
except OSError as exc:
|
|
132
|
+
parser.error(str(exc))
|
|
133
|
+
print(encoded, end="")
|
|
134
|
+
return 0 if out["state"] == "MEASURED" else 2
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
if __name__ == "__main__":
|
|
138
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Quality metrics between original and dequantized vectors/matrices."""
|
|
2
|
+
import math
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def mse(a, b):
|
|
6
|
+
return sum((x - y) ** 2 for x, y in zip(a, b)) / max(1, len(a))
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def cosine(a, b):
|
|
10
|
+
dot = sum(x * y for x, y in zip(a, b))
|
|
11
|
+
na = math.sqrt(sum(x * x for x in a)) or 1e-12
|
|
12
|
+
nb = math.sqrt(sum(y * y for y in b)) or 1e-12
|
|
13
|
+
return dot / (na * nb)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _softmax(row):
|
|
17
|
+
m = max(row)
|
|
18
|
+
e = [math.exp(x - m) for x in row]
|
|
19
|
+
s = sum(e)
|
|
20
|
+
return [x / s for x in e]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def kl_divergence(p_row, q_row):
|
|
24
|
+
"""KL(P || Q) over softmaxed rows. >= 0; 0 means identical distributions."""
|
|
25
|
+
if len(p_row) != len(q_row) or not p_row:
|
|
26
|
+
raise ValueError("KL rows must have equal nonzero length")
|
|
27
|
+
# Work in log space: clipping Q would silently cap large divergences.
|
|
28
|
+
pm, qm = max(p_row), max(q_row)
|
|
29
|
+
pz = math.log(sum(math.exp(x - pm) for x in p_row))
|
|
30
|
+
qz = math.log(sum(math.exp(x - qm) for x in q_row))
|
|
31
|
+
log_p = [x - pm - pz for x in p_row]
|
|
32
|
+
log_q = [x - qm - qz for x in q_row]
|
|
33
|
+
return max(0.0, sum(math.exp(p) * (p - q)
|
|
34
|
+
for p, q in zip(log_p, log_q) if math.exp(p) > 0))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def top1_agreement(rows_a, rows_b):
|
|
38
|
+
agree = sum(1 for a, b in zip(rows_a, rows_b)
|
|
39
|
+
if a.index(max(a)) == b.index(max(b)))
|
|
40
|
+
return agree / max(1, len(rows_a))
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Uniform symmetric quantization: quantize/dequantize with absmax scales.
|
|
2
|
+
|
|
3
|
+
Real integer quantization math, stdlib only. Per-tensor absmax scale,
|
|
4
|
+
round-to-nearest, signed integers at the requested bit width.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def quantize(values, bits):
|
|
9
|
+
"""values: flat list of floats. Returns (ints, scale). bits in 2..16."""
|
|
10
|
+
if type(bits) is not int or not 2 <= bits <= 16:
|
|
11
|
+
raise ValueError("bits must be in 2..16")
|
|
12
|
+
if not values:
|
|
13
|
+
return [], 1.0
|
|
14
|
+
qmax = (1 << (bits - 1)) - 1
|
|
15
|
+
absmax = max(abs(v) for v in values) or 1.0
|
|
16
|
+
scale = absmax / qmax
|
|
17
|
+
return [int(round(v / scale)) for v in values], scale
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def dequantize(ints, scale):
|
|
21
|
+
return [i * scale for i in ints]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Hash-chained run receipts. UNSIGNED_HONEST: proves integrity + order, not identity."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
GENESIS = "0" * 64
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _canonical(obj):
|
|
10
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
|
|
11
|
+
allow_nan=False)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ReceiptChain:
|
|
15
|
+
def __init__(self):
|
|
16
|
+
self.chain = []
|
|
17
|
+
|
|
18
|
+
def emit(self, record):
|
|
19
|
+
prev = self.chain[-1]["self_hash"] if self.chain else GENESIS
|
|
20
|
+
body = {"prev_hash": prev, "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
21
|
+
"signature": "UNSIGNED_HONEST", "run": json.loads(_canonical(record))}
|
|
22
|
+
body["self_hash"] = hashlib.sha256(_canonical(body).encode()).hexdigest()
|
|
23
|
+
self.chain.append(body)
|
|
24
|
+
return body
|
|
25
|
+
|
|
26
|
+
def verify(self):
|
|
27
|
+
prev = GENESIS
|
|
28
|
+
try:
|
|
29
|
+
for r in self.chain:
|
|
30
|
+
if not isinstance(r, dict) or r["prev_hash"] != prev:
|
|
31
|
+
return False
|
|
32
|
+
check = dict(r)
|
|
33
|
+
h = check.pop("self_hash")
|
|
34
|
+
if hashlib.sha256(_canonical(check).encode()).hexdigest() != h:
|
|
35
|
+
return False
|
|
36
|
+
prev = h
|
|
37
|
+
except (KeyError, TypeError, ValueError):
|
|
38
|
+
return False
|
|
39
|
+
return bool(self.chain)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: szl-quant-bench
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Honest quantization quality-curve bench: cosine/KL/top-1 degradation vs bit-width, hash-chained receipts. Fail closed.
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# szl-quant-bench
|
|
12
|
+
|
|
13
|
+
Honest quantization quality-curve bench for the SZL estate. Real uniform
|
|
14
|
+
absmax quantization (round-to-nearest, signed ints, 2–16 bits) with quality
|
|
15
|
+
metrics — cosine similarity, KL divergence over softmaxed rows, top-1
|
|
16
|
+
agreement, MSE — on the supplied logits. This measures logit quantization,
|
|
17
|
+
not weight quantization, GGUF behavior, inference speed, or model quality
|
|
18
|
+
after a weight conversion. Stdlib only; no downloads, no network.
|
|
19
|
+
|
|
20
|
+
Doctrine: empty or missing inputs return `BLOCKED` with a reason. The demo
|
|
21
|
+
fixture is synthetic and labeled as such. Nothing here claims to measure a
|
|
22
|
+
real model unless you pass real logits in. Run states:
|
|
23
|
+
`MEASURED | BLOCKED | INVALID | FAILED`.
|
|
24
|
+
|
|
25
|
+
## Install and verify
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
pip install -e . pytest
|
|
29
|
+
python -m pytest tests/ -q
|
|
30
|
+
python -m szl_quant_bench.harness # deterministic fixture curve + receipt
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Measured fixture curve (synthetic gaussian logits, seed 42 — NOT a real model)
|
|
34
|
+
|
|
35
|
+
| bits | cosine | KL (mean) | top-1 agreement | vs fp32 |
|
|
36
|
+
|---|---|---|---|---|
|
|
37
|
+
| 16 | 1.0000 | 0.00000 | 100.0% | 2.0x |
|
|
38
|
+
| 8 | 1.0000 | 0.00003 | 100.0% | 4.0x |
|
|
39
|
+
| 4 | 0.9882 | 0.01211 | 68.8% | 8.0x |
|
|
40
|
+
| 3 | 0.9420 | 0.06556 | 56.2% | 10.67x |
|
|
41
|
+
| 2 | 0.5715 | 0.57019 | 50.0% | 16.0x |
|
|
42
|
+
|
|
43
|
+
These numbers came out of `run_curve` in this repository, executed before the
|
|
44
|
+
initial push. Your model's curve will differ — run it on real logits.
|
|
45
|
+
|
|
46
|
+
## Measuring a real model
|
|
47
|
+
|
|
48
|
+
Capture a logit batch from the exact model revision and fixed evaluation
|
|
49
|
+
prompt set. Store a JSON object with `logits` (a rectangular finite numeric
|
|
50
|
+
matrix) and `provenance` containing:
|
|
51
|
+
|
|
52
|
+
- `source_kind`: `REAL_MODEL_LOGITS`
|
|
53
|
+
- `model_id`, `runtime`, `hardware`: nonempty identifiers
|
|
54
|
+
- `model_revision`: the exact 40-character lowercase commit
|
|
55
|
+
- `prompt_set_sha256`: the full lowercase SHA-256 of the saved prompt artifact
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
python -m szl_quant_bench.harness --input model-logits.json --output curve-receipt.json
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The output file must not already exist. Missing provenance, malformed matrices,
|
|
62
|
+
non-finite values and invalid bit widths fail closed with a nonzero exit.
|
|
63
|
+
With no input the CLI runs only the explicitly `SYNTHETIC` fixture.
|
|
64
|
+
The Python API accepts `run_curve(logits, chain=chain, provenance=provenance)`;
|
|
65
|
+
omitting provenance labels the source `UNVERIFIED_CALLER_INPUT`. Every
|
|
66
|
+
`MEASURED` API result carries a hash-chained receipt record. If no chain is
|
|
67
|
+
supplied, the API creates a fresh one-record chain for that measurement; pass
|
|
68
|
+
a caller-owned `ReceiptChain` to append the record to an existing chain.
|
|
69
|
+
|
|
70
|
+
Receipts bind the normalized float input matrix hash, complete provenance,
|
|
71
|
+
all quality records and the explicit measurement boundary. Provenance remains
|
|
72
|
+
`CALLER_DECLARED`: a hash cannot establish that the caller actually ran a model.
|
|
73
|
+
Preserve the raw logits and independent model execution evidence to support
|
|
74
|
+
that claim. Empty or malformed chains do not verify. KL is evaluated in log
|
|
75
|
+
space without silently clipping small probabilities.
|
|
76
|
+
|
|
77
|
+
Compare bit widths only on the same inputs, hardware and revision. A measured
|
|
78
|
+
logit curve does **not** authorize a GGUF export decision: actual quantized
|
|
79
|
+
model outputs and runtime evaluation are separately required.
|
|
80
|
+
|
|
81
|
+
Apache-2.0 · Doctrine v11 · SZL Holdings
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/szl_quant_bench/__init__.py
|
|
5
|
+
src/szl_quant_bench/harness.py
|
|
6
|
+
src/szl_quant_bench/metrics.py
|
|
7
|
+
src/szl_quant_bench/quant.py
|
|
8
|
+
src/szl_quant_bench/receipts.py
|
|
9
|
+
src/szl_quant_bench.egg-info/PKG-INFO
|
|
10
|
+
src/szl_quant_bench.egg-info/SOURCES.txt
|
|
11
|
+
src/szl_quant_bench.egg-info/dependency_links.txt
|
|
12
|
+
src/szl_quant_bench.egg-info/top_level.txt
|
|
13
|
+
tests/test_provenance.py
|
|
14
|
+
tests/test_quant_bench.py
|
|
15
|
+
tests/test_receipt_required.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
szl_quant_bench
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import json
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from szl_quant_bench.harness import run_curve
|
|
9
|
+
from szl_quant_bench.metrics import kl_divergence
|
|
10
|
+
from szl_quant_bench.quant import quantize
|
|
11
|
+
from szl_quant_bench.receipts import ReceiptChain
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.mark.parametrize("logits", ["bad", [1], [[1], [2, 3]],
|
|
15
|
+
[[True]], [[float("nan")]],
|
|
16
|
+
[[float("inf")]], [["1"]],
|
|
17
|
+
[[1e308, -1e308]]])
|
|
18
|
+
def test_invalid_matrix_never_emits_receipt(logits):
|
|
19
|
+
chain = ReceiptChain()
|
|
20
|
+
assert run_curve(logits, chain=chain)["state"] == "INVALID"
|
|
21
|
+
assert chain.chain == []
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@pytest.mark.parametrize("logits", [None, [], [[]], [[], []], ((), ())])
|
|
25
|
+
def test_missing_or_wholly_empty_logits_are_blocked(logits):
|
|
26
|
+
chain = ReceiptChain()
|
|
27
|
+
assert run_curve(logits, chain=chain)["state"] == "BLOCKED"
|
|
28
|
+
assert chain.chain == []
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@pytest.mark.parametrize("bits", [[], [True], [4.0], [1], [17], [4, 4], "4"])
|
|
32
|
+
def test_invalid_bits_never_emit_receipt(bits):
|
|
33
|
+
chain = ReceiptChain()
|
|
34
|
+
assert run_curve([[1.0, 2.0]], bits=bits, chain=chain)["state"] == "INVALID"
|
|
35
|
+
assert chain.chain == []
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_provenance_and_input_are_bound_to_receipt():
|
|
39
|
+
provenance = {
|
|
40
|
+
"source_kind": "REAL_MODEL_LOGITS", "model_id": "owner/model",
|
|
41
|
+
"model_revision": "a" * 40, "prompt_set_sha256": "b" * 64,
|
|
42
|
+
"runtime": "test-runtime", "hardware": "test-host",
|
|
43
|
+
}
|
|
44
|
+
logits = [[1.0, 2.0], [3.0, 4.0]]
|
|
45
|
+
chain = ReceiptChain()
|
|
46
|
+
out = run_curve(logits, chain=chain, provenance=provenance)
|
|
47
|
+
assert out["state"] == "MEASURED"
|
|
48
|
+
canonical = json.dumps(logits, sort_keys=True, separators=(",", ":"),
|
|
49
|
+
ensure_ascii=False, allow_nan=False)
|
|
50
|
+
assert out["input_sha256"] == hashlib.sha256(canonical.encode()).hexdigest()
|
|
51
|
+
assert out["provenance_authority"] == "CALLER_DECLARED"
|
|
52
|
+
assert out["weight_quantization_measured"] is False
|
|
53
|
+
assert out["gguf_export_authorized"] is False
|
|
54
|
+
provenance["model_id"] = "mutated"
|
|
55
|
+
out["curve"][0]["mse"] = 999
|
|
56
|
+
out["provenance"]["model_id"] = "mutated-too"
|
|
57
|
+
assert chain.verify()
|
|
58
|
+
chain.chain[0]["run"]["input_sha256"] = "0" * 64
|
|
59
|
+
assert not chain.verify()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_missing_real_provenance_is_rejected():
|
|
63
|
+
out = run_curve([[1.0]], provenance={"source_kind": "REAL_MODEL_LOGITS"})
|
|
64
|
+
assert out["state"] == "INVALID"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_unverified_caller_is_not_labeled_real():
|
|
68
|
+
assert run_curve([[1.0]])["provenance"]["source_kind"] == "UNVERIFIED_CALLER_INPUT"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_kl_does_not_clip_large_divergence():
|
|
72
|
+
assert kl_divergence([1000, 0], [0, 1000]) == pytest.approx(1000)
|
|
73
|
+
with pytest.raises(ValueError):
|
|
74
|
+
kl_divergence([1], [1, 2])
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@pytest.mark.parametrize("bits", [True, 4.0, "4"])
|
|
78
|
+
def test_quantize_rejects_noninteger_bits(bits):
|
|
79
|
+
with pytest.raises(ValueError):
|
|
80
|
+
quantize([1.0], bits)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_empty_and_malformed_chains_fail_closed():
|
|
84
|
+
chain = ReceiptChain()
|
|
85
|
+
assert not chain.verify()
|
|
86
|
+
for malformed in ([{}], [None], [{"prev_hash": "0" * 64}]):
|
|
87
|
+
chain.chain = malformed
|
|
88
|
+
assert not chain.verify()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_cli_labels_fixture_and_does_not_overwrite(tmp_path):
|
|
92
|
+
destination = tmp_path / "receipt.json"
|
|
93
|
+
command = [sys.executable, "-B", "-m", "szl_quant_bench.harness",
|
|
94
|
+
"--output", str(destination)]
|
|
95
|
+
first = subprocess.run(command, capture_output=True, text=True, check=True)
|
|
96
|
+
result = json.loads(first.stdout)
|
|
97
|
+
assert result["chain_valid"] is True
|
|
98
|
+
assert result["provenance"]["source_kind"] == "SYNTHETIC"
|
|
99
|
+
before = destination.read_bytes()
|
|
100
|
+
second = subprocess.run(command, capture_output=True, text=True)
|
|
101
|
+
assert second.returncode != 0
|
|
102
|
+
assert destination.read_bytes() == before
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_cli_invalid_input_has_nonzero_exit_and_no_receipt(tmp_path):
|
|
106
|
+
source = tmp_path / "input.json"
|
|
107
|
+
source.write_text(json.dumps({"logits": [[True]],
|
|
108
|
+
"provenance": {"source_kind": "SYNTHETIC"}}))
|
|
109
|
+
result = subprocess.run([sys.executable, "-B", "-m", "szl_quant_bench.harness",
|
|
110
|
+
"--input", str(source)], capture_output=True, text=True)
|
|
111
|
+
assert result.returncode == 2
|
|
112
|
+
body = json.loads(result.stdout)
|
|
113
|
+
assert body["state"] == "INVALID"
|
|
114
|
+
assert body["chain"] == []
|
|
115
|
+
assert body["chain_valid"] is False
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from szl_quant_bench.harness import run_curve
|
|
6
|
+
from szl_quant_bench.metrics import cosine, kl_divergence, top1_agreement
|
|
7
|
+
from szl_quant_bench.quant import dequantize, quantize
|
|
8
|
+
from szl_quant_bench.receipts import ReceiptChain
|
|
9
|
+
from random import Random
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def logits_fixture():
|
|
13
|
+
rng = Random(42)
|
|
14
|
+
return [[rng.gauss(0, 1) for _ in range(64)] for _ in range(16)]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_roundtrip_16bit_near_exact():
|
|
18
|
+
vals = [0.1, -0.5, 3.7, 0.0, -2.2]
|
|
19
|
+
ints, scale = quantize(vals, 16)
|
|
20
|
+
deq = dequantize(ints, scale)
|
|
21
|
+
for a, b in zip(vals, deq):
|
|
22
|
+
assert abs(a - b) < 1e-3
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_2bit_coarser_than_8bit():
|
|
26
|
+
vals = [i * 0.01 for i in range(-50, 50)]
|
|
27
|
+
ints2, s2 = quantize(vals, 2)
|
|
28
|
+
ints8, s8 = quantize(vals, 8)
|
|
29
|
+
assert len(set(ints2)) <= 4
|
|
30
|
+
assert len(set(ints8)) > 50
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_quantize_rejects_bad_bits():
|
|
34
|
+
with pytest.raises(ValueError):
|
|
35
|
+
quantize([1.0], 1)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_kl_nonnegative_and_zero_when_identical():
|
|
39
|
+
row = [0.1, 0.9, -0.4, 2.0]
|
|
40
|
+
assert kl_divergence(row, row) == pytest.approx(0.0, abs=1e-9)
|
|
41
|
+
assert kl_divergence(row, [2.0, -0.4, 0.9, 0.1]) > 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_top1_agreement_perfect_when_identical():
|
|
45
|
+
rows = [[1, 2, 3], [3, 2, 1]]
|
|
46
|
+
assert top1_agreement(rows, rows) == 1.0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_curve_measured_and_quality_drops_at_low_bits():
|
|
50
|
+
out = run_curve(logits_fixture())
|
|
51
|
+
assert out["state"] == "MEASURED"
|
|
52
|
+
curve = {r["bits"]: r for r in out["curve"]}
|
|
53
|
+
assert curve[16]["cosine"] > 0.999
|
|
54
|
+
assert curve[16]["top1_agreement"] == 1.0
|
|
55
|
+
assert curve[2]["cosine"] < curve[8]["cosine"]
|
|
56
|
+
assert curve[2]["kl_mean"] > curve[8]["kl_mean"]
|
|
57
|
+
assert curve[4]["compression_vs_fp32"] == 8.0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_curve_blocked_on_empty():
|
|
61
|
+
assert run_curve([])["state"] == "BLOCKED"
|
|
62
|
+
assert run_curve([[]])["state"] == "BLOCKED"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_curve_receipt_chain_verifies():
|
|
66
|
+
chain = ReceiptChain()
|
|
67
|
+
out = run_curve(logits_fixture(), chain=chain)
|
|
68
|
+
assert "receipt" in out and chain.verify()
|
|
69
|
+
chain.chain[0]["run"]["curve"][0]["cosine"] = 0.0
|
|
70
|
+
assert not chain.verify()
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from szl_quant_bench.harness import run_curve
|
|
2
|
+
from szl_quant_bench.receipts import ReceiptChain
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def test_every_measured_api_result_carries_a_verifiable_receipt():
|
|
6
|
+
out = run_curve([[1.0, 2.0]], provenance={"source_kind": "SYNTHETIC"})
|
|
7
|
+
assert out["state"] == "MEASURED"
|
|
8
|
+
receipt = out["receipt"]
|
|
9
|
+
assert receipt["prev_hash"] == "0" * 64
|
|
10
|
+
chain = ReceiptChain()
|
|
11
|
+
chain.chain = [receipt]
|
|
12
|
+
assert chain.verify()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_caller_chain_still_receives_the_measured_record():
|
|
16
|
+
chain = ReceiptChain()
|
|
17
|
+
out = run_curve([[1.0, 2.0]], chain=chain,
|
|
18
|
+
provenance={"source_kind": "SYNTHETIC"})
|
|
19
|
+
assert out["receipt"] is chain.chain[-1]
|
|
20
|
+
assert chain.verify()
|