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,348 @@
|
|
|
1
|
+
"""Native measurement of a consumer under a set of edits, and the comparison of two branches.
|
|
2
|
+
|
|
3
|
+
``measure(run, edits, consumer)`` stages every edit at its layer (rewinding by layer
|
|
4
|
+
boundaries first when an edited layer is already committed), runs natively to the consumer,
|
|
5
|
+
reads it and restores the session; ``state_digest`` is checked before and after. It is the
|
|
6
|
+
multi-edit form of the measurement step of ``propagate.whatif`` and refuses what that refuses
|
|
7
|
+
(an edit that is not a layer port, a consumer that is not downstream, a rewind that would drop
|
|
8
|
+
staged or later committed edits).
|
|
9
|
+
|
|
10
|
+
State-cell edits (``Edit.cell``) are staged where ``propagate.cell_plan`` puts them (at the
|
|
11
|
+
cursor when the consumer is ahead, else at the entry of the consumer row's cell layer); a set
|
|
12
|
+
that would rewind past a cell staged at the cursor is refused. Two cell edits conflict in A+B
|
|
13
|
+
when they write overlapping elements of one cache tensor with ops that do not commute (``mix``
|
|
14
|
+
never commutes).
|
|
15
|
+
|
|
16
|
+
``compare(run, a, b, consumer)``: a side is a list of edits (``propagate.Edit``; applied on the
|
|
17
|
+
current session) or a checkpoint (an in-memory ``Run.checkpoint()`` dict, or a ``Run``
|
|
18
|
+
replayed from a durable recipe). The consumer is measured at ``base`` (the current session), at
|
|
19
|
+
``A``, at ``B`` and, when both sides are edits, at ``A+B`` (both sets applied together); each is
|
|
20
|
+
``measured``. The effects ``A - base``, ``B - base`` and the interaction ``(A+B) - A - B + base``
|
|
21
|
+
are arithmetic on measured values (``measured``). For a vector consumer the effects are
|
|
22
|
+
reported as max-abs and norm of the differences.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from ..numerics.labels import MEASURED, f64
|
|
31
|
+
from ..numerics.verdict import decide, magnitude
|
|
32
|
+
from ..predict.consumers import Logit, Margin, Refusal
|
|
33
|
+
from ..predict.plan import Edit, plan, state_digest
|
|
34
|
+
from ..predict.whatif import stage
|
|
35
|
+
from .readout import claim
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _guard(run: Any, checkpoints: list[dict[str, Any]]) -> None:
|
|
39
|
+
"""Hold every edit tensor the checkpoints name (so ``restore`` can rebuild them); refuse,
|
|
40
|
+
before anything native runs, a checkpoint naming a tensor this run does not hold."""
|
|
41
|
+
held = run.edit_tensors()
|
|
42
|
+
for checkpoint in checkpoints:
|
|
43
|
+
manifests = [*checkpoint["edits"], *(m for item in checkpoint["path_edits"]
|
|
44
|
+
for m in item["edits"])]
|
|
45
|
+
for manifest in manifests:
|
|
46
|
+
needed = [manifest["value"].get("sha256"), manifest.get("mask_sha256")]
|
|
47
|
+
missing = [sha for sha in needed if sha is not None and sha not in held]
|
|
48
|
+
if missing:
|
|
49
|
+
raise Refusal(f"the session cannot be restored: edit tensor {missing[0][:12]} at "
|
|
50
|
+
f"{manifest['port']} is not held by this run")
|
|
51
|
+
run.hold(held)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
_SAME = ("where", "cut", "transitions", "port", "edits", "path_edits")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def restore_exactly(run: Any, checkpoint: dict[str, Any]) -> None:
|
|
58
|
+
"""``run.restore(checkpoint)`` that finishes even under a ``KeyboardInterrupt`` (re-raised
|
|
59
|
+
after it), then checks that the cursor, the cut and the committed and staged edits equal the
|
|
60
|
+
checkpoint's; ``RuntimeError`` if not."""
|
|
61
|
+
try:
|
|
62
|
+
run.restore(checkpoint, defer_interrupt=True)
|
|
63
|
+
finally:
|
|
64
|
+
now = run.checkpoint()
|
|
65
|
+
differ = [key for key in _SAME if now[key] != checkpoint[key]]
|
|
66
|
+
if differ:
|
|
67
|
+
raise RuntimeError(f"the restore to {checkpoint['where']} left {', '.join(differ)} "
|
|
68
|
+
f"different (now at {run.where})")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def consumer_stop(run: Any, consumer: Any) -> str:
|
|
72
|
+
"""The stop a consumer is read at: the row's ``logits`` for a margin or logit."""
|
|
73
|
+
if isinstance(consumer, (Margin, Logit)):
|
|
74
|
+
return f"t{consumer.row}.logits"
|
|
75
|
+
key = run.parse(consumer)
|
|
76
|
+
label = run.stops()[key[1]]
|
|
77
|
+
if label in ("start", "sample"):
|
|
78
|
+
raise Refusal(f"{label} is a token id, not a value with a change; use a margin M[a,b] "
|
|
79
|
+
"or a logit as the consumer")
|
|
80
|
+
return f"t{key[0]}.{label}"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def consumer_value(consumer: Any, value: Any) -> Any:
|
|
84
|
+
"""The consumer's float64 value from the tensor read at its stop (index, then cast)."""
|
|
85
|
+
flat = value.reshape(-1)
|
|
86
|
+
if isinstance(consumer, Margin):
|
|
87
|
+
return f64(flat[consumer.a]) - f64(flat[consumer.b])
|
|
88
|
+
if isinstance(consumer, Logit):
|
|
89
|
+
return f64(flat[consumer.i])
|
|
90
|
+
return f64(flat)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _read(run: Any, consumer: Any) -> tuple[Any, str, tuple[float, Any]]:
|
|
94
|
+
"""The consumer's float64 value, its label, and ``(magnitude, dtype)`` of the native tensor
|
|
95
|
+
it came from (the spacing of ``verdict.decide``)."""
|
|
96
|
+
stop = consumer_stop(run, consumer)
|
|
97
|
+
if run.parse(stop) > run.parse(run.where):
|
|
98
|
+
run.until(stop)
|
|
99
|
+
info = run.read_info(stop)
|
|
100
|
+
native = run.read(stop)
|
|
101
|
+
return (consumer_value(consumer, native), info["authority"] or MEASURED,
|
|
102
|
+
(magnitude(consumer, native), native.dtype))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _layer_key(run: Any, edit: Edit) -> tuple[int, int]:
|
|
106
|
+
row, index = run.parse(edit.address)
|
|
107
|
+
layer = int(run.stops()[index].split(".", 1)[0][1:])
|
|
108
|
+
return row, layer
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _stage_key(run: Any, edit: Edit, p: Any) -> tuple[int, int]:
|
|
112
|
+
"""The order key of where an edit is staged: a cell at its plan's ``stage_at``, a port edit
|
|
113
|
+
in its layer (keyed by the layer's entry; a pending layer is staged at the cursor)."""
|
|
114
|
+
if edit.cell is not None:
|
|
115
|
+
return run.parse(p.stage_at)
|
|
116
|
+
row, layer = _layer_key(run, edit)
|
|
117
|
+
return run.parse(f"t{row}.L{layer}.h")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def measure(run: Any, edits: list[Edit], consumer: Any, *, probe: tuple[str, ...] = ()
|
|
121
|
+
) -> dict[str, Any]:
|
|
122
|
+
"""The consumer measured natively with every edit in ``edits`` applied (none: the base);
|
|
123
|
+
the session is restored and checked unchanged. Returns ``value`` (float64), ``authority``,
|
|
124
|
+
``moves``, and ``probed``: the native value at each ``probe`` address read at the consumer
|
|
125
|
+
(None where it cannot be read)."""
|
|
126
|
+
plans = [plan(run, edit, consumer) for edit in edits]
|
|
127
|
+
consumer_stop(run, consumer)
|
|
128
|
+
keys = [_stage_key(run, edit, p) for edit, p in zip(edits, plans)]
|
|
129
|
+
rewind = any(p.mode == "rewind" for p in plans)
|
|
130
|
+
if rewind and any(e.cell is not None and p.mode == "pending" for e, p in zip(edits, plans)):
|
|
131
|
+
raise Refusal("this set mixes a cell edit staged at the cursor with an edit that needs "
|
|
132
|
+
"stepping back: the cell would be staged earlier than at the cursor")
|
|
133
|
+
before = state_digest(run)
|
|
134
|
+
checkpoint = run.checkpoint()
|
|
135
|
+
_guard(run, [checkpoint])
|
|
136
|
+
moves: list[str] = []
|
|
137
|
+
try:
|
|
138
|
+
if rewind:
|
|
139
|
+
entry = min(keys)
|
|
140
|
+
while run.parse(run.where) >= entry:
|
|
141
|
+
run.reverse_step("layer")
|
|
142
|
+
moves.append(f"reverse-step layer to {run.where}")
|
|
143
|
+
order = sorted(range(len(edits)), key=lambda i: keys[i])
|
|
144
|
+
for i in order:
|
|
145
|
+
edit = edits[i]
|
|
146
|
+
if edit.cell is not None:
|
|
147
|
+
if run.parse(run.where) != keys[i]:
|
|
148
|
+
run.until(run.address(keys[i]))
|
|
149
|
+
moves.append(f"until {run.where}")
|
|
150
|
+
stage(run, edit)
|
|
151
|
+
moves.append(f"set {edit.address}")
|
|
152
|
+
continue
|
|
153
|
+
row, layer = _layer_key(run, edit)
|
|
154
|
+
status = run.status()
|
|
155
|
+
here = run.parse(run.where)
|
|
156
|
+
pending = (status["port"] is not None and status["pending_layer"] == layer
|
|
157
|
+
and here[0] == row)
|
|
158
|
+
if not pending:
|
|
159
|
+
run.until(f"t{row}.L{layer}.h")
|
|
160
|
+
moves.append(f"until t{row}.L{layer}.h")
|
|
161
|
+
run.set(edit.address, edit.value, edit.op, mask=edit.mask, selection=edit.selection,
|
|
162
|
+
origin=edit.origin)
|
|
163
|
+
moves.append(f"set {edit.address}" + (f"[{edit.selection}]" if edit.selection
|
|
164
|
+
else ""))
|
|
165
|
+
value, authority, scale = _read(run, consumer)
|
|
166
|
+
moves.append(f"read {consumer_stop(run, consumer)}")
|
|
167
|
+
probed = {address: _probe(run, address) for address in probe}
|
|
168
|
+
finally:
|
|
169
|
+
restore_exactly(run, checkpoint)
|
|
170
|
+
moves.append(f"restore {checkpoint['where']}")
|
|
171
|
+
after = state_digest(run)
|
|
172
|
+
if after != before:
|
|
173
|
+
raise RuntimeError(f"measure did not leave the session where it was ({before[:12]} -> "
|
|
174
|
+
f"{after[:12]})")
|
|
175
|
+
return {"value": value, "authority": authority, "moves": moves,
|
|
176
|
+
"scale": scale, "probed": probed}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _probe(run: Any, address: str) -> Any:
|
|
180
|
+
try:
|
|
181
|
+
return run.read(address).clone()
|
|
182
|
+
except (ValueError, KeyError, IndexError, RuntimeError):
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _ports(side: Side) -> tuple[str, ...]:
|
|
187
|
+
"""The port addresses a side's edits write (cell edits are not probed)."""
|
|
188
|
+
return tuple(e.address for e in side.edits or () if e.cell is None)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _informative(found: dict[str, Any], base: dict[str, Any], addresses: tuple[str, ...]
|
|
192
|
+
) -> int | None:
|
|
193
|
+
"""1 when a written port differs from the base's value there, 0 when none does, None when
|
|
194
|
+
nothing could be compared (``donors.informative``)."""
|
|
195
|
+
from ..numerics.pooling import informative
|
|
196
|
+
|
|
197
|
+
known = [informative(base["probed"].get(a), found.get("probed", {}).get(a))
|
|
198
|
+
for a in addresses]
|
|
199
|
+
known = [k for k in known if k is not None]
|
|
200
|
+
return int(any(known)) if known else None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def measure_at(run: Any, checkpoint: dict[str, Any], consumer: Any) -> dict[str, Any]:
|
|
204
|
+
"""The consumer measured natively from an in-memory checkpoint of this run; the session is
|
|
205
|
+
restored and checked unchanged."""
|
|
206
|
+
before = state_digest(run)
|
|
207
|
+
here = run.checkpoint()
|
|
208
|
+
_guard(run, [here, checkpoint])
|
|
209
|
+
try:
|
|
210
|
+
run.restore(checkpoint)
|
|
211
|
+
value, authority, scale = _read(run, consumer)
|
|
212
|
+
finally:
|
|
213
|
+
restore_exactly(run, here)
|
|
214
|
+
if state_digest(run) != before:
|
|
215
|
+
raise RuntimeError("measure_at did not leave the session where it was")
|
|
216
|
+
return {"value": value, "authority": authority, "scale": scale,
|
|
217
|
+
"moves": [f"restore {checkpoint['where']}", f"read {consumer_stop(run, consumer)}",
|
|
218
|
+
f"restore {here['where']}"]}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def measure_other(other: Any, consumer: Any) -> dict[str, Any]:
|
|
222
|
+
"""The consumer measured natively on another run (a durable checkpoint replayed)."""
|
|
223
|
+
value, authority, scale = _read(other, consumer)
|
|
224
|
+
return {"value": value, "authority": authority, "scale": scale,
|
|
225
|
+
"moves": [f"replay to {other.where}", f"read {consumer_stop(other, consumer)}"]}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@dataclass
|
|
229
|
+
class Side:
|
|
230
|
+
"""One branch of a comparison: ``edits`` (a list of ``Edit``), ``checkpoint`` (an
|
|
231
|
+
in-memory checkpoint of this run) or ``run`` (another run, e.g. a durable checkpoint
|
|
232
|
+
replayed); ``text`` names it."""
|
|
233
|
+
|
|
234
|
+
text: str
|
|
235
|
+
edits: list[Edit] | None = None
|
|
236
|
+
checkpoint: dict[str, Any] | None = None
|
|
237
|
+
run: Any = None
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _side(run: Any, side: Side, consumer: Any) -> dict[str, Any]:
|
|
241
|
+
if side.edits is not None:
|
|
242
|
+
return measure(run, side.edits, consumer, probe=_ports(side))
|
|
243
|
+
if side.checkpoint is not None:
|
|
244
|
+
return measure_at(run, side.checkpoint, consumer)
|
|
245
|
+
return measure_other(side.run, consumer)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _commute(x: Edit, y: Edit) -> bool:
|
|
249
|
+
"""Whether applying ``x`` then ``y`` at one port equals ``y`` then ``x`` (real arithmetic):
|
|
250
|
+
two adds, two scales, or two replaces with the same scalar value (a ``mix`` never)."""
|
|
251
|
+
if x.op == y.op and x.op in ("add", "scale"):
|
|
252
|
+
return True
|
|
253
|
+
return (x.op == y.op == "replace" and not hasattr(x.value, "shape")
|
|
254
|
+
and not hasattr(y.value, "shape") and float(x.value) == float(y.value))
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _cell_overlap(x: Edit, y: Edit) -> bool:
|
|
258
|
+
"""Whether two cell edits write a common element of one cache tensor."""
|
|
259
|
+
a, b = x.cell, y.cell
|
|
260
|
+
if (a["layer"], a["tensor"]) != (b["layer"], b["tensor"]):
|
|
261
|
+
return False
|
|
262
|
+
return all(a.get(key) is None or b.get(key) is None or set(a[key]) & set(b[key])
|
|
263
|
+
for key in ("rows", "kv", "d"))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _overlap(x: Edit, y: Edit) -> bool:
|
|
267
|
+
if x.cell is not None or y.cell is not None:
|
|
268
|
+
return x.cell is not None and y.cell is not None and _cell_overlap(x, y)
|
|
269
|
+
if x.mask is None or y.mask is None:
|
|
270
|
+
return True
|
|
271
|
+
import torch
|
|
272
|
+
|
|
273
|
+
return bool(torch.logical_and(x.mask, y.mask).any())
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _order_conflict(a: list[Edit], b: list[Edit]) -> str | None:
|
|
277
|
+
"""Why A+B is order-dependent (same port, overlapping masks, ops that do not commute)."""
|
|
278
|
+
for x in a:
|
|
279
|
+
for y in b:
|
|
280
|
+
same = (x.cell is not None and y.cell is not None) or x.address == y.address
|
|
281
|
+
if same and _overlap(x, y) and not _commute(x, y):
|
|
282
|
+
return (f"A and B both edit {x.address} on overlapping elements with ops that "
|
|
283
|
+
f"do not commute ({x.op}, {y.op}): A+B depends on the order")
|
|
284
|
+
return None
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _effect(value: Any) -> dict[str, Any]:
|
|
288
|
+
return claim(value, MEASURED)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def compare(run: Any, a: Side, b: Side, consumer: Any) -> dict[str, Any]:
|
|
292
|
+
"""Base, A, B and (both sides edits) A+B, each measured natively; effects and the
|
|
293
|
+
interaction ``(A+B) - A - B + base``. Returns ``report`` (bounded JSON) and ``values``
|
|
294
|
+
(float64 tensors)."""
|
|
295
|
+
before = state_digest(run)
|
|
296
|
+
written = {"A": _ports(a), "B": _ports(b)}
|
|
297
|
+
written["A+B"] = written["A"] + written["B"]
|
|
298
|
+
base = measure(run, [], consumer, probe=written["A+B"])
|
|
299
|
+
found = {"base": base, "A": _side(run, a, consumer), "B": _side(run, b, consumer)}
|
|
300
|
+
joint: str | None = None
|
|
301
|
+
if a.edits is not None and b.edits is not None:
|
|
302
|
+
joint = _order_conflict(a.edits, b.edits)
|
|
303
|
+
if joint is None:
|
|
304
|
+
found["A+B"] = measure(run, [*a.edits, *b.edits], consumer, probe=written["A+B"])
|
|
305
|
+
else:
|
|
306
|
+
joint = ("A+B needs both sides to be edits (a checkpoint is a whole session state, not "
|
|
307
|
+
"a change that composes)")
|
|
308
|
+
after = state_digest(run)
|
|
309
|
+
if after != before:
|
|
310
|
+
raise RuntimeError("compare did not leave the session where it was")
|
|
311
|
+
values = {name: item["value"] for name, item in found.items()}
|
|
312
|
+
vector = values["base"].dim() > 0
|
|
313
|
+
report: dict[str, Any] = {
|
|
314
|
+
"sides": {"A": a.text, "B": b.text},
|
|
315
|
+
"measured": {name: {"value": claim(item["value"], item["authority"]),
|
|
316
|
+
"moves": item["moves"]} for name, item in found.items()},
|
|
317
|
+
"effects": {"A": _effect(values["A"] - values["base"]),
|
|
318
|
+
"B": _effect(values["B"] - values["base"])},
|
|
319
|
+
"session": {"before": before, "after": after, "unchanged": True},
|
|
320
|
+
}
|
|
321
|
+
if joint is None:
|
|
322
|
+
report["order"] = ("A+B stages both sides' edits layer by layer; at one port A's edit "
|
|
323
|
+
"is applied before B's (where both edit one port, the ops commute)")
|
|
324
|
+
interaction = values["A+B"] - values["A"] - values["B"] + values["base"]
|
|
325
|
+
report["effects"]["A+B"] = _effect(values["A+B"] - values["base"])
|
|
326
|
+
report["interaction"] = {"value": _effect(interaction),
|
|
327
|
+
"formula": "(A+B) - A - B + base"}
|
|
328
|
+
values["interaction"] = interaction
|
|
329
|
+
else:
|
|
330
|
+
report["interaction"] = {"state": "refused", "reason": joint}
|
|
331
|
+
if a.edits is not None and b.edits is not None:
|
|
332
|
+
found_joint = {"state": "refused", "reason": joint}
|
|
333
|
+
report["measured"]["A+B"] = found_joint
|
|
334
|
+
report["effects"]["A+B"] = found_joint
|
|
335
|
+
# each effect natively: edited against base (compare has no exact or emulated chain)
|
|
336
|
+
report["verdicts"] = {}
|
|
337
|
+
for name in [n for n in ("A", "B", "A+B") if n in values]:
|
|
338
|
+
size = max(found[name]["scale"][0], found["base"]["scale"][0])
|
|
339
|
+
report["verdicts"][name] = decide(
|
|
340
|
+
values[name] - values["base"], None, size, found["base"]["scale"][1],
|
|
341
|
+
why_native_only="compare measures natively, with no exact or emulated chain",
|
|
342
|
+
donors=(1, _informative(found[name], base, written[name])))
|
|
343
|
+
report["kind"] = "vector" if vector else "scalar"
|
|
344
|
+
return {"report": report, "values": values}
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
__all__ = ["Side", "compare", "consumer_stop", "consumer_value", "measure", "measure_at",
|
|
348
|
+
"measure_other", "restore_exactly"]
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Donor counts on causal nulls (measured on real binaries).
|
|
2
|
+
|
|
3
|
+
On real binaries, where the answer key is exact, a single resample donor wrongly said "no effect"
|
|
4
|
+
on 41-71% of live cells (mean over the 32 single-donor choices), and among donors whose value
|
|
5
|
+
differed from the base's only 0-3.5% did (MEASURED). Almost all single-donor
|
|
6
|
+
nulls were identity interventions: the donor carried the base's own value. A null therefore says
|
|
7
|
+
what it rests on:
|
|
8
|
+
|
|
9
|
+
* every ``no effect`` carries ``donors = {n, informative}``: how many donors were measured and in
|
|
10
|
+
how many the patched value differed from the base's (bitwise). ``informative`` is ``None`` when
|
|
11
|
+
the caller could not compare the two values (a supplied number, a vector consumer only);
|
|
12
|
+
* ``label`` is the text a reader sees: ``no effect (1 donor)`` for one donor, ``no effect (16
|
|
13
|
+
donors, 12 informative)`` for several, ``no effect (1 donor, not informative: the donor value
|
|
14
|
+
equals the base)`` for an identity patch. A bare ``no effect`` is never printed.
|
|
15
|
+
|
|
16
|
+
Multi-donor mode (``whatif``, ``compare``, ``liveness`` and ``reads`` take ``donors=``; ``sweep``
|
|
17
|
+
takes several origins): one native measurement per donor, then ``pooled``: ``effect`` when at least one
|
|
18
|
+
donor's verdict is ``effect`` (the x86 method's liveness rule: live if >= 1 donor changes y),
|
|
19
|
+
``no effect`` when every donor was measured and none had one, else ``unresolved``. ``n_effect``
|
|
20
|
+
and ``n_informative`` are reported beside it, so "1 of 16" and "16 of 16" read differently.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from collections.abc import Callable, Sequence
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from ..numerics.pooling import EFFECT, NO_EFFECT, informative, pooled
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _value(donor: Any) -> tuple[Any, Any]:
|
|
32
|
+
"""``(value, origin pointer)`` of a donor: a ``ValueRef`` (pool or run), a tensor or a
|
|
33
|
+
number."""
|
|
34
|
+
if hasattr(donor, "value") and hasattr(donor, "pointer"):
|
|
35
|
+
return donor.value, dict(donor.pointer)
|
|
36
|
+
return donor, None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
_CELL = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def cell_sites(address: str, kv_heads: int | None = None) -> list[tuple[int, str, int, int]]:
|
|
43
|
+
"""``cache.L<l>.<k|v|kv>[kv<g>|kv*, row=<r>|<a>:<b>]`` -> ``(layer, tensor, row, kv)`` sites
|
|
44
|
+
(``kv`` = both tensors, ``kv*`` = every KV head, ``a:b`` = rows a..b-1). ``None`` when the
|
|
45
|
+
address is not a cache cell."""
|
|
46
|
+
import re
|
|
47
|
+
|
|
48
|
+
global _CELL
|
|
49
|
+
if _CELL is None:
|
|
50
|
+
_CELL = re.compile(r"cache\.L(?P<l>\d+)\.(?P<t>kv|k|v)\[kv(?P<g>\d+|\*),\s*"
|
|
51
|
+
r"row=(?P<a>\d+)(?::(?P<b>\d+))?\]$")
|
|
52
|
+
m = _CELL.match(address.strip())
|
|
53
|
+
if m is None:
|
|
54
|
+
return None
|
|
55
|
+
layer = int(m["l"])
|
|
56
|
+
tensors = ["k", "v"] if m["t"] == "kv" else [m["t"]]
|
|
57
|
+
if m["g"] == "*":
|
|
58
|
+
if kv_heads is None:
|
|
59
|
+
raise ValueError("kv* needs the number of KV heads")
|
|
60
|
+
heads = list(range(kv_heads))
|
|
61
|
+
else:
|
|
62
|
+
heads = [int(m["g"])]
|
|
63
|
+
a = int(m["a"])
|
|
64
|
+
rows = list(range(a, int(m["b"]))) if m["b"] is not None else [a]
|
|
65
|
+
return [(layer, t, r, g) for t in tensors for r in rows for g in heads]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def whatif_cells(run: Any, sites: Sequence[tuple[int, str, int, int]] | str, donors: Sequence[Any],
|
|
69
|
+
consumer: Any, *, batch: int = 32, stepped_logits: Any = None,
|
|
70
|
+
floor_spacings: float | None = None) -> dict[str, Any]:
|
|
71
|
+
"""Multi-donor cache-cell interchange at the run's pending row (request
|
|
72
|
+
``mdb-donors-whatif-cache-cells``): ``sites`` (``(layer, "k"|"v", row, kv)`` or a
|
|
73
|
+
``cache.L..`` address, see ``cell_sites``) take each donor's values; one native batched
|
|
74
|
+
forward per chunk through ``sweep.cell_sweep`` (the edited cells are read by the pending row
|
|
75
|
+
only, as a staged ``set_cell`` is). A donor is a ``Run`` (its cache at the same sites is read,
|
|
76
|
+
committed state) or a dict ``{site: tensor}``. ``consumer`` is a ``Margin`` of the pending
|
|
77
|
+
row. Per donor: ``delta`` = edited margin - null margin (the chunk's own null arm), ``floor``
|
|
78
|
+
= ``verdict.margin_floor`` at the null (2 spacings of the run dtype at the larger logit) plus
|
|
79
|
+
the measured ``null_vs_stepped`` when ``stepped_logits`` is given; ``effect`` when
|
|
80
|
+
``|delta| > floor`` else ``no effect`` (native only, no emulated chain); ``informative`` when
|
|
81
|
+
any patched cell differs bitwise from the base. Pooled with ``pooled``; ``n_flipped`` counts
|
|
82
|
+
donors whose margin has the other sign than the null's."""
|
|
83
|
+
from ..numerics.verdict import floors, margin_floor
|
|
84
|
+
from ..predict.consumers import Margin
|
|
85
|
+
from .sweep import Cell, cell_sweep
|
|
86
|
+
|
|
87
|
+
if isinstance(sites, str):
|
|
88
|
+
parsed = cell_sites(sites, int(run.adapter.num_kv_heads))
|
|
89
|
+
if parsed is None:
|
|
90
|
+
raise ValueError(f"not a cache cell address: {sites!r}")
|
|
91
|
+
sites = parsed
|
|
92
|
+
if not isinstance(consumer, Margin):
|
|
93
|
+
raise ValueError("whatif_cells measures a margin M[a,b] of the pending row")
|
|
94
|
+
sites = [tuple(s) for s in sites]
|
|
95
|
+
base = {}
|
|
96
|
+
for layer, tensor, row, kv in sites:
|
|
97
|
+
base[(layer, tensor, row, kv)] = run.read_cache(layer, tensor, staged=False)[0, kv, row]
|
|
98
|
+
arms, info = [], []
|
|
99
|
+
for donor in donors:
|
|
100
|
+
if isinstance(donor, dict):
|
|
101
|
+
vals = {tuple(k): v for k, v in donor.items()}
|
|
102
|
+
else:
|
|
103
|
+
vals = {s: donor.read_cache(s[0], s[1], staged=False)[0, s[3], s[2]] for s in sites}
|
|
104
|
+
arms.append([Cell(s[0], s[1], s[2], s[3], vals[s]) for s in sites])
|
|
105
|
+
info.append(any(informative(base[s], vals[s]) for s in sites))
|
|
106
|
+
tokens = [consumer.a, consumer.b]
|
|
107
|
+
out = cell_sweep(run, arms, tokens=tokens, batch=batch, stepped_logits=stepped_logits)
|
|
108
|
+
extra = float(out["null_vs_stepped"] or 0.0)
|
|
109
|
+
null = out["null"][0]
|
|
110
|
+
dtype = run.read_cache(0, "k", staged=False).dtype
|
|
111
|
+
kw = {} if floor_spacings is None else {"spacings": floor_spacings}
|
|
112
|
+
floor = margin_floor(null.to(dtype), 0, 1, extra=extra, **kw)
|
|
113
|
+
m0 = float(null[0] - null[1])
|
|
114
|
+
rows, per = [], []
|
|
115
|
+
for i, lg in enumerate(out["logits"]):
|
|
116
|
+
chunk_null = out["null"][i // batch]
|
|
117
|
+
m_null = float(chunk_null[0] - chunk_null[1])
|
|
118
|
+
m = float(lg[0] - lg[1])
|
|
119
|
+
delta = m - m_null
|
|
120
|
+
verdict = EFFECT if abs(delta) > floor else NO_EFFECT
|
|
121
|
+
rows.append({"verdict": verdict, "informative": info[i]})
|
|
122
|
+
per.append({"donor": i, "verdict": verdict, "informative": info[i], "margin": m,
|
|
123
|
+
"delta": delta, "floors": floors(delta, floor),
|
|
124
|
+
"flipped": (m > 0) != (m_null > 0)})
|
|
125
|
+
return {"sites": len(sites), "consumer": consumer.text, "margin": m0, "floor": floor,
|
|
126
|
+
"null_vs_stepped": out["null_vs_stepped"], **pooled(rows),
|
|
127
|
+
"n_flipped": sum(p["flipped"] for p in per), "per_donor": per,
|
|
128
|
+
"basis": "native batched cell_sweep; effect when |delta| > floor (2 dtype spacings at "
|
|
129
|
+
"the larger logit of the null + measured null_vs_stepped)"}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def whatif(run: Any, address: str, donors: Sequence[Any], consumer: Any, *, op: str = "replace",
|
|
133
|
+
mask: Any = None, selection: str | None = None, path: bool = False) -> dict[str, Any]:
|
|
134
|
+
"""``propagate.whatif`` once per donor value at ``address`` (``ValueRef`` from
|
|
135
|
+
``Pool.donors`` or ``Run.ref``, tensor or number); each verdict keeps its own P20 accounting
|
|
136
|
+
and donor stamp; the pooled verdict says how many donors were informative. ``path=True``
|
|
137
|
+
also runs ``paths.paired`` per donor (total and frozen-selection effects). A ``cache.L..``
|
|
138
|
+
cell address goes to ``whatif_cells`` (replace only; donors are runs or site dicts)."""
|
|
139
|
+
from ..predict.plan import Edit
|
|
140
|
+
from ..predict.whatif import whatif as one
|
|
141
|
+
|
|
142
|
+
if isinstance(address, str) and address.strip().startswith("cache."):
|
|
143
|
+
if op != "replace" or mask is not None or selection is not None or path:
|
|
144
|
+
raise ValueError("a cache-cell whatif takes replace donors only (no mask, selection "
|
|
145
|
+
"or path)")
|
|
146
|
+
return {"address": address, **whatif_cells(run, address, donors, consumer)}
|
|
147
|
+
rows, per = [], []
|
|
148
|
+
for i, donor in enumerate(donors):
|
|
149
|
+
value, origin = _value(donor)
|
|
150
|
+
result = one(run, Edit(address, value, op, mask=mask, selection=selection,
|
|
151
|
+
source=f"donor {i}", origin=origin), consumer)
|
|
152
|
+
effect = result.report["effect"]
|
|
153
|
+
k = (effect.get("donors") or {}).get("informative", {})
|
|
154
|
+
row = {"verdict": effect["verdict"], "informative": (bool(k["value"]) if "value" in k
|
|
155
|
+
else None)}
|
|
156
|
+
entry = {"donor": i, "verdict": effect["verdict"], "label": effect.get("label"),
|
|
157
|
+
"informative": row["informative"], "delta": result.report["measured"]["delta"],
|
|
158
|
+
"record": result.report["record"], "origin": origin}
|
|
159
|
+
if path:
|
|
160
|
+
from .paths import paired
|
|
161
|
+
|
|
162
|
+
report = paired(run, [(address, value, op, mask)], consumer)
|
|
163
|
+
row["path_diverged"] = report["path"]["diverged"]
|
|
164
|
+
entry["path"] = report
|
|
165
|
+
rows.append(row)
|
|
166
|
+
per.append(entry)
|
|
167
|
+
return {"address": address, "consumer": getattr(consumer, "text", str(consumer)),
|
|
168
|
+
**pooled(rows), "per_donor": per}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def compare(run: Any, sides: Callable[[Any], tuple[Any, Any]], donors: Sequence[Any],
|
|
172
|
+
consumer: Any) -> dict[str, Any]:
|
|
173
|
+
"""``compare.compare`` once per donor: ``sides(donor)`` builds the two ``compare.Side``s for
|
|
174
|
+
that donor. Each column (A, B, A+B) is pooled over donors."""
|
|
175
|
+
from .compare import compare as one
|
|
176
|
+
|
|
177
|
+
columns: dict[str, list[dict[str, Any]]] = {}
|
|
178
|
+
per = []
|
|
179
|
+
for i, donor in enumerate(donors):
|
|
180
|
+
a, b = sides(donor)
|
|
181
|
+
report = one(run, a, b, consumer)["report"]
|
|
182
|
+
per.append({"donor": i, "verdicts": {k: v.get("label", v["verdict"])
|
|
183
|
+
for k, v in report["verdicts"].items()}})
|
|
184
|
+
for name, v in report["verdicts"].items():
|
|
185
|
+
k = (v.get("donors") or {}).get("informative", {})
|
|
186
|
+
columns.setdefault(name, []).append(
|
|
187
|
+
{"verdict": v["verdict"], "informative": bool(k["value"]) if "value" in k
|
|
188
|
+
else None})
|
|
189
|
+
return {"consumer": getattr(consumer, "text", str(consumer)),
|
|
190
|
+
"columns": {name: pooled(rows) for name, rows in columns.items()}, "per_donor": per}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
__all__ = ["cell_sites", "compare", "whatif", "whatif_cells"]
|