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,227 @@
|
|
|
1
|
+
"""Novelty of a candidate intermediate: is a cell's value new, or a re-encoding of the input?
|
|
2
|
+
|
|
3
|
+
A forecast or an interchange test names a causal unit next to the consumer. On a shortcut program
|
|
4
|
+
(no intermediate is ever computed) that unit is the input itself, and multi-donor interchange
|
|
5
|
+
still confirms it causal. What separates a bridge from a
|
|
6
|
+
re-encoded input is a cross-item test of the unit's *value*. This module holds that test and the
|
|
7
|
+
walk that applies it along a reads graph.
|
|
8
|
+
|
|
9
|
+
``bridge_share``: for one cell address aligned across N items (``values[i]`` the cell's value on
|
|
10
|
+
item ``i``, ``None`` where the item has no such cell), each item's
|
|
11
|
+
|
|
12
|
+
share_i = 1 - mean ||v_i - v_j||^2 over same-bridge partners j (another descriptor)
|
|
13
|
+
/ mean ||v_i - v_k||^2 over different-bridge partners k of the same family
|
|
14
|
+
|
|
15
|
+
``share`` is the part of the cell's cross-item variation that the bridge label explains, with the
|
|
16
|
+
family (prompt template) held fixed in the denominator: 1 when same-bridge items carry the same
|
|
17
|
+
value, 0 when a same-bridge partner is no closer than any other item of the family, negative when
|
|
18
|
+
it is farther. With unique descriptors, ``1 - share`` is the descriptor-specific part, so
|
|
19
|
+
``share >= 0.5`` reads "explained more by the bridge than by the descriptor".
|
|
20
|
+
|
|
21
|
+
``novelty``: the verdict of each item at one cell, against a ``reference`` representation of the
|
|
22
|
+
same items' input (for a language model: the descriptor's token embeddings; for a program: the
|
|
23
|
+
input bytes). The cell is ``novel`` when ``share >= min_share`` and ``share - share_ref >=
|
|
24
|
+
min_gain``: the bridge structure is in the cell and was not already in the input. ``input
|
|
25
|
+
re-encoding`` when the share passes but the input already carries it (a shortcut whose input names
|
|
26
|
+
the bridge has ``share_ref = 1``, so nothing downstream of it can be novel). ``no bridge code``
|
|
27
|
+
when ``share < min_share``. ``undecidable`` when the item has no same-bridge or no
|
|
28
|
+
different-bridge partner, or no cell.
|
|
29
|
+
|
|
30
|
+
The answer clause (not a re-encoding of the answer) needs items where bridge and answer
|
|
31
|
+
partitions differ. ``answer_separable`` reports whether they do; when the answer is a one-to-one
|
|
32
|
+
function of the bridge on the given items, the clause cannot be decided from identities and the
|
|
33
|
+
verdict says so instead of passing it silently.
|
|
34
|
+
|
|
35
|
+
``walk_back``: breadth-first along a caller-supplied ``parents`` function from a start node
|
|
36
|
+
(a forecast's cell) to the first node whose ``passes`` is true, visiting each step's parents in
|
|
37
|
+
the order given. Returns the node, the step, the visit order and the passing nodes seen.
|
|
38
|
+
|
|
39
|
+
Labels: every share is ``derived-exact`` from the supplied values (float64); the verdict is a rule
|
|
40
|
+
applied to it. Importing this module does not import torch.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
from __future__ import annotations
|
|
44
|
+
|
|
45
|
+
from collections.abc import Callable, Hashable, Sequence
|
|
46
|
+
from typing import Any
|
|
47
|
+
|
|
48
|
+
NOVEL, INPUT, NO_CODE, UNDECIDABLE = ("novel", "input re-encoding", "no bridge code",
|
|
49
|
+
"undecidable")
|
|
50
|
+
RULE = ("novel when share >= min_share and share - share_ref >= min_gain; share = 1 - mean sq "
|
|
51
|
+
"distance to same-bridge partners / mean sq distance to different-bridge same-family "
|
|
52
|
+
"items")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _torch():
|
|
56
|
+
import torch
|
|
57
|
+
|
|
58
|
+
return torch
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _stack(values: Sequence[Any]) -> tuple[Any, list[bool]]:
|
|
62
|
+
"""(N, d) float64 tensor with zero rows where a value is missing, and the presence mask."""
|
|
63
|
+
torch = _torch()
|
|
64
|
+
present = [v is not None for v in values]
|
|
65
|
+
if not any(present):
|
|
66
|
+
return torch.zeros(len(values), 1, dtype=torch.float64), present
|
|
67
|
+
d = next(torch.as_tensor(v).numel() for v in values if v is not None)
|
|
68
|
+
out = torch.zeros(len(values), d, dtype=torch.float64)
|
|
69
|
+
for i, v in enumerate(values):
|
|
70
|
+
if v is not None:
|
|
71
|
+
out[i] = torch.as_tensor(v).reshape(-1).to(torch.float64).cpu()
|
|
72
|
+
return out, present
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def bridge_share(values: Sequence[Any], bridge: Sequence[Hashable], family: Sequence[Hashable],
|
|
76
|
+
*, items: Sequence[int] | None = None) -> list[dict[str, Any]]:
|
|
77
|
+
"""Per-item bridge share of one aligned cell (module docstring). ``items``: the indices to
|
|
78
|
+
score (default all); every index with a value is a partner."""
|
|
79
|
+
torch = _torch()
|
|
80
|
+
n = len(values)
|
|
81
|
+
if not (len(bridge) == len(family) == n):
|
|
82
|
+
raise ValueError("values, bridge and family need one entry per item")
|
|
83
|
+
x, present = _stack(values)
|
|
84
|
+
d2 = torch.cdist(x, x).pow(2)
|
|
85
|
+
code = {}
|
|
86
|
+
b = torch.tensor([code.setdefault(v, len(code)) for v in bridge])
|
|
87
|
+
fcode = {}
|
|
88
|
+
f = torch.tensor([fcode.setdefault(v, len(fcode)) for v in family])
|
|
89
|
+
p = torch.tensor(present)
|
|
90
|
+
both = p[:, None] & p[None, :]
|
|
91
|
+
same = (b[:, None] == b[None, :]) & both & ~torch.eye(n, dtype=torch.bool)
|
|
92
|
+
diff = (b[:, None] != b[None, :]) & (f[:, None] == f[None, :]) & both
|
|
93
|
+
ns, nd = same.sum(1), diff.sum(1)
|
|
94
|
+
ds = (d2 * same).sum(1) / ns.clamp(min=1)
|
|
95
|
+
dd = (d2 * diff).sum(1) / nd.clamp(min=1)
|
|
96
|
+
out = []
|
|
97
|
+
for i in (range(n) if items is None else items):
|
|
98
|
+
if not present[i]:
|
|
99
|
+
out.append({"item": i, "share": None, "n_same": 0, "n_diff": 0, "reason": "no cell"})
|
|
100
|
+
continue
|
|
101
|
+
row = {"item": i, "n_same": int(ns[i]), "n_diff": int(nd[i])}
|
|
102
|
+
if not ns[i] or not nd[i]:
|
|
103
|
+
row.update(share=None, reason="no same-bridge partner" if not ns[i]
|
|
104
|
+
else "no different-bridge item in the family")
|
|
105
|
+
elif float(dd[i]) == 0.0:
|
|
106
|
+
row.update(share=None, reason="all different-bridge items carry the same value")
|
|
107
|
+
else:
|
|
108
|
+
row.update(share=1.0 - float(ds[i]) / float(dd[i]), same_sq=float(ds[i]),
|
|
109
|
+
diff_sq=float(dd[i]))
|
|
110
|
+
out.append(row)
|
|
111
|
+
return out
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def answer_separable(bridge: Sequence[Hashable], answer: Sequence[Hashable]) -> bool:
|
|
115
|
+
"""Whether the answer partition differs from the bridge partition on these items (some pair
|
|
116
|
+
shares one label but not the other)."""
|
|
117
|
+
b2a: dict[Hashable, set] = {}
|
|
118
|
+
a2b: dict[Hashable, set] = {}
|
|
119
|
+
for b, a in zip(bridge, answer):
|
|
120
|
+
b2a.setdefault(b, set()).add(a)
|
|
121
|
+
a2b.setdefault(a, set()).add(b)
|
|
122
|
+
return any(len(s) > 1 for s in b2a.values()) or any(len(s) > 1 for s in a2b.values())
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def novelty(values: Sequence[Any], reference: Sequence[Any], bridge: Sequence[Hashable],
|
|
126
|
+
family: Sequence[Hashable], *, answer: Sequence[Hashable] | None = None,
|
|
127
|
+
items: Sequence[int] | None = None, min_share: float = 0.5,
|
|
128
|
+
min_gain: float = 0.25, reference_shares: Sequence[dict] | None = None
|
|
129
|
+
) -> list[dict[str, Any]]:
|
|
130
|
+
"""Per-item novelty verdict of one aligned cell (module docstring). ``reference``: the
|
|
131
|
+
items' input representation (ignored when ``reference_shares``, a previous
|
|
132
|
+
``bridge_share(reference, ...)`` over all items, is given). ``answer``: the answer labels;
|
|
133
|
+
when separable from the bridge, the cell must also beat the answer share by ``min_gain``."""
|
|
134
|
+
idx = list(range(len(values))) if items is None else list(items)
|
|
135
|
+
cell = bridge_share(values, bridge, family, items=idx)
|
|
136
|
+
ref_all = (reference_shares if reference_shares is not None
|
|
137
|
+
else bridge_share(reference, bridge, family))
|
|
138
|
+
ref = {r["item"]: r for r in ref_all}
|
|
139
|
+
sep = answer is not None and answer_separable(bridge, answer)
|
|
140
|
+
ans = {r["item"]: r for r in bridge_share(values, answer, family, items=idx)} if sep else {}
|
|
141
|
+
out = []
|
|
142
|
+
for row in cell:
|
|
143
|
+
i = row["item"]
|
|
144
|
+
r = ref.get(i, {})
|
|
145
|
+
share, sref = row.get("share"), r.get("share")
|
|
146
|
+
res = {"item": i, "share": share, "share_ref": sref, "n_same": row["n_same"],
|
|
147
|
+
"n_diff": row["n_diff"]}
|
|
148
|
+
if answer is None:
|
|
149
|
+
res["answer_clause"] = "not given"
|
|
150
|
+
elif not sep:
|
|
151
|
+
res["answer_clause"] = ("not decidable: the answer is a one-to-one function of the "
|
|
152
|
+
"bridge on these items")
|
|
153
|
+
else:
|
|
154
|
+
res["share_answer"] = ans[i].get("share")
|
|
155
|
+
if share is None or sref is None:
|
|
156
|
+
res["verdict"] = UNDECIDABLE
|
|
157
|
+
res["reason"] = row.get("reason") or r.get("reason") or "no reference"
|
|
158
|
+
elif share < min_share:
|
|
159
|
+
res["verdict"] = NO_CODE
|
|
160
|
+
elif share - sref < min_gain:
|
|
161
|
+
res["verdict"] = INPUT
|
|
162
|
+
elif sep and res.get("share_answer") is not None and share - res["share_answer"] < min_gain:
|
|
163
|
+
res["verdict"] = "answer re-encoding"
|
|
164
|
+
else:
|
|
165
|
+
res["verdict"] = NOVEL
|
|
166
|
+
res["gain"] = None if share is None or sref is None else share - sref
|
|
167
|
+
out.append(res)
|
|
168
|
+
return out
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def permutation_null(values: Sequence[Any], bridge: Sequence[Hashable],
|
|
172
|
+
family: Sequence[Hashable], *, n: int = 200, seed: int = 0) -> dict:
|
|
173
|
+
"""Median item share with bridge labels shuffled within each family (``n`` shuffles): the
|
|
174
|
+
share a cell gets from the label structure alone. Returns the per-shuffle medians' median,
|
|
175
|
+
5th and 95th percentiles."""
|
|
176
|
+
import random
|
|
177
|
+
import statistics
|
|
178
|
+
|
|
179
|
+
rng = random.Random(seed)
|
|
180
|
+
meds = []
|
|
181
|
+
fams: dict[Hashable, list[int]] = {}
|
|
182
|
+
for i, f in enumerate(family):
|
|
183
|
+
fams.setdefault(f, []).append(i)
|
|
184
|
+
for _ in range(n):
|
|
185
|
+
shuffled = list(bridge)
|
|
186
|
+
for idx in fams.values():
|
|
187
|
+
labels = [bridge[i] for i in idx]
|
|
188
|
+
rng.shuffle(labels)
|
|
189
|
+
for i, b in zip(idx, labels):
|
|
190
|
+
shuffled[i] = b
|
|
191
|
+
shares = [r["share"] for r in bridge_share(values, shuffled, family)
|
|
192
|
+
if r.get("share") is not None]
|
|
193
|
+
if shares:
|
|
194
|
+
meds.append(statistics.median(shares))
|
|
195
|
+
if not meds:
|
|
196
|
+
return {"n": 0}
|
|
197
|
+
meds.sort()
|
|
198
|
+
pick = lambda q: meds[min(len(meds) - 1, int(q * len(meds)))] # noqa: E731
|
|
199
|
+
return {"n": len(meds), "median": statistics.median(meds), "p05": pick(0.05),
|
|
200
|
+
"p95": pick(0.95)}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def walk_back(start: Hashable, parents: Callable[[Hashable], Sequence[Hashable]],
|
|
204
|
+
passes: Callable[[Hashable], bool], *, max_steps: int = 64) -> dict[str, Any]:
|
|
205
|
+
"""Breadth-first walk from ``start`` (step 0) through ``parents`` to the first node whose
|
|
206
|
+
``passes`` is true. Each step's frontier is the parents of the previous frontier, in order,
|
|
207
|
+
without repeats. Returns ``{"found", "node", "step", "visited": [(node, step, passed)]}``."""
|
|
208
|
+
frontier, seen, visited = [start], {start}, []
|
|
209
|
+
for step in range(max_steps + 1):
|
|
210
|
+
nxt = []
|
|
211
|
+
for node in frontier:
|
|
212
|
+
ok = bool(passes(node))
|
|
213
|
+
visited.append((node, step, ok))
|
|
214
|
+
if ok:
|
|
215
|
+
return {"found": True, "node": node, "step": step, "visited": visited}
|
|
216
|
+
for p in parents(node):
|
|
217
|
+
if p not in seen:
|
|
218
|
+
seen.add(p)
|
|
219
|
+
nxt.append(p)
|
|
220
|
+
if not nxt:
|
|
221
|
+
break
|
|
222
|
+
frontier = nxt
|
|
223
|
+
return {"found": False, "node": None, "step": None, "visited": visited}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
__all__ = ["INPUT", "NOVEL", "NO_CODE", "RULE", "UNDECIDABLE", "answer_separable",
|
|
227
|
+
"bridge_share", "novelty", "permutation_null", "walk_back"]
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""``path-diverged`` for transformers (measured first on binaries).
|
|
2
|
+
|
|
3
|
+
On the binaries, 60-85% of aligned-resample patches of branch-feeding cells changed the control
|
|
4
|
+
path (MEASURED); read as data effects they would have been misread. The
|
|
5
|
+
transformer analogue of a branch outcome is an attention selection: the source a head weights
|
|
6
|
+
most. After an edit at row ``r``, layer ``l``, the downstream selections are the ``p`` rows of
|
|
7
|
+
every head at every row ``>= r`` from the first layer the edit reaches (``l`` for a port that
|
|
8
|
+
computes before ``p`` in the layer, else ``l + 1``).
|
|
9
|
+
|
|
10
|
+
``paired(run, edits, consumer)`` measures from one branch point (``Branches``, stepped):
|
|
11
|
+
|
|
12
|
+
* ``total``: the edits, run free to the consumer;
|
|
13
|
+
* ``frozen``: the same edits with every downstream ``p`` held at the reference's (the unedited
|
|
14
|
+
continuation's) pattern, ``hold t*.L>=k.p`` (``engine.holds``): only values flow, selections
|
|
15
|
+
are the base's;
|
|
16
|
+
|
|
17
|
+
and reads the argmax of every downstream ``p`` row on the base and on the free arm (Branches
|
|
18
|
+
probes). ``path.diverged`` when any argmax moved. A row whose top two weights are equal in either
|
|
19
|
+
run is a tie and is not counted (``ties`` gives how many). ``first`` names the earliest moved
|
|
20
|
+
selection in execution order (row, then layer, then head), ``moved`` counts moved (row, layer,
|
|
21
|
+
head) selections and ``heads`` the distinct (layer, head). ``verdict``: ``path-diverged`` when
|
|
22
|
+
diverged, else the free arm's ``effect`` / ``no effect`` against the Branches floor. The total
|
|
23
|
+
and frozen effects are always both reported: when a path diverged, their gap is what the moved
|
|
24
|
+
selections carried.
|
|
25
|
+
|
|
26
|
+
``argmax_rows`` and ``diverged`` are plain functions on tensors so batched drivers decide
|
|
27
|
+
divergence with the same rule.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
from collections.abc import Sequence
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
from ..numerics.labels import MEASURED, num
|
|
36
|
+
|
|
37
|
+
RULE = ("path-diverged when the argmax over sources of any downstream p row (heads x rows >= the "
|
|
38
|
+
"edit row x layers the edit reaches) differs between the base and the edited run; rows "
|
|
39
|
+
"whose top two weights tie in either run are not counted")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _torch():
|
|
43
|
+
import torch
|
|
44
|
+
|
|
45
|
+
return torch
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def argmax_rows(p: Any) -> Any:
|
|
49
|
+
"""``p`` [..., sources] -> the argmax per row, ``-1`` where the top two weights tie."""
|
|
50
|
+
torch = _torch()
|
|
51
|
+
flat = p.reshape(-1, p.shape[-1]).float()
|
|
52
|
+
if flat.shape[-1] < 2:
|
|
53
|
+
return torch.zeros(flat.shape[0], dtype=torch.long, device=flat.device)
|
|
54
|
+
top = flat.topk(2, dim=-1)
|
|
55
|
+
return torch.where(top.values[:, 0] > top.values[:, 1], top.indices[:, 0], -1)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def diverged(base: Any, edited: Any, names: Sequence[str] | None = None) -> dict[str, Any]:
|
|
59
|
+
"""Compare two argmax tensors of the same shape (``argmax_rows`` per selection, in execution
|
|
60
|
+
order along the first axis; ``names[i]`` names selection ``i``)."""
|
|
61
|
+
torch = _torch()
|
|
62
|
+
base, edited = torch.as_tensor(base).reshape(-1), torch.as_tensor(edited).reshape(-1)
|
|
63
|
+
tie = (base < 0) | (edited < 0)
|
|
64
|
+
moved = (base != edited) & ~tie
|
|
65
|
+
idx = torch.nonzero(moved).flatten().tolist()
|
|
66
|
+
out = {"diverged": bool(idx), "moved": len(idx), "ties": int(tie.sum()),
|
|
67
|
+
"selections": int(base.numel()), "rule": RULE}
|
|
68
|
+
if idx and names is not None:
|
|
69
|
+
out["first"] = names[idx[0]]
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def first_layer(run: Any, port: str, layer: int) -> int:
|
|
74
|
+
"""The first layer whose ``p`` an edit at ``L<layer>.<port>`` reaches."""
|
|
75
|
+
names = run.program.names
|
|
76
|
+
return layer if names.index(port) < names.index("p") else layer + 1
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _site(run: Any, address: str) -> tuple[int, int, str]:
|
|
80
|
+
head, _, _ = address.partition("[")
|
|
81
|
+
row, layer, port = head.split(".")
|
|
82
|
+
return int(row[1:]), int(layer[1:]), port
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def paired(run: Any, edits: Sequence[Any], consumer: Any, *, name: str = "paired"
|
|
86
|
+
) -> dict[str, Any]:
|
|
87
|
+
"""Total and frozen-selection effects of ``edits`` (``branches.Edit`` or ``(address,
|
|
88
|
+
value, op, mask)``; port edits of one row) at ``consumer``, with the path report (module
|
|
89
|
+
docstring). The run is left where it was."""
|
|
90
|
+
from .branches import Branches, edit
|
|
91
|
+
|
|
92
|
+
edits = [e if hasattr(e, "target") else edit(e[0], e[1], e[2], mask=e[3]) for e in edits]
|
|
93
|
+
sites = [_site(run, e.target) for e in edits]
|
|
94
|
+
row = min(r for r, _, _ in sites)
|
|
95
|
+
start = min(first_layer(run, port, layer) for r, layer, port in sites if r == row)
|
|
96
|
+
entry_layer = min(layer for r, layer, _ in sites if r == row)
|
|
97
|
+
last = int(getattr(consumer, "row", row))
|
|
98
|
+
rows = list(range(row, last + 1))
|
|
99
|
+
layers = list(range(start, run.adapter.layers))
|
|
100
|
+
names = [f"t{r}.L{l}.p[h{h}]" for r in rows for l in layers
|
|
101
|
+
for h in range(run.adapter.num_heads)]
|
|
102
|
+
|
|
103
|
+
def probe(r: Any) -> list[float]:
|
|
104
|
+
torch = _torch()
|
|
105
|
+
if not layers:
|
|
106
|
+
return []
|
|
107
|
+
found = [argmax_rows(r.read(f"t{x}.L{l}.p")) for x in rows for l in layers]
|
|
108
|
+
return torch.cat(found).double().tolist()
|
|
109
|
+
|
|
110
|
+
where = run.where
|
|
111
|
+
br = Branches(run, consumer, at=f"t{row}.L{entry_layer}.h", name=name,
|
|
112
|
+
probes={"argmax": probe})
|
|
113
|
+
try:
|
|
114
|
+
br.add("total", edits)
|
|
115
|
+
if layers:
|
|
116
|
+
br.add("frozen", edits, holds=[f"t*.L>={start}.p"])
|
|
117
|
+
found = {r["name"]: r for r in br.run()}
|
|
118
|
+
finally:
|
|
119
|
+
br.restore()
|
|
120
|
+
if run.where != where:
|
|
121
|
+
(run.until if run.parse(where) > run.parse(run.where) else run.rewind)(where)
|
|
122
|
+
total = found["total"]
|
|
123
|
+
frozen = found.get("frozen", total)
|
|
124
|
+
base_ids = [int(v["value"]) for v in br.base_probes.get("argmax", [])]
|
|
125
|
+
free_ids = [int(v["value"]) for v in total.get("probes", {}).get("argmax", [])]
|
|
126
|
+
path = diverged(base_ids, free_ids, names) if layers else {
|
|
127
|
+
"diverged": False, "moved": 0, "ties": 0, "selections": 0, "rule": RULE,
|
|
128
|
+
"note": "no layer downstream of the edit computes p"}
|
|
129
|
+
if path["moved"]:
|
|
130
|
+
torch = _torch()
|
|
131
|
+
moved = (torch.tensor(base_ids) != torch.tensor(free_ids)) & (torch.tensor(base_ids) >= 0) \
|
|
132
|
+
& (torch.tensor(free_ids) >= 0)
|
|
133
|
+
path["heads"] = len({names[i].split(".", 1)[1] for i in torch.nonzero(moved).flatten()
|
|
134
|
+
.tolist()})
|
|
135
|
+
above = bool(total.get("above_floor", total["dM"]["value"] != 0))
|
|
136
|
+
verdict = "path-diverged" if path["diverged"] else ("effect" if above else "no effect")
|
|
137
|
+
return {"verdict": verdict, "path": path,
|
|
138
|
+
"total": {"dM": total["dM"], "above_floor": total.get("above_floor")},
|
|
139
|
+
"frozen": {"dM": frozen["dM"], "above_floor": frozen.get("above_floor"),
|
|
140
|
+
"holds": f"t*.L>={start}.p at the reference" if layers else "none"},
|
|
141
|
+
"frozen_minus_total": num(frozen["dM"]["value"] - total["dM"]["value"], MEASURED),
|
|
142
|
+
"floor": total.get("floor"), "consumer": br.text, "layers": [start, len(layers)],
|
|
143
|
+
"rows": [row, last]}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
__all__ = ["RULE", "argmax_rows", "diverged", "first_layer", "paired"]
|