kestrom-verify 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.
@@ -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,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: kestrom-verify
3
+ Version: 0.1.0
4
+ Summary: Check a language-model weight edit: what changed, byte for byte, and that outputs outside the declared range stayed bit-identical
5
+ Author: CAPH TECH Inc.
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/CAPHTECH/kestrom
8
+ Project-URL: Repository, https://github.com/CAPHTECH/kestrom
9
+ Project-URL: Issues, https://github.com/CAPHTECH/kestrom/issues
10
+ Keywords: llm,verification,ai-security,model-audit,safetensors,gguf
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Security
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: numpy
24
+ Provides-Extra: mlx
25
+ Requires-Dist: mlx; extra == "mlx"
26
+ Requires-Dist: mlx-lm; extra == "mlx"
27
+ Requires-Dist: transformers; extra == "mlx"
28
+ Provides-Extra: gguf
29
+ Requires-Dist: gguf; extra == "gguf"
30
+ Requires-Dist: transformers; extra == "gguf"
31
+ Provides-Extra: torch
32
+ Requires-Dist: torch; extra == "torch"
33
+ Requires-Dist: transformers>=5; extra == "torch"
34
+ Requires-Dist: safetensors; extra == "torch"
35
+ Dynamic: license-file
36
+
37
+ # kestrom-verify
38
+
39
+ The checker of [Kestrom](https://github.com/CAPHTECH/kestrom): compares an edited language model with its original,
40
+ byte for byte and output for output, and writes a report that rebuilds to the same bytes. Apache-2.0.
41
+
42
+ `kestrom-verify` with no arguments lists the commands. Every check and what it does not guarantee: `docs/guarantees.md` in the
43
+ repository.
@@ -0,0 +1,7 @@
1
+ # kestrom-verify
2
+
3
+ The checker of [Kestrom](https://github.com/CAPHTECH/kestrom): compares an edited language model with its original,
4
+ byte for byte and output for output, and writes a report that rebuilds to the same bytes. Apache-2.0.
5
+
6
+ `kestrom-verify` with no arguments lists the commands. Every check and what it does not guarantee: `docs/guarantees.md` in the
7
+ repository.
@@ -0,0 +1,14 @@
1
+ import inspect
2
+
3
+ HELP = {"-h", "--help"}
4
+
5
+
6
+ def call(f, args, help):
7
+ """f(*args); or the help printed (exit status 1) when ARGS ask for it (-h, --help) or do not fit f's parameters."""
8
+ try:
9
+ if HELP & set(args):
10
+ raise TypeError
11
+ inspect.signature(f).bind(*args)
12
+ except TypeError:
13
+ raise SystemExit(help) from None
14
+ return f(*args)
@@ -0,0 +1,85 @@
1
+ """kestrom-verify: check a weight edit on your own machine. Every command but generate and summary writes a JSON report with no
2
+ times in it (the same inputs give the same bytes), prints each check as `name: count of total PASS|FAIL`, and exits with status 1
3
+ if one fails. logits when W fails, and compare when its range report did not pass or PROMPTS.json does not fit the range or the
4
+ outputs, stop first, with no report.
5
+ range ORIGINAL EDITED REPORT.json the range of a row edit, read from the bytes: the changed rows of the
6
+ output layer, and every other byte the same (W). Folders of
7
+ safetensors, or GGUF files. With no output layer tensor, the output
8
+ layer is tied to the embedding (in a folder, config.json must say
9
+ so, else it stops): then G1 and G2 check only the sequences and
10
+ prompts that hold no changed id, and count the others
11
+ logits RUNTIME ORIGINAL EDITED INPUTS.json REPORT.json teacher forcing: the original equal to itself (U0), every logit of an
12
+ unchanged row equal to the original's at every position (G1)
13
+ generate RUNTIME MODEL PROMPTS.json OUT.jsonl [MAX_TOKENS]
14
+ greedy decoding (512 tokens unless given)
15
+ generate gguf MODEL.gguf PROMPTS.json TOKENIZER OUT.jsonl
16
+ greedy decoding with llama-server (TOKENIZER: a Hugging Face folder)
17
+ generate server URL MODEL PROMPTS.json TOKENIZER OUT.jsonl [MAX_TOKENS]
18
+ greedy decoding on a running OpenAI-compatible chat server (mlx-serve,
19
+ vLLM, ...): PROMPTS.json {"id", "messages", "body": request fields};
20
+ the tokens from each logprob's bytes (a byte-level BPE vocabulary)
21
+ compare RANGE.json ORIGINAL.jsonl ORIGINAL2.jsonl EDITED.jsonl TOKENIZER REPORT.json [PROMPTS.json]
22
+ greedy outputs against the range: the original twice the same (U0),
23
+ the edited output the same or first different inside the range (G2).
24
+ RANGE.json "events": the events each edited output records (an
25
+ inference-time edit, as kestrom generate writes them). PROMPTS.json,
26
+ the prompts of the outputs: for a range tied to the embedding only
27
+ measure RUNTIME ORIGINAL EDITED INPUTS.json REPORT.json [ORIGINAL.jsonl ORIGINAL2.jsonl EDITED.jsonl]
28
+ an edit with no guarantee: how much changed (each model whole)
29
+ diff ORIGINAL EDITED REPORT.json [DECLARED.json] every tensor compared byte for byte; with a declaration, whether every
30
+ change lies inside it (D). No guarantee on the outputs
31
+ summary REPORT.json the report in markdown
32
+ RUNTIME: mlx (MLX, Apple Silicon) or torch (PyTorch with transformers: CUDA, else MPS, else the CPU), on a folder of safetensors.
33
+ Compare the original and the edited model on the same runtime and machine."""
34
+ import sys
35
+ from functools import partial
36
+
37
+ from . import call, report, weights
38
+
39
+
40
+ def runtime(kind):
41
+ """The module of a RUNTIME: mlx or torch."""
42
+ import importlib
43
+ if kind not in ("mlx", "torch"):
44
+ raise SystemExit(f"RUNTIME is mlx or torch, not {kind!r}")
45
+ return importlib.import_module({"mlx": ".mlx", "torch": ".pt"}[kind], __package__)
46
+
47
+
48
+ def generate(kind, *args):
49
+ from . import llama, server
50
+ call({"gguf": llama.gen, "server": server.gen}.get(kind) or runtime(kind).gen, args, __doc__)
51
+
52
+
53
+ def compare(range_file, a, a2, e, tokenizer, out, prompts=None):
54
+ from transformers import AutoTokenizer
55
+ report.greedy(range_file, (a, a2, e), AutoTokenizer.from_pretrained(tokenizer).decode, out, prompts)
56
+
57
+
58
+ def logits(kind, *args):
59
+ from . import forward
60
+ call(partial(forward.forced, runtime(kind)), args, __doc__)
61
+
62
+
63
+ def measure(kind, *args):
64
+ from . import forward
65
+ call(partial(forward.measure, runtime(kind)), args, __doc__)
66
+
67
+
68
+ def diff(*args):
69
+ from . import diff as d
70
+ call(d.main, args, __doc__)
71
+
72
+
73
+ COMMANDS = {"range": lambda a, b, out: report.finish(out, weights.diff(a, b)), "logits": logits, "generate": generate, "compare": compare,
74
+ "measure": measure, "diff": diff, "summary": lambda path: print(report.summary(path), end="")}
75
+
76
+
77
+ def main():
78
+ cmd, *args = sys.argv[1:] or [None]
79
+ if cmd not in COMMANDS:
80
+ raise SystemExit(__doc__)
81
+ call(COMMANDS[cmd], args, __doc__)
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
@@ -0,0 +1,142 @@
1
+ """Every tensor of two models compared byte for byte, read from the weights and not from what the editor says: which tensors changed,
2
+ and in each which rows (the first axis) and how many elements. With a declaration, whether the change lies inside what was declared.
3
+ No guarantee on the outputs: a changed tensor inside the network can move the output at every position (only a change limited to
4
+ rows of the output layer bounds the outputs, see rows and forced). This is the check that the delivered model is the original with the
5
+ declared change and nothing else (sparse fine-tuning, a merged adapter, some layers retrained, a row edit).
6
+ Usage: kestrom-verify diff ORIGINAL EDITED REPORT.json [DECLARED.json]
7
+ ORIGINAL, EDITED: a folder of safetensors (tensors paired by name across the shards) or one GGUF file.
8
+ DECLARED: {"name": "all" | [[first row, end row], ...]}, a name a tensor or another file of the folder (config.json, ...) or
9
+ "__metadata__" (the safetensors metadata, or every key-value field of a GGUF file: tokenizer, special tokens, ...). D is PASS when
10
+ every changed row, tensor and file is inside it; a tensor added, removed or of another dtype or shape, a changed file and changed
11
+ metadata are inside only a declaration "all"."""
12
+ import hashlib
13
+ import json
14
+ import sys
15
+ from math import prod
16
+ from pathlib import Path
17
+
18
+ from . import report
19
+ from .weights import files, hashes, header, named
20
+
21
+ CHUNK = 1 << 28 # bytes of a tensor compared at a time
22
+
23
+
24
+ def tensors(path):
25
+ """({name: (file, first byte, end byte, dtype, shape)}, {file name: metadata}): for safetensors the __metadata__ of each shard,
26
+ for GGUF the SHA-256 of each key-value field's bytes (its key, type and value)."""
27
+ path = Path(path)
28
+ if path.is_dir():
29
+ out, meta = {}, {}
30
+ for f in sorted(path.glob("*.safetensors")):
31
+ n, h = header(f)
32
+ meta[f.name] = h.pop("__metadata__", None)
33
+ for k, v in h.items():
34
+ out[k] = (f, 8 + n + v["data_offsets"][0], 8 + n + v["data_offsets"][1], v["dtype"], v["shape"])
35
+ return out, meta
36
+ import gguf
37
+ r = gguf.GGUFReader(path)
38
+ return ({t.name: (path, t.data_offset, t.data_offset + t.n_bytes, t.tensor_type.name, [int(x) for x in reversed(t.shape)]) # the
39
+ for t in r.tensors}, # logical shape, rows first (GGUF lists the dimensions innermost first)
40
+ {"gguf": {k: hashlib.sha256(b"".join(bytes(x) for x in f.parts)).hexdigest() for k, f in r.fields.items()}})
41
+
42
+
43
+ def metadata(meta):
44
+ """The distinct metadata of the shards (a resharded copy carries the same metadata in each shard)."""
45
+ return {json.dumps(m, sort_keys=True) for m in meta.values() if m}
46
+
47
+
48
+ def spans(rows):
49
+ """Sorted row numbers as [[first, end], ...]."""
50
+ out = []
51
+ for r in rows:
52
+ if out and out[-1][1] == r:
53
+ out[-1][1] = r + 1
54
+ else:
55
+ out.append([r, r + 1])
56
+ return out
57
+
58
+
59
+ def compare(a, b):
60
+ """The changed rows (spans) and changed elements (None when the storage has no whole element per byte group, as a quantized
61
+ GGUF block) of two tensors of the same dtype and shape."""
62
+ import numpy as np
63
+ (fa, sa, ea, _, shape), (fb, sb, _, _, _) = a, b
64
+ n = ea - sa
65
+ if n == 0:
66
+ return [], 0
67
+ rows = shape[0] if shape else 1
68
+ width = n // rows
69
+ item = n // prod(shape) if prod(shape) and n % prod(shape) == 0 else None
70
+ x = np.memmap(fa, np.uint8, "r", offset=sa, shape=(n,)).reshape(rows, width)
71
+ y = np.memmap(fb, np.uint8, "r", offset=sb, shape=(n,)).reshape(rows, width)
72
+ changed, elements, step = [], 0, max(1, CHUNK // width)
73
+ for i in range(0, rows, step):
74
+ d = x[i:i + step] != y[i:i + step]
75
+ changed += (np.flatnonzero(d.any(1)) + i).tolist()
76
+ if item:
77
+ elements += int(d.reshape(d.shape[0], -1, item).any(2).sum())
78
+ return spans(changed), elements if item else None
79
+
80
+
81
+ def inside(change, declared):
82
+ """A changed tensor inside its declaration: "all" holds every change, spans hold changed values whose rows all lie in them."""
83
+ return declared == "all" or change["change"] == "values" and all(any(p <= s and e <= q for p, q in declared) for s, e in change["changed rows"])
84
+
85
+
86
+ def diff(original, edited, declared=None):
87
+ ta, ma = tensors(original)
88
+ tb, mb = tensors(edited)
89
+ fa, fb = files(original), files(edited)
90
+ ha, hb = hashes(fa), hashes(fb)
91
+ changed = {}
92
+ for name in sorted(set(ta) | set(tb)):
93
+ a, b = ta.get(name), tb.get(name)
94
+ if a is None or b is None or a[3:] != b[3:]:
95
+ changed[name] = {"change": "added" if a is None else "removed" if b is None else "dtype or shape",
96
+ "original": a and {"dtype": a[3], "shape": a[4]}, "edited": b and {"dtype": b[3], "shape": b[4]}}
97
+ continue
98
+ rows, elements = compare(a, b)
99
+ if rows:
100
+ changed[name] = {"change": "values", "dtype": a[3], "shape": a[4], "rows": a[4][0] if a[4] else 1,
101
+ "changed rows": rows, "changed row count": sum(e - s for s, e in rows),
102
+ "elements": prod(a[4]), "changed elements": elements}
103
+ weights = {k for f in (fa, fb) for k, p in f.items() if "/" not in k and p.suffix in (".safetensors", ".gguf")} # read as tensors
104
+ others = {n: "added" if n not in ha else "removed" if n not in hb else "changed"
105
+ for n in sorted((set(ha) | set(hb)) - weights) if ha.get(n) != hb.get(n)}
106
+ if metadata(ma) != metadata(mb):
107
+ others["__metadata__"] = "changed"
108
+ totals = {"tensors": len(set(ta) | set(tb)), "tensors the same": len(set(ta) | set(tb)) - len(changed), "tensors changed": len(changed),
109
+ "elements": sum(prod(t[4]) for t in ta.values()),
110
+ "changed elements": sum(c.get("changed elements") or 0 for c in changed.values()),
111
+ "tensors changed with no element count": sum(c["change"] == "values" and c["changed elements"] is None for c in changed.values()),
112
+ "other files changed": len(others)}
113
+ out = {"original": named(fa, ha), "edited": named(fb, hb), "diff": totals, "tensors": changed, "files": others}
114
+ if declared is not None:
115
+ within = [n for n, c in changed.items() if n in declared and inside(c, declared[n])]
116
+ within += [n for n in others if declared.get(n) == "all"]
117
+ out["declared"] = {"declaration": declared, "changes": len(changed) + len(others), "inside": len(within),
118
+ "outside": sorted((set(changed) | set(others)) - set(within))}
119
+ return out
120
+
121
+
122
+ def declared_diff(original, edited, declared_file=None):
123
+ """diff(...) against the declaration read from DECLARED_FILE, which the report names by its SHA-256."""
124
+ r = diff(original, edited, report.read(declared_file) if declared_file else None)
125
+ if declared_file:
126
+ r["declaration file"] = {Path(declared_file).name: report.sha(declared_file)}
127
+ return r
128
+
129
+
130
+ def main(original, edited, out, declared_file=None):
131
+ r = declared_diff(original, edited, declared_file)
132
+ t = r["diff"]
133
+ print("tensors changed", t["tensors changed"], "of", t["tensors"], "| elements changed", t["changed elements"], "of", t["elements"],
134
+ f"(and {t['tensors changed with no element count']} quantized tensors changed, counted in rows only)" if t["tensors changed with no element count"] else "",
135
+ "| other files changed", t["other files changed"], flush=True)
136
+ if r.get("declared", {}).get("outside"):
137
+ print("outside the declaration:", r["declared"]["outside"][:20], flush=True)
138
+ report.finish(out, r)
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main(*sys.argv[1:])
@@ -0,0 +1,118 @@
1
+ """Teacher forcing on a runtime (kestrom_verify.mlx or kestrom_verify.pt): forced, a row edit of the output layer (U0 and G1), and
2
+ measure, an edit with no guarantee. A runtime gives load(folder) -> model, logits(model, ids) -> (the logits' bits as unsigned
3
+ integers, one row per position; their type: bfloat16, float16 or float32), and output_layers(model, edited, file, key, tied) ->
4
+ (use the original output layer, use the edited folder's). The comparisons here are numpy, the same for every runtime."""
5
+ import hashlib
6
+ from pathlib import Path
7
+
8
+ from . import report, weights
9
+
10
+
11
+ def values(bits, kind):
12
+ """The logits as float32, exactly, from their bits."""
13
+ import numpy as np
14
+ if kind == "bfloat16":
15
+ return (bits.astype(np.uint32) << 16).view(np.float32)
16
+ return bits.view({"float16": np.float16, "float32": np.float32}[kind]).astype(np.float32)
17
+
18
+
19
+ def forced(rt, original, edited, inputs, out):
20
+ """Teacher forcing on every sequence of inputs (a JSON list of {"ids": prompt ids, "tokens": answer ids, other keys kept}), at
21
+ every position, with the original output layer twice and the edited once: the original equal to itself (U0), every logit of an
22
+ unchanged row equal to the original's (G1). Reported only: the positions whose original top token's row changed; at the
23
+ positions that predict the answer, those whose edited top token's row changed and the highest logit of a changed row there. An
24
+ output layer tied to the embedding is read from the edited folder as the embedding too: G1 checks only the sequences whose ids and
25
+ tokens hold no changed id, and counts the others (sequences_outside). The edited model is the original with its output layer
26
+ read from the edited folder, so this stops unless weights.diff finds every other byte the same."""
27
+ import numpy as np
28
+ r = weights.diff(original, edited)
29
+ w = r["weights"]
30
+ if w["files equal but for the changed rows"] != w["files"]: # the forward below reads only the output layer of the edited folder
31
+ raise SystemExit("other bytes than the output layer's rows differ: G1 here would be about another model; use kestrom-verify measure (no guarantee)")
32
+ if len(weights.parts(original)) > 1: # the runtimes swap one tensor; a quantized layer's scales and biases would stay the original's
33
+ raise SystemExit("the output layer is several tensors (quantized): logits reads one; check it with compare")
34
+ changed = w["changed rows"]
35
+ file, _, _, n, key = weights.output(original)
36
+ tied = weights.tied(key) # then the changed rows are also input embeddings: a sequence holding a changed id is not checked
37
+ model = rt.load(original)
38
+ use_original, use_edited = rt.output_layers(model, edited, file, key, tied)
39
+ keep = np.ones(n, bool)
40
+ keep[changed] = False
41
+ keys = ("positions", "original_equal", "other_equal", "positions_other_equal", "positions_top_changed", "answer_positions", "answer_edited_top_changed")
42
+ rows, totals, high = [], dict(sequences=0, **{k: 0 for k in keys}, **({"sequences_outside": 0} if tied else {})), -float("inf")
43
+ for x in report.read(inputs):
44
+ outside = tied and bool(set(x["ids"] + x["tokens"]) & set(changed))
45
+ ids = x["ids"] + x["tokens"]
46
+ use_original()
47
+ (a, kind), (b, _) = rt.logits(model, ids), rt.logits(model, ids)
48
+ use_edited()
49
+ e, _ = rt.logits(model, ids)
50
+ eq = ((a == e) | ~keep).all(1)
51
+ top_changed = ~keep[values(a, kind).argmax(1)]
52
+ answer = values(e, kind)[-len(x["tokens"]) - 1:] # the positions that predict each answer token and what follows the last
53
+ edited_changed = ~keep[answer.argmax(1)]
54
+ changed_max = float(answer[:, changed].max())
55
+ high = max(high, changed_max)
56
+ row = dict({k: v for k, v in x.items() if k not in ("ids", "tokens")}, positions=a.shape[0], original_equal=bool(np.array_equal(a, b)),
57
+ other_equal=bool(eq.all()), positions_other_equal=int(eq.sum()), positions_top_changed=int(top_changed.sum()),
58
+ answer_positions=answer.shape[0], answer_edited_top_changed=int(edited_changed.sum()), answer_max_changed=changed_max,
59
+ **({"changed_id_in_input": outside} if tied else {}))
60
+ rows.append(row)
61
+ totals["sequences"] += 1
62
+ for k in keys:
63
+ totals[k] += int(row[k]) * (k != "other_equal" or not outside) # G1 counts only the sequences it checks
64
+ if outside:
65
+ totals["sequences_outside"] += 1
66
+ if totals["sequences"] % 50 == 0:
67
+ print(totals, flush=True)
68
+ use_original()
69
+ totals["answer_max_changed_logit"] = high
70
+ report.finish(out, dict(r, inputs={Path(inputs).name: report.sha(inputs)}, forced=totals, rows=rows))
71
+
72
+
73
+ def digests(rt, model_dir, data, twice=False, at=None):
74
+ """Per sequence of data and per position: the SHA-256 of the logits' bytes, the top token, and the logit at the top token, or at
75
+ the tokens of at (per sequence, the top tokens of another model). One model loaded at a time, so two 9B models need not fit
76
+ together. twice: the same again, to check the model equal to itself."""
77
+ import numpy as np
78
+ model = rt.load(model_dir)
79
+ out = []
80
+ for i, x in enumerate(data):
81
+ runs = []
82
+ for _ in range(2 if twice else 1):
83
+ raw, kind = rt.logits(model, x["ids"] + x["tokens"])
84
+ v = values(raw, kind)
85
+ top = v.argmax(1)
86
+ runs.append(([hashlib.sha256(r.tobytes()).digest() for r in raw], top.tolist(), v[np.arange(len(v)), top if at is None else at[i]]))
87
+ out.append(runs)
88
+ del model
89
+ return out
90
+
91
+
92
+ def measure(rt, original, edited, inputs, out, *greedy_files):
93
+ """An edit with no guarantee (other bytes than output-layer rows may differ): teacher forcing on every sequence of inputs with the
94
+ original twice (U0, the only check) and the edited once, each model loaded whole. Reported only, how much changed: the positions
95
+ whose logits are all equal (same bytes), whose top token changed, and the highest absolute change of the logit of the original's
96
+ top token. greedy_files: the greedy outputs (JSONL) of the original, the original again and the edited, for the prompts the same
97
+ and the original twice the same."""
98
+ import numpy as np
99
+ data = report.read(inputs)
100
+ o = digests(rt, original, data, twice=True)
101
+ e = digests(rt, edited, data, at=[runs[0][1] for runs in o])
102
+ rows, high = [], 0.0
103
+ for x, runs, (er,) in zip(data, o, e):
104
+ (h1, t1, v1), (h2, _, _) = runs
105
+ d = float(np.max(np.abs(er[2] - v1)))
106
+ high = max(high, d)
107
+ rows.append(dict({k: v for k, v in x.items() if k not in ("ids", "tokens")}, positions=len(h1), original_equal=h1 == h2,
108
+ positions_all_equal=sum(p == q for p, q in zip(h1, er[0])), positions_top_changed=sum(p != q for p, q in zip(t1, er[1])),
109
+ max_abs_top_difference=d))
110
+ totals = {"sequences": len(rows), **{k: sum(int(r[k]) for r in rows) for k in ("original_equal", "positions", "positions_all_equal", "positions_top_changed")},
111
+ "sequences_all_equal": sum(r["positions_all_equal"] == r["positions"] for r in rows), "max_abs_top_logit_difference": high}
112
+ fo, fe = weights.files(original), weights.files(edited)
113
+ r = dict(original=weights.named(fo, weights.hashes(fo)), edited=weights.named(fe, weights.hashes(fe)),
114
+ inputs={Path(inputs).name: report.sha(inputs)}, measure=totals, rows=rows)
115
+ if greedy_files:
116
+ r["measure greedy"] = report.unchanged(greedy_files)
117
+ r["generations"] = {Path(f).name: report.sha(f) for f in greedy_files}
118
+ report.finish(out, r)