model-debugger 0.4.0__py3-none-any.whl
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.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
"""A binding across doses, across the tokens of a generation and across runs.
|
|
2
|
+
|
|
3
|
+
Doses. A binding edit (``symbol_finite.edit_bindings``: cells moved to ``x + dose (target -
|
|
4
|
+
x)``; ``liveness``: the reader row's reads of its value cells scaled by ``1 - dose``) is run
|
|
5
|
+
natively at the doses a ``DosePolicy`` picks. Shipped policies: ``EnvelopeDoses`` (the default),
|
|
6
|
+
``GridDoses`` and ``BisectDoses``; subclass ``DosePolicy`` for another.
|
|
7
|
+
|
|
8
|
+
The decision envelope (``decision_envelope``, exact rational arithmetic, ported from cmachine
|
|
9
|
+
``tools/decision_envelope.py``). For a final state ``h(alpha) = h_lo + (alpha - lo)/(hi - lo)
|
|
10
|
+
(h_hi - h_lo)`` on the straight line between the two endpoint captures, a bias-free head after
|
|
11
|
+
RMS gives ``logit_v(alpha) = rho(alpha) (a_v + alpha b_v)`` with ``a_v + alpha b_v = W_v gamma .
|
|
12
|
+
h(alpha)``; the common positive ``rho`` keeps the ranking, so the greedy winner on
|
|
13
|
+
``[lo, hi]`` is the upper hull of the lines ``a_v + alpha b_v``: the intervals where each token
|
|
14
|
+
wins and a binary64 dose inside each. Regime: the intervals are derived-exact for that
|
|
15
|
+
fixed-additive final-state path (exact over the float64 coefficients ``a``, ``b``; native
|
|
16
|
+
logit rounding can move a boundary by rounding). The native dose path (cells moved by
|
|
17
|
+
``alpha``, every later layer recomputed) is not affine in ``alpha``: there the intervals are a
|
|
18
|
+
derived-local forecast, every probe is a measured native run, and ``agrees`` says whether the
|
|
19
|
+
native winner at that dose is the envelope's. The endpoints are measured in both regimes and
|
|
20
|
+
coincide with the secant path's, so the envelope runs no probe in a segment that holds an
|
|
21
|
+
endpoint: a winner that holds or changes once on ``[lo, hi]`` costs no run beyond the two
|
|
22
|
+
endpoints; a token that wins only in the middle costs one run.
|
|
23
|
+
|
|
24
|
+
Default: ``EnvelopeDoses``. The endpoint runs are the ones a one-point test already makes
|
|
25
|
+
(``liveness``'s null arm and its full arm), the envelope itself is two matrix products with
|
|
26
|
+
the unembedding, and a probe is run only where a token is predicted to win strictly inside
|
|
27
|
+
``(lo, hi)`` (exactly what one operating point and a quarter grid can miss). It is not a
|
|
28
|
+
guarantee: a winner that exists on the native dose path but not on the secant is not probed.
|
|
29
|
+
``GridDoses`` costs ``n - 1`` runs whatever happens; ``BisectDoses`` runs only where the two
|
|
30
|
+
ends of an interval disagree, so it misses a middle winner whose ends agree.
|
|
31
|
+
|
|
32
|
+
Per-token lifetime (``lifetime_ledger``): per binding and reader row, the attention mass the
|
|
33
|
+
row's reads of its value cells receive, summed over heads and layers (``sum p``, derived-exact
|
|
34
|
+
from the native ``p``) and its largest single-head value. Only ``p`` is read, so it is cheap
|
|
35
|
+
across a whole generation.
|
|
36
|
+
|
|
37
|
+
Identity across runs (``interface_row``, ``interface_compare``, ``witnesses``; cmachine
|
|
38
|
+
``cm_interface_compare``): a binding's interface row is a scope (model identity, execution
|
|
39
|
+
profile, consumer, horizon, edits), its arguments and its result, each as canonical bytes.
|
|
40
|
+
Rows of different scopes or arguments are not compared; equal arguments with equal results
|
|
41
|
+
agree on that pair; equal arguments with different results are a witness: a counterexample to
|
|
42
|
+
the two bindings being one symbol over that interface. Agreement is not a certificate of
|
|
43
|
+
sufficiency, only the absence of a counterexample on the pairs given.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
from __future__ import annotations
|
|
47
|
+
|
|
48
|
+
import abc
|
|
49
|
+
import hashlib
|
|
50
|
+
import json
|
|
51
|
+
import math
|
|
52
|
+
from collections.abc import Callable
|
|
53
|
+
from dataclasses import dataclass, field
|
|
54
|
+
from fractions import Fraction
|
|
55
|
+
from typing import Any
|
|
56
|
+
|
|
57
|
+
from ..numerics.labels import EXACT, LOCAL, MEASURED, SUPPLIED, f64, num
|
|
58
|
+
from ..predict.consumers import Margin, Refusal
|
|
59
|
+
|
|
60
|
+
SEGMENTS = 16 # envelope segments listed in a report (the rest counted)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _torch():
|
|
64
|
+
import torch
|
|
65
|
+
|
|
66
|
+
return torch
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# --------------------------------------------------------------------------- exact envelope
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def rational(value: Any) -> Fraction:
|
|
73
|
+
"""A coefficient as an exact rational: an int, a finite float (its stored binary64
|
|
74
|
+
value), or a decimal / rational string."""
|
|
75
|
+
if isinstance(value, bool) or not isinstance(value, (int, float, str)):
|
|
76
|
+
raise ValueError("coefficient must be an integer, finite float or rational string")
|
|
77
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
78
|
+
raise ValueError("nonfinite coefficient")
|
|
79
|
+
if isinstance(value, str) and len(value) > 8192:
|
|
80
|
+
raise ValueError("coefficient text exceeds inspection bound")
|
|
81
|
+
out = Fraction(value)
|
|
82
|
+
if out.numerator.bit_length() > 4096 or out.denominator.bit_length() > 4096:
|
|
83
|
+
raise ValueError("coefficient precision exceeds inspection bound")
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _probe(left: Fraction, right: Fraction) -> dict[str, Any]:
|
|
88
|
+
"""An interior dyadic binary64 dose of ``(left, right)``, or why there is none."""
|
|
89
|
+
midpoint = (left + right) / 2
|
|
90
|
+
for power in range(1075):
|
|
91
|
+
scale = 1 << power
|
|
92
|
+
point = Fraction((left * scale).__floor__() + 1, scale)
|
|
93
|
+
if point >= right:
|
|
94
|
+
continue
|
|
95
|
+
try:
|
|
96
|
+
value = float(point)
|
|
97
|
+
except OverflowError:
|
|
98
|
+
continue
|
|
99
|
+
if math.isfinite(value) and left < Fraction(value) < right:
|
|
100
|
+
return {"exact_midpoint": str(midpoint), "binary64_dose": value,
|
|
101
|
+
"binary64_exact": str(Fraction(value))}
|
|
102
|
+
return {"exact_midpoint": str(midpoint), "binary64_dose": None,
|
|
103
|
+
"reason": "no interior binary64 probe found"}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def decision_envelope(rows: list[dict[str, Any]], lower: Any = 0, upper: Any = 1, *,
|
|
107
|
+
vocabulary_size: int | None = None) -> dict[str, Any]:
|
|
108
|
+
"""The exact upper envelope of the lines ``intercept + dose * slope`` (``rows``:
|
|
109
|
+
``{token_id, intercept, slope}``) on ``[lower, upper]``: ``segments`` (positive-length
|
|
110
|
+
winning intervals as exact rational strings, the winner, identical-line ties and a binary64
|
|
111
|
+
probe inside) and ``points`` (the endpoints and every interior breakpoint with the tokens
|
|
112
|
+
tied there). The lowest token id wins an exact tie. ``vocabulary_size``: every id
|
|
113
|
+
``0..V-1`` must be present (coverage ``all-supplied-vocabulary-rows``); else the coverage
|
|
114
|
+
is ``provided-lines-only`` and no claim is made about omitted rows."""
|
|
115
|
+
lower, upper = rational(lower), rational(upper)
|
|
116
|
+
if lower > upper or not rows or len(rows) > 1_000_000:
|
|
117
|
+
raise ValueError("invalid envelope extent")
|
|
118
|
+
lines, ids = [], set()
|
|
119
|
+
for row in rows:
|
|
120
|
+
token = row["token_id"]
|
|
121
|
+
if isinstance(token, bool) or not isinstance(token, int) or token < 0 or token in ids:
|
|
122
|
+
raise ValueError("token IDs must be unique nonnegative integers")
|
|
123
|
+
ids.add(token)
|
|
124
|
+
lines.append({"a": rational(row["intercept"]), "b": rational(row["slope"]),
|
|
125
|
+
"ids": [token]})
|
|
126
|
+
if vocabulary_size is not None:
|
|
127
|
+
if isinstance(vocabulary_size, bool) or not isinstance(vocabulary_size, int) \
|
|
128
|
+
or vocabulary_size < 1:
|
|
129
|
+
raise ValueError("invalid vocabulary size")
|
|
130
|
+
if ids != set(range(vocabulary_size)):
|
|
131
|
+
raise ValueError("full-vocabulary declaration requires every vocabulary row")
|
|
132
|
+
parallel: dict[Fraction, dict[str, Any]] = {}
|
|
133
|
+
for line in lines: # dominated parallels never win; equal lines tie
|
|
134
|
+
old = parallel.get(line["b"])
|
|
135
|
+
if old is None or line["a"] > old["a"]:
|
|
136
|
+
parallel[line["b"]] = {"a": line["a"], "b": line["b"], "ids": list(line["ids"])}
|
|
137
|
+
elif line["a"] == old["a"]:
|
|
138
|
+
old["ids"].extend(line["ids"])
|
|
139
|
+
hull: list[tuple[dict[str, Any], Fraction | None]] = []
|
|
140
|
+
touches: dict[Fraction, set] = {}
|
|
141
|
+
for line in sorted(parallel.values(), key=lambda x: x["b"]):
|
|
142
|
+
line["ids"].sort()
|
|
143
|
+
start = None
|
|
144
|
+
while hull:
|
|
145
|
+
old, previous = hull[-1]
|
|
146
|
+
start = (old["a"] - line["a"]) / (line["b"] - old["b"])
|
|
147
|
+
if previous is None or start > previous:
|
|
148
|
+
break
|
|
149
|
+
if start == previous:
|
|
150
|
+
touches.setdefault(start, set()).update(old["ids"])
|
|
151
|
+
hull.pop()
|
|
152
|
+
hull.append((line, start if hull else None))
|
|
153
|
+
segments = []
|
|
154
|
+
for i, (line, start) in enumerate(hull):
|
|
155
|
+
stop = hull[i + 1][1] if i + 1 < len(hull) else None
|
|
156
|
+
left = lower if start is None else max(lower, start)
|
|
157
|
+
right = upper if stop is None else min(upper, stop)
|
|
158
|
+
if left < right:
|
|
159
|
+
segments.append({"left": str(left), "right": str(right), "winner": min(line["ids"]),
|
|
160
|
+
"tied_line_ids": line["ids"], "intercept": str(line["a"]),
|
|
161
|
+
"slope": str(line["b"]), "probe": _probe(left, right)})
|
|
162
|
+
points: dict[Fraction, list[int]] = {}
|
|
163
|
+
for point in {lower, upper}: # endpoint ties include lines winning outside
|
|
164
|
+
scores = [(line["a"] + point * line["b"], line["ids"][0]) for line in lines]
|
|
165
|
+
best = max(score for score, _ in scores)
|
|
166
|
+
points[point] = sorted(token for score, token in scores if score == best)
|
|
167
|
+
for i in range(1, len(hull)):
|
|
168
|
+
point = hull[i][1]
|
|
169
|
+
if lower < point < upper:
|
|
170
|
+
points[point] = sorted(set(hull[i - 1][0]["ids"]) | set(hull[i][0]["ids"])
|
|
171
|
+
| touches.get(point, set()))
|
|
172
|
+
return {"arithmetic": "exact-rational-supplied-coefficients",
|
|
173
|
+
"coverage": ("all-supplied-vocabulary-rows" if vocabulary_size is not None
|
|
174
|
+
else "provided-lines-only"),
|
|
175
|
+
"vocabulary_size": vocabulary_size, "input_rows": len(rows),
|
|
176
|
+
"domain": [str(lower), str(upper)], "segments": segments,
|
|
177
|
+
"points": [{"dose": str(p), "tied_token_ids": tied, "winner": min(tied)}
|
|
178
|
+
for p, tied in sorted(points.items())],
|
|
179
|
+
"operator_contract": "fixed-additive-final-readout/common-positive-RMS/bias-free-head"}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def envelope_winner(found: dict[str, Any], dose: float) -> int | None:
|
|
183
|
+
"""The envelope's winner at ``dose`` (a breakpoint: its lowest tied id)."""
|
|
184
|
+
x = Fraction(dose)
|
|
185
|
+
for point in found["points"]:
|
|
186
|
+
if Fraction(point["dose"]) == x:
|
|
187
|
+
return point["winner"]
|
|
188
|
+
for seg in found["segments"]:
|
|
189
|
+
if Fraction(seg["left"]) < x < Fraction(seg["right"]):
|
|
190
|
+
return seg["winner"]
|
|
191
|
+
return None
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def secant_lines(run: Any, h_lo: Any, h_hi: Any, lower: float = 0.0, upper: float = 1.0, *,
|
|
195
|
+
tokens: tuple[int, ...] | None = None, chunk: int = 32768
|
|
196
|
+
) -> tuple[list[dict[str, Any]], str]:
|
|
197
|
+
"""``(rows, coverage)``: the readout lines ``W_v gamma . h(alpha)`` of the secant final
|
|
198
|
+
state between ``h_lo`` (dose ``lower``) and ``h_hi`` (dose ``upper``), float64, over
|
|
199
|
+
``tokens`` or the whole vocabulary. Over the vocabulary, a row whose larger endpoint value
|
|
200
|
+
is below ``max_v min(endpoint values)`` (less a float64 margin) can win nowhere on the
|
|
201
|
+
interval (a line's maximum is at an endpoint) and is dropped before the exact hull.
|
|
202
|
+
``Refusal`` for a head with a bias (the common-scale argument fails)."""
|
|
203
|
+
torch = _torch()
|
|
204
|
+
adapter = run.adapter
|
|
205
|
+
head = adapter.model.lm_head
|
|
206
|
+
if getattr(head, "bias", None) is not None:
|
|
207
|
+
raise Refusal("the decision envelope needs a bias-free head")
|
|
208
|
+
weight = head.weight.detach()
|
|
209
|
+
device = weight.device if weight.device.type != "mps" else torch.device("cpu")
|
|
210
|
+
gamma = f64(getattr(adapter.backbone, adapter.spec.final_norm).weight).reshape(-1)
|
|
211
|
+
x0 = (gamma * f64(h_lo).reshape(-1)).to(device)
|
|
212
|
+
dx = (gamma * (f64(h_hi).reshape(-1) - f64(h_lo).reshape(-1)) / (upper - lower)).to(device)
|
|
213
|
+
ids = range(weight.shape[0]) if tokens is None else tokens
|
|
214
|
+
index = torch.tensor(list(ids), dtype=torch.long)
|
|
215
|
+
a, b = [], []
|
|
216
|
+
for start in range(0, index.numel(), chunk): # float64 on the weight's device
|
|
217
|
+
part = weight.index_select(0, index[start:start + chunk].to(weight.device)).to(
|
|
218
|
+
device, torch.float64)
|
|
219
|
+
a.append((part @ x0).cpu())
|
|
220
|
+
b.append((part @ dx).cpu())
|
|
221
|
+
a, b = torch.cat(a), torch.cat(b)
|
|
222
|
+
intercept = a - lower * b
|
|
223
|
+
keep = torch.ones_like(a, dtype=torch.bool)
|
|
224
|
+
coverage = "provided-lines-only"
|
|
225
|
+
if tokens is None:
|
|
226
|
+
s_lo, s_hi = intercept + lower * b, intercept + upper * b
|
|
227
|
+
floor = float(torch.minimum(s_lo, s_hi).max())
|
|
228
|
+
margin = 1e-9 * (1.0 + float(torch.maximum(s_lo.abs(), s_hi.abs()).max()))
|
|
229
|
+
keep = torch.maximum(s_lo, s_hi) >= floor - margin
|
|
230
|
+
coverage = "all-vocabulary-rows (rows that win nowhere on the interval dropped first)"
|
|
231
|
+
rows = [{"token_id": int(index[i]), "intercept": float(intercept[i]), "slope": float(b[i])}
|
|
232
|
+
for i in keep.nonzero().reshape(-1).tolist()]
|
|
233
|
+
return rows, coverage
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# --------------------------------------------------------------------------- dose policies
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class DoseProbe:
|
|
240
|
+
"""Native measurements of one edit at doses in ``[lower, upper]``.
|
|
241
|
+
|
|
242
|
+
``measure(dose)`` returns ``{"value": consumer, "winner": argmax token, "h": final state}``
|
|
243
|
+
(a native run, cached by dose); ``envelope(tokens)`` the decision envelope of the secant
|
|
244
|
+
between the two endpoint measurements (computed once per token set)."""
|
|
245
|
+
|
|
246
|
+
def __init__(self, run: Any, measure: Callable[[float], dict[str, Any]], *,
|
|
247
|
+
lower: float = 0.0, upper: float = 1.0,
|
|
248
|
+
measured: dict[float, dict[str, Any]] | None = None):
|
|
249
|
+
if not lower < upper:
|
|
250
|
+
raise Refusal("a dose interval needs lower < upper")
|
|
251
|
+
self.run, self._measure = run, measure
|
|
252
|
+
self.lower, self.upper = float(lower), float(upper)
|
|
253
|
+
self.measured: dict[float, dict[str, Any]] = dict(measured or {})
|
|
254
|
+
self._envelopes: dict[Any, dict[str, Any]] = {}
|
|
255
|
+
|
|
256
|
+
def measure(self, dose: float) -> dict[str, Any]:
|
|
257
|
+
dose = float(dose)
|
|
258
|
+
if dose not in self.measured:
|
|
259
|
+
self.measured[dose] = self._measure(dose)
|
|
260
|
+
return self.measured[dose]
|
|
261
|
+
|
|
262
|
+
def envelope(self, tokens: tuple[int, ...] | None = None) -> dict[str, Any]:
|
|
263
|
+
if tokens not in self._envelopes:
|
|
264
|
+
lo, hi = self.measure(self.lower), self.measure(self.upper)
|
|
265
|
+
rows, coverage = secant_lines(self.run, lo["h"], hi["h"], self.lower, self.upper,
|
|
266
|
+
tokens=tokens)
|
|
267
|
+
found = decision_envelope(rows, self.lower, self.upper)
|
|
268
|
+
found["coverage"] = coverage
|
|
269
|
+
self._envelopes[tokens] = found
|
|
270
|
+
return self._envelopes[tokens]
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class DosePolicy(abc.ABC):
|
|
274
|
+
"""Picks the doses at which an edit is measured natively. ``doses`` returns doses in
|
|
275
|
+
``[probe.lower, probe.upper]``; it may measure (``probe.measure``) or read the envelope
|
|
276
|
+
(``probe.envelope``) to decide. Every returned dose is measured by ``sweep``."""
|
|
277
|
+
|
|
278
|
+
name = "policy"
|
|
279
|
+
|
|
280
|
+
@abc.abstractmethod
|
|
281
|
+
def doses(self, probe: DoseProbe) -> list[float]:
|
|
282
|
+
"""The doses to measure."""
|
|
283
|
+
|
|
284
|
+
def describe(self) -> dict[str, Any]:
|
|
285
|
+
return {"name": self.name}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class EnvelopeDoses(DosePolicy):
|
|
289
|
+
"""The two endpoints plus the binary64 probe of every envelope segment that holds neither
|
|
290
|
+
endpoint (module docstring). ``tokens``: compete these tokens only (coverage
|
|
291
|
+
``provided-lines-only``) instead of the whole vocabulary."""
|
|
292
|
+
|
|
293
|
+
name = "envelope"
|
|
294
|
+
|
|
295
|
+
def __init__(self, tokens: tuple[int, ...] | None = None):
|
|
296
|
+
self.tokens = None if tokens is None else tuple(int(t) for t in tokens)
|
|
297
|
+
|
|
298
|
+
def doses(self, probe: DoseProbe) -> list[float]:
|
|
299
|
+
ends = (Fraction(probe.lower), Fraction(probe.upper))
|
|
300
|
+
out = [probe.lower, probe.upper]
|
|
301
|
+
for seg in probe.envelope(self.tokens)["segments"]:
|
|
302
|
+
left, right = Fraction(seg["left"]), Fraction(seg["right"])
|
|
303
|
+
dose = seg["probe"]["binary64_dose"]
|
|
304
|
+
if dose is not None and not any(left <= e <= right for e in ends):
|
|
305
|
+
out.append(dose)
|
|
306
|
+
return sorted(out)
|
|
307
|
+
|
|
308
|
+
def describe(self) -> dict[str, Any]:
|
|
309
|
+
return {"name": self.name, "tokens": None if self.tokens is None else len(self.tokens)}
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class GridDoses(DosePolicy):
|
|
313
|
+
"""``n + 1`` evenly spaced doses from ``lower`` to ``upper``."""
|
|
314
|
+
|
|
315
|
+
name = "grid"
|
|
316
|
+
|
|
317
|
+
def __init__(self, n: int = 4):
|
|
318
|
+
if n < 1:
|
|
319
|
+
raise Refusal("a dose grid needs n >= 1")
|
|
320
|
+
self.n = int(n)
|
|
321
|
+
|
|
322
|
+
def doses(self, probe: DoseProbe) -> list[float]:
|
|
323
|
+
step = (probe.upper - probe.lower) / self.n
|
|
324
|
+
return [probe.lower + i * step for i in range(self.n)] + [probe.upper]
|
|
325
|
+
|
|
326
|
+
def describe(self) -> dict[str, Any]:
|
|
327
|
+
return {"name": self.name, "n": self.n}
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
class BisectDoses(DosePolicy):
|
|
331
|
+
"""Measure both ends; while an interval's two ends name different winners and it is wider
|
|
332
|
+
than ``width``, measure its midpoint and recurse, at most ``budget`` runs in all. Finds
|
|
333
|
+
every change between disagreeing ends to ``width``; misses a middle winner whose
|
|
334
|
+
interval ends agree."""
|
|
335
|
+
|
|
336
|
+
name = "bisect"
|
|
337
|
+
|
|
338
|
+
def __init__(self, budget: int = 8, width: float = 2.0 ** -6):
|
|
339
|
+
self.budget, self.width = int(budget), float(width)
|
|
340
|
+
|
|
341
|
+
def doses(self, probe: DoseProbe) -> list[float]:
|
|
342
|
+
out = {probe.lower, probe.upper}
|
|
343
|
+
stack = [(probe.lower, probe.upper)]
|
|
344
|
+
while stack and len(out) < self.budget:
|
|
345
|
+
lo, hi = stack.pop()
|
|
346
|
+
if hi - lo <= self.width or \
|
|
347
|
+
probe.measure(lo)["winner"] == probe.measure(hi)["winner"]:
|
|
348
|
+
continue
|
|
349
|
+
mid = (lo + hi) / 2
|
|
350
|
+
probe.measure(mid)
|
|
351
|
+
out.add(mid)
|
|
352
|
+
stack += [(mid, hi), (lo, mid)]
|
|
353
|
+
return sorted(out)
|
|
354
|
+
|
|
355
|
+
def describe(self) -> dict[str, Any]:
|
|
356
|
+
return {"name": self.name, "budget": self.budget, "width": num(self.width, SUPPLIED)}
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
REGIME = ("envelope intervals: derived-exact for the secant final state between the endpoint "
|
|
360
|
+
"captures (fixed additive final-state edit, bias-free head, common positive RMS); "
|
|
361
|
+
"for the native dose path they are a derived-local forecast, each point is a "
|
|
362
|
+
"measured native run and agrees says whether its winner is the envelope's")
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def sweep(probe: DoseProbe, policy: DosePolicy | None = None, *,
|
|
366
|
+
tokens: tuple[int, ...] | None = None) -> dict[str, Any]:
|
|
367
|
+
"""Measure the doses ``policy`` picks (default ``EnvelopeDoses``) and report each with the
|
|
368
|
+
envelope's predicted winner; ``tokens`` restricts the envelope's competition."""
|
|
369
|
+
policy = EnvelopeDoses(tokens) if policy is None else policy
|
|
370
|
+
if tokens is None and isinstance(policy, EnvelopeDoses):
|
|
371
|
+
tokens = policy.tokens
|
|
372
|
+
doses = policy.doses(probe)
|
|
373
|
+
for dose in doses:
|
|
374
|
+
probe.measure(dose)
|
|
375
|
+
base = probe.measure(probe.lower)["value"]
|
|
376
|
+
found = probe.envelope(tokens)
|
|
377
|
+
points = []
|
|
378
|
+
for dose in sorted(set(doses)):
|
|
379
|
+
got = probe.measured[dose]
|
|
380
|
+
predicted = envelope_winner(found, dose)
|
|
381
|
+
points.append({"dose": num(dose, SUPPLIED), "value": num(got["value"], MEASURED),
|
|
382
|
+
"delta": num(got["value"] - base, MEASURED), "winner": got["winner"],
|
|
383
|
+
"predicted": predicted, "agrees": predicted == got["winner"]})
|
|
384
|
+
segments = [{"left": s["left"], "right": s["right"],
|
|
385
|
+
"left_float": num(float(Fraction(s["left"])), EXACT),
|
|
386
|
+
"right_float": num(float(Fraction(s["right"])), EXACT),
|
|
387
|
+
"winner": s["winner"],
|
|
388
|
+
"probe": None if s["probe"]["binary64_dose"] is None else
|
|
389
|
+
num(s["probe"]["binary64_dose"], EXACT)}
|
|
390
|
+
for s in found["segments"]]
|
|
391
|
+
return {"policy": policy.describe(),
|
|
392
|
+
"domain": [num(probe.lower, SUPPLIED), num(probe.upper, SUPPLIED)],
|
|
393
|
+
"points": points, "runs": len(probe.measured),
|
|
394
|
+
"winners": sorted({p["winner"] for p in points}),
|
|
395
|
+
"envelope": {"segments": segments[:SEGMENTS],
|
|
396
|
+
"omitted": max(0, len(segments) - SEGMENTS),
|
|
397
|
+
"coverage": found["coverage"],
|
|
398
|
+
"operator_contract": found["operator_contract"]},
|
|
399
|
+
"regime": REGIME,
|
|
400
|
+
"forecast_authority": LOCAL}
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _winner(logits: Any) -> int:
|
|
404
|
+
return int(logits.reshape(-1).double().argmax())
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def dose_sweep(run: Any, binding: Any, reader: Any, *, policy: DosePolicy | None = None,
|
|
408
|
+
donor: Any = None, lower: float = 0.0, upper: float = 1.0,
|
|
409
|
+
tokens: tuple[int, ...] | None = None) -> dict[str, Any]:
|
|
410
|
+
"""``sweep`` of ``symbol_finite.edit_bindings(run, [binding], reader.row, dose=d,
|
|
411
|
+
donor=donor)`` (k and v cells; dose 0 is ``run`` itself). Scalar consumer."""
|
|
412
|
+
from .symbol_finite import _value, edit_bindings
|
|
413
|
+
|
|
414
|
+
if reader is None or not reader.scalar:
|
|
415
|
+
raise Refusal("a dose sweep needs a scalar consumer (a margin or a logit)")
|
|
416
|
+
j, last = reader.row, run.adapter.layers - 1
|
|
417
|
+
|
|
418
|
+
def read(r: Any) -> dict[str, Any]:
|
|
419
|
+
return {"value": _value(r, reader), "winner": _winner(r.read(f"t{j}.logits")),
|
|
420
|
+
"h": f64(r.read(f"t{j}.L{last}.h_out")).reshape(-1)}
|
|
421
|
+
|
|
422
|
+
def measure(dose: float) -> dict[str, Any]:
|
|
423
|
+
if dose == 0.0:
|
|
424
|
+
return read(run)
|
|
425
|
+
edited = edit_bindings(run, [binding], j, dose=dose, donor=donor)
|
|
426
|
+
try:
|
|
427
|
+
return read(edited)
|
|
428
|
+
finally:
|
|
429
|
+
edited.close()
|
|
430
|
+
out = sweep(DoseProbe(run, measure, lower=lower, upper=upper), policy, tokens=tokens)
|
|
431
|
+
out["edit"] = ("cells x + dose (target - x), target " +
|
|
432
|
+
("zero" if donor is None else f"donor {getattr(donor, 'name', None) or 'run'}"))
|
|
433
|
+
return out
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
# --------------------------------------------------------------------------- lifetime ledger
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def lifetime_ledger(run: Any, bindings: list[Any] | None = None, *, rows: str | None = "all",
|
|
440
|
+
min_mass: float = 0.1) -> dict[str, Any]:
|
|
441
|
+
"""Per binding, one scalar per reader row (module docstring): ``mass`` ``[B, R]`` (sum of
|
|
442
|
+
``p`` over heads and layers of the row's reads of the binding's value cells, derived-exact)
|
|
443
|
+
and ``peak`` ``[B, R]`` (the largest single-head sum), with ``first``/``last`` reader row
|
|
444
|
+
whose peak reaches ``min_mass`` and a strip per binding (``#`` peak >= ``min_mass``, ``.``
|
|
445
|
+
read below it, ``-`` no value cell read, ``?`` a layer's ``p`` not computed). ``rows``: the
|
|
446
|
+
reader rows (``reads.reader_rows``: default every stepped row to the cursor).
|
|
447
|
+
``bindings``: default the table's (declared symbols, then token rows)."""
|
|
448
|
+
from mdb.core.records import nums
|
|
449
|
+
|
|
450
|
+
from ..measure.readout import computed
|
|
451
|
+
from ..measure.reads import Source, reader_rows
|
|
452
|
+
from .binding import declared
|
|
453
|
+
from .table import _token_rows
|
|
454
|
+
|
|
455
|
+
torch = _torch()
|
|
456
|
+
if bindings is None:
|
|
457
|
+
users = list(declared(run).values())
|
|
458
|
+
bindings = users + _token_rows(run, run.parse(run.where)[0], users)
|
|
459
|
+
found = reader_rows(run, Source(0), rows)
|
|
460
|
+
adapter = run.adapter
|
|
461
|
+
heads, kv, layers = adapter.num_heads, adapter.num_kv_heads, adapter.layers
|
|
462
|
+
kappa = [h // (heads // kv) for h in range(heads)]
|
|
463
|
+
n, width = len(bindings), max(found) + 1
|
|
464
|
+
owner = torch.full((layers, kv, width), -1, dtype=torch.long) # value cell -> binding
|
|
465
|
+
for b, binding in enumerate(bindings):
|
|
466
|
+
for row in {c.row for c in binding.cells}:
|
|
467
|
+
if row < width:
|
|
468
|
+
for layer in range(layers):
|
|
469
|
+
for g in range(kv):
|
|
470
|
+
if binding.covers(row, layer, g, "v"):
|
|
471
|
+
owner[layer, g, row] = b
|
|
472
|
+
mass = torch.zeros(n, len(found), dtype=torch.float64)
|
|
473
|
+
peak = torch.zeros(n, len(found), dtype=torch.float64)
|
|
474
|
+
read = torch.zeros(n, len(found), dtype=torch.bool)
|
|
475
|
+
pending = [False] * len(found)
|
|
476
|
+
for i, j in enumerate(found):
|
|
477
|
+
for layer in range(layers):
|
|
478
|
+
address = f"t{j}.L{layer}.p"
|
|
479
|
+
if j < run.first_row or not computed(run, address):
|
|
480
|
+
pending[i] = True
|
|
481
|
+
continue
|
|
482
|
+
p = f64(run.read(address)).reshape(heads, -1)
|
|
483
|
+
index = owner[layer][kappa, : p.shape[1]] # (H, T)
|
|
484
|
+
held = index >= 0
|
|
485
|
+
per = torch.zeros(n, heads, dtype=torch.float64)
|
|
486
|
+
per.index_put_((index[held], held.nonzero()[:, 0]), p[held], accumulate=True)
|
|
487
|
+
mass[:, i] += per.sum(1)
|
|
488
|
+
peak[:, i] = torch.maximum(peak[:, i], per.max(1).values)
|
|
489
|
+
read[:, i] |= torch.bincount(index[held], minlength=n) > 0
|
|
490
|
+
out = []
|
|
491
|
+
for b, binding in enumerate(bindings):
|
|
492
|
+
live = [found[i] for i in range(len(found)) if peak[b, i] >= min_mass]
|
|
493
|
+
strip = "".join("?" if pending[i] else "#" if peak[b, i] >= min_mass else
|
|
494
|
+
"." if read[b, i] else "-" for i in range(len(found)))
|
|
495
|
+
entry = {"symbol": binding.name, "first": f"t{live[0]}" if live else None,
|
|
496
|
+
"last": f"t{live[-1]}" if live else None}
|
|
497
|
+
if len(strip) <= 4096:
|
|
498
|
+
entry["strip"] = strip
|
|
499
|
+
out.append(entry)
|
|
500
|
+
return {"rows": [found[0], found[-1] + 1], "count": len(found),
|
|
501
|
+
"min_mass": num(float(min_mass), SUPPLIED), "bindings": out,
|
|
502
|
+
"mass": nums(mass, EXACT), "peak": nums(peak, EXACT),
|
|
503
|
+
"meaning": "per binding and reader row: sum over heads and layers of the native p of "
|
|
504
|
+
"the row's reads of the binding's value cells (mass) and the largest "
|
|
505
|
+
"one-head sum (peak); rows are a half-open range"}
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
# --------------------------------------------------------------------------- identity
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
RELATIONS = ("other-scope", "other-arguments", "agrees", "witness")
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
@dataclass(frozen=True)
|
|
515
|
+
class InterfaceRow:
|
|
516
|
+
"""One occurrence of a binding's interface: ``scope``, ``arguments`` and ``result`` as
|
|
517
|
+
canonical bytes (compared bytewise); ``shown`` a readable form of each (not compared)."""
|
|
518
|
+
|
|
519
|
+
scope: bytes
|
|
520
|
+
occurrence: str
|
|
521
|
+
arguments: bytes
|
|
522
|
+
result: bytes
|
|
523
|
+
shown: dict[str, Any] = field(default_factory=dict, compare=False)
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def interface_compare(a: InterfaceRow, b: InterfaceRow) -> str:
|
|
527
|
+
"""``other-scope``, ``other-arguments``, ``agrees`` or ``witness`` (equal scope and
|
|
528
|
+
arguments, different result)."""
|
|
529
|
+
if a.scope != b.scope:
|
|
530
|
+
return "other-scope"
|
|
531
|
+
if a.arguments != b.arguments:
|
|
532
|
+
return "other-arguments"
|
|
533
|
+
return "agrees" if a.result == b.result else "witness"
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _canon(value: Any) -> bytes:
|
|
537
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _sha(raw: bytes) -> str:
|
|
541
|
+
return hashlib.sha256(raw).hexdigest()
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _tensor_bytes(x: Any) -> bytes:
|
|
545
|
+
x = x.detach().to("cpu").contiguous()
|
|
546
|
+
return str(x.dtype).encode() + _canon(list(x.shape)) + x.reshape(-1).view(
|
|
547
|
+
_torch().uint8).numpy().tobytes()
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def cell_bytes(run: Any, binding: Any, row: int) -> bytes:
|
|
551
|
+
"""The binding's k/v cells at rows ``<= row`` as stored (native dtype, post-RoPE keys), in
|
|
552
|
+
the order (layer, port, KV head, the cell's rank among the binding's rows): the bytes do
|
|
553
|
+
not depend on the absolute row numbers, only on the values."""
|
|
554
|
+
from .symbol_finite import binding_cells
|
|
555
|
+
|
|
556
|
+
adapter = run.adapter
|
|
557
|
+
cells = binding_cells(binding, row, adapter.layers, adapter.num_kv_heads)
|
|
558
|
+
rank = {s: i for i, s in enumerate(sorted({key[2] for key in cells}))}
|
|
559
|
+
parts = []
|
|
560
|
+
for (layer, port, s), heads in sorted(cells.items(), key=lambda kv: (kv[0][0], kv[0][1],
|
|
561
|
+
rank[kv[0][2]])):
|
|
562
|
+
cache = run.read_cache(layer, port)[0]
|
|
563
|
+
if cache.shape[1] > s:
|
|
564
|
+
block = cache[heads, s]
|
|
565
|
+
elif port == "v":
|
|
566
|
+
block = run.read(f"t{s}.L{layer}.v").reshape(adapter.num_kv_heads, -1)[heads]
|
|
567
|
+
else:
|
|
568
|
+
block = run.read(f"t{s}.L{layer}.kr")[0, heads, s]
|
|
569
|
+
parts.append(_canon([layer, port, heads, rank[s]]) + _tensor_bytes(block))
|
|
570
|
+
return b"".join(parts)
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def binding_write(run: Any, binding: Any, row: int) -> Any:
|
|
574
|
+
"""The binding's write into reader row ``row``, summed over its reads (float64, ``(d,)``):
|
|
575
|
+
``sum p[h, s] W_O,h v[kappa(h), s]`` over the value cells it holds (P06/P07)."""
|
|
576
|
+
from ..measure.readout import head_mix
|
|
577
|
+
|
|
578
|
+
torch = _torch()
|
|
579
|
+
total, weights = None, {}
|
|
580
|
+
for layer in range(run.adapter.layers):
|
|
581
|
+
mix = head_mix(run, row, layer, weights)
|
|
582
|
+
own = torch.tensor([[binding.covers(s, layer, g, "v") for s in range(mix.p.shape[1])]
|
|
583
|
+
for g in range(run.adapter.num_kv_heads)], dtype=torch.bool)
|
|
584
|
+
parts = mix.o_parts()[own[mix.kappa]].sum(0)
|
|
585
|
+
total = parts if total is None else total + parts
|
|
586
|
+
return total
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def _consumer(consumer: Any) -> Any:
|
|
590
|
+
if isinstance(consumer, Margin):
|
|
591
|
+
return {"kind": "margin", "a": int(consumer.a), "b": int(consumer.b)}
|
|
592
|
+
if consumer is None:
|
|
593
|
+
return None
|
|
594
|
+
return {"kind": type(consumer).__name__.lower(), "text": getattr(consumer, "text",
|
|
595
|
+
str(consumer))}
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def interface_row(run: Any, binding: Any, *, row: int | None = None,
|
|
599
|
+
arguments: Any = "cells", result: Any = None, sets: list[Any] | None = None,
|
|
600
|
+
consumer: Any = None, scope: dict[str, Any] | None = None) -> InterfaceRow:
|
|
601
|
+
"""The interface row of ``binding`` read at reader row ``row`` (default the cursor's).
|
|
602
|
+
|
|
603
|
+
``arguments``: ``"cells"`` (``cell_bytes``), a JSON-able value the caller supplies (the
|
|
604
|
+
abstract argument, e.g. ``{"country": "France"}``) or a callable ``(run, binding) ->``
|
|
605
|
+
JSON-able. ``result``: ``"content"`` (per candidate set of ``sets``, the best token of the
|
|
606
|
+
binding's write; ``symbols.content``), ``"write"`` (the float64 bytes of ``binding_write``),
|
|
607
|
+
``"effect"`` (the float64 bytes of its exact contribution to the scalar ``consumer``) or a
|
|
608
|
+
callable; default ``"content"`` with ``sets``, else ``"write"``. The scope binds the model
|
|
609
|
+
identity, the execution profile, the consumer or sets, the result and argument kinds, the
|
|
610
|
+
horizon (the cursor's stop, row-relative) and whether the run carries edits; ``scope`` adds
|
|
611
|
+
caller entries (an intervention class, a task, the edit applied)."""
|
|
612
|
+
from ..measure.readout import readout
|
|
613
|
+
from .table import content, readout_basis
|
|
614
|
+
|
|
615
|
+
torch = _torch()
|
|
616
|
+
j = int(run.where.split(".")[0][1:]) if row is None else int(row)
|
|
617
|
+
result = ("content" if sets else "write") if result is None else result
|
|
618
|
+
if isinstance(arguments, str) and arguments == "cells":
|
|
619
|
+
args = cell_bytes(run, binding, j)
|
|
620
|
+
shown_args: Any = {"cells_sha256": _sha(args)}
|
|
621
|
+
else:
|
|
622
|
+
value = arguments(run, binding) if callable(arguments) else arguments
|
|
623
|
+
args, shown_args = _canon(value), value
|
|
624
|
+
if callable(result):
|
|
625
|
+
value = result(run, binding)
|
|
626
|
+
res, shown_res = _canon(value), value
|
|
627
|
+
elif result == "content":
|
|
628
|
+
if not sets:
|
|
629
|
+
raise Refusal("a content result needs candidate sets")
|
|
630
|
+
found = content(run, binding_write(run, binding, j), sets, readout_basis(run, j))
|
|
631
|
+
shown_res = {c.name: found[c.name]["best"] for c in sets}
|
|
632
|
+
res = _canon(shown_res)
|
|
633
|
+
elif result == "write":
|
|
634
|
+
res = binding_write(run, binding, j).numpy().tobytes()
|
|
635
|
+
shown_res = {"write_sha256": _sha(res)}
|
|
636
|
+
elif result == "effect":
|
|
637
|
+
reader = readout(run, consumer)
|
|
638
|
+
if not reader.scalar:
|
|
639
|
+
raise Refusal("an effect result needs a scalar consumer")
|
|
640
|
+
effect = float(f64(reader.vector) @ binding_write(run, binding, j))
|
|
641
|
+
res = torch.tensor(effect, dtype=torch.float64).numpy().tobytes()
|
|
642
|
+
shown_res = {"effect": effect}
|
|
643
|
+
else:
|
|
644
|
+
raise Refusal(f"result is content, write, effect or a callable, not {result!r}")
|
|
645
|
+
stop = run.where.split(".", 1)[1]
|
|
646
|
+
body = {"model": run.adapter.model_identity, "execution": dict(run.adapter.execution),
|
|
647
|
+
"consumer": _consumer(consumer),
|
|
648
|
+
"sets": None if not sets else [[c.name, list(c.tokens)] for c in sets],
|
|
649
|
+
"arguments": arguments if isinstance(arguments, str) else
|
|
650
|
+
"callable" if callable(arguments) else "supplied",
|
|
651
|
+
"result": result if isinstance(result, str) else "callable",
|
|
652
|
+
"horizon": stop, "edited": bool(run.edited), **(scope or {})}
|
|
653
|
+
return InterfaceRow(_canon(body), f"{getattr(run, 'name', None) or 'run'}:{binding.name}"
|
|
654
|
+
f"@t{j}", args, res,
|
|
655
|
+
{"arguments": shown_args, "result": shown_res, "scope": _sha(_canon(body))})
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def witnesses(rows: list[InterfaceRow], *, limit: int = 16) -> dict[str, Any]:
|
|
659
|
+
"""Compare every pair of interface rows; report the count of each relation and the
|
|
660
|
+
witnesses (equal scope and arguments, different results), at most ``limit`` listed."""
|
|
661
|
+
counts = dict.fromkeys(RELATIONS, 0)
|
|
662
|
+
found = []
|
|
663
|
+
for i in range(len(rows)):
|
|
664
|
+
for k in range(i + 1, len(rows)):
|
|
665
|
+
relation = interface_compare(rows[i], rows[k])
|
|
666
|
+
counts[relation] += 1
|
|
667
|
+
if relation == "witness":
|
|
668
|
+
found.append({"a": rows[i].occurrence, "b": rows[k].occurrence,
|
|
669
|
+
"scope_sha256": _sha(rows[i].scope),
|
|
670
|
+
"arguments_sha256": _sha(rows[i].arguments),
|
|
671
|
+
"results": [rows[i].shown.get("result"),
|
|
672
|
+
rows[k].shown.get("result")]})
|
|
673
|
+
return {"rows": len(rows), "pairs": counts, "witnesses": found[:limit],
|
|
674
|
+
"omitted": max(0, len(found) - limit),
|
|
675
|
+
"verdict": ("counterexample: not one symbol over this interface" if found else
|
|
676
|
+
"no counterexample on these pairs (not a certificate)")}
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
__all__ = ["BisectDoses", "DosePolicy", "DoseProbe", "EnvelopeDoses", "GridDoses",
|
|
680
|
+
"InterfaceRow", "RELATIONS", "REGIME", "binding_write", "cell_bytes",
|
|
681
|
+
"decision_envelope", "dose_sweep", "envelope_winner", "interface_compare",
|
|
682
|
+
"interface_row", "lifetime_ledger", "rational", "secant_lines", "sweep",
|
|
683
|
+
"witnesses"]
|