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,393 @@
|
|
|
1
|
+
"""Forced-answer probes along a stored chain: ``suffix_sweep``.
|
|
2
|
+
|
|
3
|
+
``suffix_sweep(run, steps, suffix, n_prompt=..., bindings=..., letters=..., X=..., hint=...)``
|
|
4
|
+
reads, for every probe step ``k`` in ``steps``, the sequence ``run.tokens[:n_prompt + k] +
|
|
5
|
+
suffix`` at its answer row (the last suffix token), natively, without re-encoding the prefix:
|
|
6
|
+
the prefix cache of ``run.tokens[:n_prompt + max(steps)]`` is built once (one native forward),
|
|
7
|
+
and for each ``k`` (largest first) the cache is cropped to ``n_prompt + k`` rows and only the
|
|
8
|
+
suffix is run. Arms, at the answer row (all measured, FP32 eager, letter logits ``W[ids] . h``):
|
|
9
|
+
|
|
10
|
+
* ``native``: the suffix as is;
|
|
11
|
+
* ``M2``: the answer row's attention weights on the ``hint`` rows zeroed at every layer and head,
|
|
12
|
+
no renormalisation (= V cells of those rows zeroed for the answer row's pass only);
|
|
13
|
+
* ``CM1``: the same for the chain rows read so far (``n_prompt .. n_prompt + k - 1``);
|
|
14
|
+
* ``M3``: the hint rows' V cells zeroed for every suffix row (the suffix re-run).
|
|
15
|
+
|
|
16
|
+
The native answer row also yields, with hooks on the attention weights and the cached V cells,
|
|
17
|
+
the exact per-binding ``to_consumer`` and ``mass`` of the consumer ``M[X, R]`` (as
|
|
18
|
+
``rows.row_table`` at one row; bindings: the given prompt bindings plus ``chain_so_far`` and
|
|
19
|
+
``suffix``) and ``share = to_consumer / margin``. ``R`` is fixed for the whole sweep: given, or
|
|
20
|
+
the strongest letter other than ``X`` at the largest step's native answer row.
|
|
21
|
+
|
|
22
|
+
``null_steps``: at those steps the native answer letters are also read from a fresh forward of
|
|
23
|
+
the whole probe sequence (no cache) and ``null_vs_fresh_max_abs`` reports the largest letter
|
|
24
|
+
logit difference (the cache-reuse check).
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import time
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
from ..predict.consumers import Refusal
|
|
33
|
+
from .rows import (
|
|
34
|
+
LETTERS,
|
|
35
|
+
Trace,
|
|
36
|
+
_check_partition,
|
|
37
|
+
_masks,
|
|
38
|
+
consumer_backs,
|
|
39
|
+
crop_to,
|
|
40
|
+
decoder_parts,
|
|
41
|
+
head_groups,
|
|
42
|
+
letter_logits,
|
|
43
|
+
letter_setup,
|
|
44
|
+
rho_of,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
ARMS = ("native", "M2", "M3", "CM1")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def suffix_sweep(run: Any, steps: list[int], suffix: list[int], *, n_prompt: int,
|
|
51
|
+
bindings: dict[str, list[int]], letters: Any, X: str, R: str | None = None,
|
|
52
|
+
hint: str = "hint", arms: tuple[str, ...] = ARMS,
|
|
53
|
+
null_steps: tuple[int, ...] = ()) -> Trace:
|
|
54
|
+
"""Forced-answer probe trace over ``steps`` (module doc)."""
|
|
55
|
+
import torch
|
|
56
|
+
|
|
57
|
+
from mdb.engine.ports import check_deterministic
|
|
58
|
+
|
|
59
|
+
model = run.adapter.model
|
|
60
|
+
check_deterministic(model)
|
|
61
|
+
base, layers, norm = decoder_parts(run)
|
|
62
|
+
ids, names = letter_setup(run, letters, X, R)
|
|
63
|
+
xi = names.index(X)
|
|
64
|
+
bad = [a for a in arms if a not in ARMS]
|
|
65
|
+
if bad or "native" not in arms:
|
|
66
|
+
raise Refusal(f"arms are a subset of {', '.join(ARMS)} that includes native")
|
|
67
|
+
tokens = list(run.tokens)
|
|
68
|
+
chain_len = len(tokens) - n_prompt
|
|
69
|
+
steps = sorted({int(k) for k in steps}, reverse=True)
|
|
70
|
+
if not steps or steps[-1] < 0 or steps[0] > chain_len:
|
|
71
|
+
raise Refusal(f"probe steps must lie in 0..{chain_len}")
|
|
72
|
+
suffix = [int(t) for t in suffix]
|
|
73
|
+
if not suffix:
|
|
74
|
+
raise Refusal("a probe needs a suffix of at least one token")
|
|
75
|
+
binds = {b: sorted(int(r) for r in rows) for b, rows in bindings.items()}
|
|
76
|
+
_check_partition(binds, n_prompt)
|
|
77
|
+
if ("M2" in arms or "M3" in arms) and (hint not in binds or not binds[hint]):
|
|
78
|
+
raise Refusal(f"no {hint!r} binding to ablate")
|
|
79
|
+
device = next(model.parameters()).device
|
|
80
|
+
H, G, dh = head_groups(run)
|
|
81
|
+
per = H // G
|
|
82
|
+
S = len(suffix)
|
|
83
|
+
hint_index = torch.as_tensor(binds.get(hint, []), device=device, dtype=torch.long)
|
|
84
|
+
t0 = time.time()
|
|
85
|
+
with torch.no_grad():
|
|
86
|
+
cache = base(input_ids=torch.tensor([tokens[: n_prompt + steps[0]]], device=device),
|
|
87
|
+
use_cache=True).past_key_values
|
|
88
|
+
t_prefix = time.time() - t0
|
|
89
|
+
|
|
90
|
+
def run_tokens(toks: list[int], start: int) -> Any:
|
|
91
|
+
pos = torch.arange(start, start + len(toks), device=device)[None]
|
|
92
|
+
out = base(input_ids=torch.tensor([toks], device=device), past_key_values=cache,
|
|
93
|
+
position_ids=pos, use_cache=True)
|
|
94
|
+
return out.last_hidden_state[0, -1]
|
|
95
|
+
|
|
96
|
+
def normed(h: Any) -> Any:
|
|
97
|
+
return h # last_hidden_state is the final norm's output already
|
|
98
|
+
|
|
99
|
+
def zeroed(index: Any):
|
|
100
|
+
"""Zero V cells of ``index`` in the cache now; returns the restorer."""
|
|
101
|
+
saved = [layer.values[:, :, index].clone() for layer in cache.layers]
|
|
102
|
+
for layer in cache.layers:
|
|
103
|
+
layer.values[:, :, index] = 0
|
|
104
|
+
|
|
105
|
+
def restore() -> None:
|
|
106
|
+
for layer, keep in zip(cache.layers, saved):
|
|
107
|
+
layer.values[:, :, index] = keep
|
|
108
|
+
return restore
|
|
109
|
+
|
|
110
|
+
def shares_pass(toks_last: int, position: int, backs: list[Any], masks: Any) -> tuple:
|
|
111
|
+
"""The native answer row with hooks: letters, per-binding contrib and mass, total."""
|
|
112
|
+
store: dict[str, Any] = {}
|
|
113
|
+
nb = masks.shape[0]
|
|
114
|
+
contrib = torch.zeros(nb, dtype=torch.float64, device=device)
|
|
115
|
+
mass = torch.zeros(nb, dtype=torch.float64, device=device)
|
|
116
|
+
total = torch.zeros((), dtype=torch.float64, device=device)
|
|
117
|
+
hooks = []
|
|
118
|
+
|
|
119
|
+
def a_hook(mod, inp, out, li):
|
|
120
|
+
nonlocal total
|
|
121
|
+
p = out[1]
|
|
122
|
+
if p is None:
|
|
123
|
+
raise Refusal("the attention module returned no weights (eager attention needed)")
|
|
124
|
+
p = p[0, :, -1, :].double() # (H, cols)
|
|
125
|
+
v = cache.layers[li].values[0].double() # (G, cols, dh)
|
|
126
|
+
vb = torch.stack([v[h // per] @ backs[li][h] for h in range(H)]) # (H, cols)
|
|
127
|
+
pv = p * vb
|
|
128
|
+
contrib.add_(masks @ pv.sum(0))
|
|
129
|
+
mass.add_(masks @ p.sum(0))
|
|
130
|
+
total = total + pv.sum()
|
|
131
|
+
|
|
132
|
+
def n_hook(mod, inp, out):
|
|
133
|
+
store["pre"] = inp[0][0, -1]
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
for li, layer in enumerate(layers):
|
|
137
|
+
hooks.append(layer.self_attn.register_forward_hook(
|
|
138
|
+
lambda m, i, o, li=li: a_hook(m, i, o, li)))
|
|
139
|
+
hooks.append(norm.register_forward_hook(n_hook))
|
|
140
|
+
h = run_tokens([toks_last], position)
|
|
141
|
+
finally:
|
|
142
|
+
for hook in hooks:
|
|
143
|
+
hook.remove()
|
|
144
|
+
rho = rho_of(run, store["pre"])
|
|
145
|
+
return letter_logits(run, normed(h)[None], ids)[0], contrib * rho, mass, total * rho
|
|
146
|
+
|
|
147
|
+
if R is None:
|
|
148
|
+
with torch.no_grad():
|
|
149
|
+
n = n_prompt + steps[0]
|
|
150
|
+
crop_to(cache, n)
|
|
151
|
+
h = run_tokens(suffix, n)
|
|
152
|
+
top = letter_logits(run, normed(h)[None], ids)[0]
|
|
153
|
+
crop_to(cache, n)
|
|
154
|
+
R = names[max((j for j in range(len(names)) if j != xi), key=lambda j: float(top[j]))]
|
|
155
|
+
ri = names.index(R)
|
|
156
|
+
backs = consumer_backs(run, ids[xi], ids[ri])
|
|
157
|
+
records = []
|
|
158
|
+
null_diffs = {}
|
|
159
|
+
with torch.no_grad():
|
|
160
|
+
for k in steps:
|
|
161
|
+
ts = time.time()
|
|
162
|
+
n = n_prompt + k
|
|
163
|
+
crop_to(cache, n)
|
|
164
|
+
letters_of: dict[str, Any] = {}
|
|
165
|
+
if "M3" in arms:
|
|
166
|
+
restore = zeroed(hint_index)
|
|
167
|
+
h = run_tokens(suffix, n)
|
|
168
|
+
letters_of["M3"] = letter_logits(run, normed(h)[None], ids)[0]
|
|
169
|
+
crop_to(cache, n)
|
|
170
|
+
restore()
|
|
171
|
+
if S > 1:
|
|
172
|
+
run_tokens(suffix[:-1], n)
|
|
173
|
+
last = n + S - 1
|
|
174
|
+
cols = last + 1
|
|
175
|
+
binds_k = dict(binds)
|
|
176
|
+
binds_k["chain_so_far"] = list(range(n_prompt, n))
|
|
177
|
+
binds_k["suffix"] = list(range(n, cols))
|
|
178
|
+
masks = _masks(binds_k, cols, device)
|
|
179
|
+
nat, contrib, mass, total = shares_pass(suffix[-1], last, backs, masks)
|
|
180
|
+
letters_of["native"] = nat
|
|
181
|
+
crop_to(cache, last)
|
|
182
|
+
for arm, index in (("M2", hint_index),
|
|
183
|
+
("CM1", torch.arange(n_prompt, n, device=device))):
|
|
184
|
+
if arm not in arms:
|
|
185
|
+
continue
|
|
186
|
+
if arm == "CM1" and k == 0:
|
|
187
|
+
letters_of[arm] = nat # no chain rows: the arm is the native pass
|
|
188
|
+
continue
|
|
189
|
+
restore = zeroed(index)
|
|
190
|
+
h = run_tokens([suffix[-1]], last)
|
|
191
|
+
letters_of[arm] = letter_logits(run, normed(h)[None], ids)[0]
|
|
192
|
+
crop_to(cache, last)
|
|
193
|
+
restore()
|
|
194
|
+
if k in null_steps:
|
|
195
|
+
seq = tokens[:n] + suffix
|
|
196
|
+
fresh = base(input_ids=torch.tensor([seq], device=device)).last_hidden_state[0, -1]
|
|
197
|
+
null_diffs[k] = float((letter_logits(run, normed(fresh)[None], ids)[0]
|
|
198
|
+
- nat).abs().max())
|
|
199
|
+
margin = float(nat[xi] - nat[ri])
|
|
200
|
+
tc = {b: float(contrib[i]) for i, b in enumerate(binds_k)}
|
|
201
|
+
arm_name = {"M2": hint, "CM1": "chain_so_far", "M3": hint + "_suffix"}
|
|
202
|
+
records.append({
|
|
203
|
+
"step": k,
|
|
204
|
+
"frac": (k / chain_len) if chain_len else 1.0,
|
|
205
|
+
"letters": {a: [float(v) for v in lg] for a, lg in letters_of.items()},
|
|
206
|
+
"margin": margin,
|
|
207
|
+
"argmax_letter": names[int(nat.argmax())],
|
|
208
|
+
"to_consumer": tc,
|
|
209
|
+
"mass": {b: float(mass[i]) for i, b in enumerate(binds_k)},
|
|
210
|
+
"share": {b: (v / margin if margin != 0 else None) for b, v in tc.items()},
|
|
211
|
+
"attn_total": float(total),
|
|
212
|
+
"ablated": {arm_name[a]: float(lg[xi] - lg[ri])
|
|
213
|
+
for a, lg in letters_of.items() if a != "native"},
|
|
214
|
+
"ablated_argmax": {arm_name[a]: names[int(lg.argmax())]
|
|
215
|
+
for a, lg in letters_of.items() if a != "native"},
|
|
216
|
+
"seconds": round(time.time() - ts, 4),
|
|
217
|
+
})
|
|
218
|
+
cache = None # drop the prefix cache (the closures above read this name)
|
|
219
|
+
records.reverse() # probe order: k ascending
|
|
220
|
+
meta = {
|
|
221
|
+
"verb": "suffix_sweep", "n_prompt": n_prompt, "chain_len": chain_len, "suffix": suffix,
|
|
222
|
+
"X": X, "R": R, "letters": ids, "letter_names": names, "arms": list(arms),
|
|
223
|
+
"arm_tables": {"M2": hint, "CM1": "chain_so_far", "M3": hint + "_suffix"},
|
|
224
|
+
"labels": {"margin": "measured", "letters": "measured", "ablated": "measured",
|
|
225
|
+
"mass": "measured", "to_consumer": "derived-exact", "share": "derived-exact"},
|
|
226
|
+
"null_vs_fresh_max_abs": (max(null_diffs.values()) if null_diffs else None),
|
|
227
|
+
"null_vs_fresh": {str(k): v for k, v in null_diffs.items()},
|
|
228
|
+
"seconds": {"prefix": round(t_prefix, 3), "total": round(time.time() - t0, 3)},
|
|
229
|
+
}
|
|
230
|
+
return Trace("probe", records, meta, from_checkpoint=getattr(run, "from_checkpoint", None))
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
SPAN_MODES = ("mask", "zero", "mask_last")
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def span_mask(run: Any, spans: dict[str, list[int]], suffix: list[int], *, letters: Any, X: str,
|
|
237
|
+
modes: tuple[str, ...] = SPAN_MODES, batch: int = 32,
|
|
238
|
+
fresh_check: bool = True) -> Trace:
|
|
239
|
+
"""Answer-step span masking over a stored sequence, all arms batched.
|
|
240
|
+
|
|
241
|
+
The answer step is ``run.tokens + suffix``; its answer row is the last suffix row. The
|
|
242
|
+
prefix cache of ``run.tokens`` is built once; every (span, mode) arm then runs only the
|
|
243
|
+
suffix, ``batch`` arms per forward, against a batch copy of that cache. Modes, at every
|
|
244
|
+
layer and head (measured, letter logits ``W[ids] . h`` at the answer row):
|
|
245
|
+
|
|
246
|
+
* ``mask``: every suffix row's attention scores on the span's rows set to the dtype minimum
|
|
247
|
+
before the softmax (the weights renormalise over the other columns);
|
|
248
|
+
* ``zero``: every suffix row's weights on the span's rows zeroed after the softmax, no
|
|
249
|
+
renormalisation (= the span's V cells zeroed in the batch copy);
|
|
250
|
+
* ``mask_last``: ``mask`` for the answer row only (earlier suffix rows read natively).
|
|
251
|
+
|
|
252
|
+
Native answer row (one hooked pass): per span ``mass`` (sum over layers and heads of the
|
|
253
|
+
attention weight, divided by layers x heads) and ``vw_mass`` (sum of ``p[h, s] * ||W_O,h
|
|
254
|
+
v_s||`` over layers, heads and the span's rows, divided by the same sum over all columns:
|
|
255
|
+
the value-weighted read share). ``margin`` is ``logit[X] - max other letter``; ``delta`` per
|
|
256
|
+
mode is ``native margin - arm margin`` (positive: the span supported ``X``). A null arm (no
|
|
257
|
+
rows masked) checks the batched path (``null_max_abs``); ``fresh_check`` compares the native
|
|
258
|
+
letters with one cache-free forward of the whole sequence (``fresh_max_abs``).
|
|
259
|
+
"""
|
|
260
|
+
import copy
|
|
261
|
+
|
|
262
|
+
import torch
|
|
263
|
+
|
|
264
|
+
from mdb.engine.ports import check_deterministic
|
|
265
|
+
|
|
266
|
+
model = run.adapter.model
|
|
267
|
+
check_deterministic(model)
|
|
268
|
+
base, layers, _ = decoder_parts(run)
|
|
269
|
+
ids, names = letter_setup(run, letters, X, None)
|
|
270
|
+
xi = names.index(X)
|
|
271
|
+
bad = [m for m in modes if m not in SPAN_MODES]
|
|
272
|
+
if bad or not modes:
|
|
273
|
+
raise Refusal(f"modes are a non-empty subset of {', '.join(SPAN_MODES)}")
|
|
274
|
+
tokens = list(run.tokens)
|
|
275
|
+
T, S = len(tokens), len(suffix)
|
|
276
|
+
if not S:
|
|
277
|
+
raise Refusal("the answer step needs a suffix of at least one token")
|
|
278
|
+
spans = {str(n): sorted({int(r) for r in rows}) for n, rows in spans.items()}
|
|
279
|
+
for n, rows in spans.items():
|
|
280
|
+
if not rows or rows[0] < 0 or rows[-1] >= T:
|
|
281
|
+
raise Refusal(f"span {n} must name rows in 0..{T - 1}")
|
|
282
|
+
device = next(model.parameters()).device
|
|
283
|
+
dtype = next(model.parameters()).dtype
|
|
284
|
+
neg = torch.finfo(dtype).min
|
|
285
|
+
H, G, dh = head_groups(run)
|
|
286
|
+
per = H // G
|
|
287
|
+
L = len(layers)
|
|
288
|
+
t0 = time.time()
|
|
289
|
+
|
|
290
|
+
def margin_of(lg: Any) -> float:
|
|
291
|
+
others = [float(lg[j]) for j in range(len(names)) if j != xi]
|
|
292
|
+
return float(lg[xi]) - max(others)
|
|
293
|
+
|
|
294
|
+
pos = torch.arange(T, T + S, device=device)
|
|
295
|
+
with torch.no_grad():
|
|
296
|
+
cache = base(input_ids=torch.tensor([tokens], device=device), use_cache=True).past_key_values
|
|
297
|
+
caps: dict[int, Any] = {}
|
|
298
|
+
hooks = []
|
|
299
|
+
try:
|
|
300
|
+
for li, layer in enumerate(layers):
|
|
301
|
+
hooks.append(layer.self_attn.register_forward_hook(
|
|
302
|
+
lambda m, i, o, li=li: caps.__setitem__(li, o[1][0, :, -1, :].double())))
|
|
303
|
+
h = base(input_ids=torch.tensor([suffix], device=device), past_key_values=cache,
|
|
304
|
+
position_ids=pos[None], use_cache=True).last_hidden_state[0, -1]
|
|
305
|
+
finally:
|
|
306
|
+
for hook in hooks:
|
|
307
|
+
hook.remove()
|
|
308
|
+
if len(caps) != L or any(c is None for c in caps.values()):
|
|
309
|
+
raise Refusal("the attention modules returned no weights (eager attention needed)")
|
|
310
|
+
native = letter_logits(run, h[None], ids)[0]
|
|
311
|
+
cols = T + S
|
|
312
|
+
vw = torch.zeros(cols, dtype=torch.float64, device=device)
|
|
313
|
+
mass = torch.zeros(cols, dtype=torch.float64, device=device)
|
|
314
|
+
for li, layer in enumerate(layers):
|
|
315
|
+
v = cache.layers[li].values[0] # (G, cols, dh)
|
|
316
|
+
wo = layer.self_attn.o_proj.weight # (hidden, H * dh)
|
|
317
|
+
p = caps.pop(li) # (H, cols)
|
|
318
|
+
for hh in range(H):
|
|
319
|
+
w = wo[:, hh * dh:(hh + 1) * dh].double() # slice, then cast once
|
|
320
|
+
gram = w.T @ w
|
|
321
|
+
vg = v[hh // per].double()
|
|
322
|
+
norms = torch.einsum("cd,de,ce->c", vg, gram, vg).clamp_min(0).sqrt()
|
|
323
|
+
vw.add_(p[hh] * norms)
|
|
324
|
+
mass.add_(p[hh])
|
|
325
|
+
del w, gram, vg, norms
|
|
326
|
+
vw_total = float(vw.sum())
|
|
327
|
+
crop_to(cache, T)
|
|
328
|
+
t_native = time.time() - t0
|
|
329
|
+
|
|
330
|
+
arms = [(n, m) for n in spans for m in modes] + [(None, "null")]
|
|
331
|
+
causal = torch.zeros(S, T + S, dtype=dtype, device=device)
|
|
332
|
+
ii = torch.arange(S, device=device)
|
|
333
|
+
causal[:, T:] = torch.where(ii[None, :] <= ii[:, None], 0.0, neg)
|
|
334
|
+
results: dict[tuple, Any] = {}
|
|
335
|
+
for a in range(0, len(arms), batch):
|
|
336
|
+
sel = arms[a:a + batch]
|
|
337
|
+
B = len(sel)
|
|
338
|
+
bc = copy.deepcopy(cache)
|
|
339
|
+
for layer in bc.layers:
|
|
340
|
+
layer.keys = layer.keys.repeat(B, 1, 1, 1)
|
|
341
|
+
layer.values = layer.values.repeat(B, 1, 1, 1)
|
|
342
|
+
mask = causal[None, None].repeat(B, 1, 1, 1)
|
|
343
|
+
for b, (n, m) in enumerate(sel):
|
|
344
|
+
if n is None:
|
|
345
|
+
continue
|
|
346
|
+
index = torch.as_tensor(spans[n], device=device)
|
|
347
|
+
if m == "mask":
|
|
348
|
+
mask[b, 0][:, index] = neg
|
|
349
|
+
elif m == "mask_last":
|
|
350
|
+
mask[b, 0, S - 1, index] = neg
|
|
351
|
+
else:
|
|
352
|
+
for layer in bc.layers:
|
|
353
|
+
layer.values[b, :, index] = 0
|
|
354
|
+
out = base(input_ids=torch.tensor([suffix] * B, device=device), past_key_values=bc,
|
|
355
|
+
attention_mask=mask, position_ids=pos[None].expand(B, S), use_cache=True)
|
|
356
|
+
lg = letter_logits(run, out.last_hidden_state[:, -1], ids)
|
|
357
|
+
for b, arm in enumerate(sel):
|
|
358
|
+
results[arm] = lg[b]
|
|
359
|
+
del bc, out, mask, lg
|
|
360
|
+
null = results.pop((None, "null"))
|
|
361
|
+
fresh = None
|
|
362
|
+
if fresh_check:
|
|
363
|
+
hf = base(input_ids=torch.tensor([tokens + list(suffix)], device=device)).last_hidden_state[0, -1]
|
|
364
|
+
fresh = float((letter_logits(run, hf[None], ids)[0] - native).abs().max())
|
|
365
|
+
cache = None # drop the prefix cache (the closures above read this name)
|
|
366
|
+
nm = margin_of(native)
|
|
367
|
+
records = []
|
|
368
|
+
for n, rows in spans.items():
|
|
369
|
+
lgs = {m: results[(n, m)] for m in modes}
|
|
370
|
+
records.append({
|
|
371
|
+
"step": n, "rows": len(rows), "first_row": rows[0], "last_row": rows[-1],
|
|
372
|
+
"letters": {m: [float(x) for x in lg] for m, lg in lgs.items()},
|
|
373
|
+
"margin": {m: margin_of(lg) for m, lg in lgs.items()},
|
|
374
|
+
"delta": {m: nm - margin_of(lg) for m, lg in lgs.items()},
|
|
375
|
+
"argmax": {m: names[int(lg.argmax())] for m, lg in lgs.items()},
|
|
376
|
+
"mass": float(mass[rows].sum()) / (L * H),
|
|
377
|
+
"vw_mass": (float(vw[rows].sum()) / vw_total) if vw_total else None,
|
|
378
|
+
})
|
|
379
|
+
meta = {
|
|
380
|
+
"verb": "span_mask", "T": T, "suffix": list(suffix), "X": X, "letters": ids,
|
|
381
|
+
"letter_names": names, "modes": list(modes), "batch": batch,
|
|
382
|
+
"native_letters": [float(x) for x in native], "native_margin": nm,
|
|
383
|
+
"native_argmax": names[int(native.argmax())],
|
|
384
|
+
"null_max_abs": float((null - native).abs().max()), "fresh_max_abs": fresh,
|
|
385
|
+
"labels": {"letters": "measured", "margin": "measured", "delta": "measured",
|
|
386
|
+
"mass": "measured", "vw_mass": "measured"},
|
|
387
|
+
"seconds": {"native": round(t_native, 3), "total": round(time.time() - t0, 3)},
|
|
388
|
+
}
|
|
389
|
+
return Trace("span_mask", records, meta,
|
|
390
|
+
from_checkpoint=getattr(run, "from_checkpoint", None))
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
__all__ = ["ARMS", "LETTERS", "SPAN_MODES", "span_mask", "suffix_sweep"]
|