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,400 @@
|
|
|
1
|
+
"""All-rows reads: the per-row symbol accounting of one native forward, as a ``Trace``.
|
|
2
|
+
|
|
3
|
+
``row_table(run, bindings, letters=..., X=..., R=...)`` runs the run's whole token sequence once,
|
|
4
|
+
natively (FP32 eager, no cache), with hooks on every layer's ``v_proj`` output and attention
|
|
5
|
+
weights and on the final norm's input, and returns for every reader row ``t``:
|
|
6
|
+
|
|
7
|
+
* ``margin``: the native letter margin ``M[X,R] = logits_t[X] - logits_t[R]`` at row ``t`` (the
|
|
8
|
+
next-token lens; measured), ``letters`` (the letter logits) and ``argmax_letter``;
|
|
9
|
+
* per binding ``B``: ``mass[B]`` = sum over layers and heads of ``p[h, t, s]`` over ``s`` in
|
|
10
|
+
``B`` (the ``symbols`` mass), and ``to_consumer[B]`` = the exact direct contribution of row
|
|
11
|
+
``t``'s reads of ``B`` to the margin through the frozen final norm (P06/P07/P19 arithmetic of
|
|
12
|
+
``symbols._Grid``, vectorised over rows): ``rho_t * sum_{l,h,s in B} p[h,t,s] (v_s W_O,h^T
|
|
13
|
+
(gamma * (W_X - W_R)))``, with ``rho_t`` read from the final norm's input (derived-exact from
|
|
14
|
+
measured captures); ``share[B] = to_consumer[B] / margin``;
|
|
15
|
+
* per arm (``arms={"hint": cols, ...}``): ``ablated[arm]``, the native margin of row ``t`` when
|
|
16
|
+
row ``t``'s attention weights on the arm's columns are zeroed at every layer and head (no
|
|
17
|
+
renormalisation) for every row at once, each row's own read only (row ``t``'s inputs, the
|
|
18
|
+
cache rows ``< t``, are native). Measured with one masked forward per arm against the native
|
|
19
|
+
cache with the arm columns' V cells zeroed (zeroing ``p[h, t, s]`` and zeroing ``v_s`` give
|
|
20
|
+
the same row-``t`` output when only row ``t`` reads the changed cells); chunked over query
|
|
21
|
+
rows (``chunk``) to bound memory.
|
|
22
|
+
|
|
23
|
+
The bindings are whole-row column sets (``{name: [rows]}``); with ``bindings=None`` the run's
|
|
24
|
+
declared symbols are used (whole-row cells only). ``check=True`` also builds ``symbols.table``
|
|
25
|
+
at the run's last row (moving the run's cursor to ``t<last>.logits`` and declaring the bindings
|
|
26
|
+
there) and reports ``trace_check_max_abs``, the largest ``|to_consumer|`` difference.
|
|
27
|
+
|
|
28
|
+
This is the all-rows ``symbols`` that the prefilled-row refusal blocks: rows before
|
|
29
|
+
``first_row(run)`` are read from one native forward instead of the run's stepped trail.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
from ..predict.consumers import Margin, Refusal
|
|
38
|
+
|
|
39
|
+
LETTERS = "ABCDEFGH"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def crop_to(cache: Any, n: int) -> None:
|
|
43
|
+
"""Truncate a ``DynamicCache`` to ``n`` positions. transformers < 5.2x takes an absolute
|
|
44
|
+
length in ``crop``; newer releases reject positive values and take a negative count to
|
|
45
|
+
remove. A negative count is accepted by both, and growing is a no-op in both."""
|
|
46
|
+
drop = cache.get_seq_length() - n
|
|
47
|
+
if drop > 0:
|
|
48
|
+
cache.crop(-drop)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Trace:
|
|
53
|
+
"""A per-step (or per-row) readout table: ``records`` in order, each a dict with ``step``,
|
|
54
|
+
``margin``, ``argmax_letter``, ``letters`` and the tables ``to_consumer``, ``mass``,
|
|
55
|
+
``share`` and ``ablated`` (``{binding or arm: float}``); ``meta`` says how it was made
|
|
56
|
+
(labels, checks, timings). ``breakpoints.replay`` evaluates watch predicates over it.
|
|
57
|
+
``seal`` makes it a ``trace`` record; ``to_frame`` a long DataFrame."""
|
|
58
|
+
|
|
59
|
+
kind: str
|
|
60
|
+
records: list[dict[str, Any]]
|
|
61
|
+
meta: dict[str, Any] = field(default_factory=dict)
|
|
62
|
+
# the checkpoint the traced run is rooted at (``Run.from_checkpoint``): its seal carries it
|
|
63
|
+
from_checkpoint: dict[str, Any] | None = field(default=None, compare=False)
|
|
64
|
+
|
|
65
|
+
def column(self, table: str, key: str | None = None) -> list[Any]:
|
|
66
|
+
if key is None:
|
|
67
|
+
return [r.get(table) for r in self.records]
|
|
68
|
+
return [(r.get(table) or {}).get(key) for r in self.records]
|
|
69
|
+
|
|
70
|
+
def to_json(self) -> dict[str, Any]:
|
|
71
|
+
return {"kind": self.kind, "meta": self.meta, "records": self.records}
|
|
72
|
+
|
|
73
|
+
def seal(self, *, session_id: str, run: Any = None, store: Any = None,
|
|
74
|
+
**identity: Any) -> dict[str, Any]:
|
|
75
|
+
"""This trace as a sealed ``trace`` record (``analysis.symbols.sealed.seal_trace``): the
|
|
76
|
+
step records in a sha256-checked blob (``store``: a project or its store), so "sealed
|
|
77
|
+
before scoring" is a record, not a file time."""
|
|
78
|
+
from .sealed import seal_trace
|
|
79
|
+
|
|
80
|
+
return seal_trace(self, session_id=session_id, run=run, store=store, **identity)
|
|
81
|
+
|
|
82
|
+
def to_frame(self, table: str | None = None) -> Any:
|
|
83
|
+
"""The records as a long pandas DataFrame (``analysis.symbols.frame.trace_frame``)."""
|
|
84
|
+
from .frame import trace_frame
|
|
85
|
+
|
|
86
|
+
return trace_frame(self, table)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# --------------------------------------------------------------------------- shared helpers
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _torch():
|
|
93
|
+
import torch
|
|
94
|
+
return torch
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def decoder_parts(run: Any) -> tuple[Any, Any, Any]:
|
|
98
|
+
"""``(base, layers, final_norm)`` of a Qwen2/Llama-family causal LM, refusing others."""
|
|
99
|
+
model = run.adapter.model
|
|
100
|
+
base = getattr(model, "model", None)
|
|
101
|
+
if base is None or not hasattr(base, "layers") or not hasattr(base, "norm") \
|
|
102
|
+
or not hasattr(model, "lm_head"):
|
|
103
|
+
raise Refusal("all-rows reads need a decoder with model.layers, model.norm and lm_head")
|
|
104
|
+
impl = getattr(model.config, "_attn_implementation", "eager")
|
|
105
|
+
if impl != "eager":
|
|
106
|
+
raise Refusal(f"all-rows reads need eager attention (weights), not {impl!r}")
|
|
107
|
+
return base, base.layers, base.norm
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def letter_setup(run: Any, letters: Any, X: str, R: str | None) -> tuple[list[int], list[str]]:
|
|
111
|
+
ids = [int(t) for t in letters]
|
|
112
|
+
names = list(LETTERS[: len(ids)])
|
|
113
|
+
if X not in names or (R is not None and (R not in names or R == X)):
|
|
114
|
+
raise Refusal(f"X and R must be two different letters of {''.join(names)}")
|
|
115
|
+
return ids, names
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def consumer_backs(run: Any, a: int, b: int) -> list[Any]:
|
|
119
|
+
"""Per layer, ``(H, dh)`` float64: ``W_O,h^T (gamma * (W_a - W_b))`` for each head."""
|
|
120
|
+
torch = _torch()
|
|
121
|
+
model = run.adapter.model
|
|
122
|
+
cfg = model.config
|
|
123
|
+
_, layers, norm = decoder_parts(run)
|
|
124
|
+
H = cfg.num_attention_heads
|
|
125
|
+
dh = getattr(cfg, "head_dim", None) or cfg.hidden_size // H
|
|
126
|
+
w = model.lm_head.weight
|
|
127
|
+
gu = norm.weight.double() * (w[a].double() - w[b].double())
|
|
128
|
+
backs = []
|
|
129
|
+
for layer in layers:
|
|
130
|
+
wo = layer.self_attn.o_proj.weight.double().reshape(cfg.hidden_size, H, dh)
|
|
131
|
+
backs.append(torch.einsum("dhe,d->he", wo, gu))
|
|
132
|
+
return backs
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def head_groups(run: Any) -> tuple[int, int, int]:
|
|
136
|
+
cfg = run.adapter.model.config
|
|
137
|
+
H, G = cfg.num_attention_heads, cfg.num_key_value_heads
|
|
138
|
+
dh = getattr(cfg, "head_dim", None) or cfg.hidden_size // H
|
|
139
|
+
return H, G, dh
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def rho_of(run: Any, pre_norm: Any) -> Any:
|
|
143
|
+
"""RMSNorm scale ``rho = (mean(h^2) + eps)^-1/2`` of final-norm inputs (float64)."""
|
|
144
|
+
_, _, norm = decoder_parts(run)
|
|
145
|
+
eps = getattr(norm, "variance_epsilon", None) or getattr(norm, "eps")
|
|
146
|
+
return (pre_norm.double().pow(2).mean(-1) + eps) ** -0.5
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def letter_logits(run: Any, normed: Any, ids: list[int]) -> Any:
|
|
150
|
+
"""Letter logits ``W[ids] . h`` of final-norm outputs (rows x letters), float64."""
|
|
151
|
+
w = run.adapter.model.lm_head.weight[ids]
|
|
152
|
+
return (normed @ w.T).double()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _masks(bindings: dict[str, list[int]], T: int, device: Any) -> Any:
|
|
156
|
+
torch = _torch()
|
|
157
|
+
m = torch.zeros(len(bindings), T, dtype=torch.float64, device=device)
|
|
158
|
+
for i, rows in enumerate(bindings.values()):
|
|
159
|
+
if rows:
|
|
160
|
+
m[i, torch.as_tensor(rows, device=device)] = 1.0
|
|
161
|
+
return m
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _bindings_of(run: Any, bindings: dict[str, list[int]] | None) -> dict[str, list[int]]:
|
|
165
|
+
if bindings is not None:
|
|
166
|
+
return {name: sorted(int(r) for r in rows) for name, rows in bindings.items()}
|
|
167
|
+
from . import table as symbols
|
|
168
|
+
out = {}
|
|
169
|
+
for name, binding in symbols.declared(run).items():
|
|
170
|
+
rows = sorted({c.row for c in binding.cells})
|
|
171
|
+
if not all(binding.whole(r) for r in rows):
|
|
172
|
+
raise Refusal(f"symbol {name} holds partial rows; all-rows reads take whole rows")
|
|
173
|
+
out[name] = rows
|
|
174
|
+
if not out:
|
|
175
|
+
raise Refusal("no bindings: pass bindings= or declare symbols first")
|
|
176
|
+
return out
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _check_partition(bindings: dict[str, list[int]], T: int) -> None:
|
|
180
|
+
seen: dict[int, str] = {}
|
|
181
|
+
for name, rows in bindings.items():
|
|
182
|
+
for r in rows:
|
|
183
|
+
if not 0 <= r < T:
|
|
184
|
+
raise Refusal(f"binding {name} names row {r}, outside 0..{T - 1}")
|
|
185
|
+
if r in seen:
|
|
186
|
+
raise Refusal(f"bindings {seen[r]} and {name} overlap at row {r}")
|
|
187
|
+
seen[r] = name
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# --------------------------------------------------------------------------- row_table
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def row_table(run: Any, bindings: dict[str, list[int]] | None = None, *, letters: Any,
|
|
194
|
+
X: str, R: str, arms: dict[str, list[int]] | None = None, chunk: int = 512,
|
|
195
|
+
check: bool = False) -> Trace:
|
|
196
|
+
"""Per-row symbol accounting and per-row arm ablations over ``run.tokens`` (module doc)."""
|
|
197
|
+
torch = _torch()
|
|
198
|
+
import time
|
|
199
|
+
|
|
200
|
+
from mdb.engine.ports import check_deterministic
|
|
201
|
+
|
|
202
|
+
model = run.adapter.model
|
|
203
|
+
check_deterministic(model)
|
|
204
|
+
base, layers, norm = decoder_parts(run)
|
|
205
|
+
ids, names = letter_setup(run, letters, X, R)
|
|
206
|
+
xi, ri = names.index(X), names.index(R)
|
|
207
|
+
tokens = list(run.tokens)
|
|
208
|
+
T = len(tokens)
|
|
209
|
+
binds = _bindings_of(run, bindings)
|
|
210
|
+
_check_partition(binds, T)
|
|
211
|
+
arms = {k: sorted(int(r) for r in v) for k, v in (arms or {}).items()}
|
|
212
|
+
device = next(model.parameters()).device
|
|
213
|
+
H, G, dh = head_groups(run)
|
|
214
|
+
per = H // G
|
|
215
|
+
backs = consumer_backs(run, ids[xi], ids[ri])
|
|
216
|
+
masks = _masks(binds, T, device)
|
|
217
|
+
contrib = torch.zeros(len(binds), T, dtype=torch.float64, device=device)
|
|
218
|
+
mass = torch.zeros(len(binds), T, dtype=torch.float64, device=device)
|
|
219
|
+
total = torch.zeros(T, dtype=torch.float64, device=device)
|
|
220
|
+
store: dict[Any, Any] = {}
|
|
221
|
+
hooks = []
|
|
222
|
+
t0 = time.time()
|
|
223
|
+
|
|
224
|
+
def v_hook(mod, inp, out, li):
|
|
225
|
+
store[li] = out[0].double().reshape(T, G, dh)
|
|
226
|
+
|
|
227
|
+
def a_hook(mod, inp, out, li):
|
|
228
|
+
p = out[1]
|
|
229
|
+
if p is None:
|
|
230
|
+
raise Refusal("the attention module returned no weights (eager attention needed)")
|
|
231
|
+
v = store.pop(li) # (T, G, dh)
|
|
232
|
+
for h in range(H): # one head at a time: float64 (T, T) blocks, bounded memory
|
|
233
|
+
ph = p[0, h].double() # (T, T)
|
|
234
|
+
vb = v[:, h // per, :] @ backs[li][h] # (T,)
|
|
235
|
+
pv = ph * vb[None, :]
|
|
236
|
+
contrib.add_((pv @ masks.T).T)
|
|
237
|
+
total.add_(pv.sum(1))
|
|
238
|
+
mass.add_((ph @ masks.T).T)
|
|
239
|
+
del ph, pv
|
|
240
|
+
|
|
241
|
+
def n_hook(mod, inp, out):
|
|
242
|
+
store["pre"] = inp[0][0]
|
|
243
|
+
store["post"] = out[0]
|
|
244
|
+
|
|
245
|
+
try:
|
|
246
|
+
for li, layer in enumerate(layers):
|
|
247
|
+
hooks.append(layer.self_attn.v_proj.register_forward_hook(
|
|
248
|
+
lambda m, i, o, li=li: v_hook(m, i, o, li)))
|
|
249
|
+
hooks.append(layer.self_attn.register_forward_hook(
|
|
250
|
+
lambda m, i, o, li=li: a_hook(m, i, o, li)))
|
|
251
|
+
hooks.append(norm.register_forward_hook(n_hook))
|
|
252
|
+
with torch.no_grad():
|
|
253
|
+
out = base(input_ids=torch.tensor([tokens], device=device), use_cache=bool(arms))
|
|
254
|
+
finally:
|
|
255
|
+
for hook in hooks:
|
|
256
|
+
hook.remove()
|
|
257
|
+
rho = rho_of(run, store.pop("pre"))
|
|
258
|
+
native = letter_logits(run, store.pop("post"), ids) # (T, letters)
|
|
259
|
+
contrib *= rho[None]
|
|
260
|
+
total *= rho
|
|
261
|
+
t_native = time.time() - t0
|
|
262
|
+
ablated: dict[str, Any] = {}
|
|
263
|
+
if arms:
|
|
264
|
+
cache = out.past_key_values
|
|
265
|
+
for arm, cols in arms.items():
|
|
266
|
+
ablated[arm] = _row_ablation(run, cache, tokens, cols, ids, chunk)
|
|
267
|
+
del out
|
|
268
|
+
native = native.detach()
|
|
269
|
+
margin = native[:, xi] - native[:, ri]
|
|
270
|
+
records = []
|
|
271
|
+
names_b = list(binds)
|
|
272
|
+
for t in range(T):
|
|
273
|
+
m = float(margin[t])
|
|
274
|
+
tc = {b: float(contrib[i, t]) for i, b in enumerate(names_b)}
|
|
275
|
+
rec = {
|
|
276
|
+
"step": t,
|
|
277
|
+
"letters": [float(v) for v in native[t]],
|
|
278
|
+
"margin": m,
|
|
279
|
+
"argmax_letter": names[int(native[t].argmax())],
|
|
280
|
+
"to_consumer": tc,
|
|
281
|
+
"mass": {b: float(mass[i, t]) for i, b in enumerate(names_b)},
|
|
282
|
+
"share": {b: (v / m if m != 0 else None) for b, v in tc.items()},
|
|
283
|
+
"attn_total": float(total[t]),
|
|
284
|
+
"ablated": {a: float(v[t, xi] - v[t, ri]) for a, v in ablated.items()},
|
|
285
|
+
"ablated_argmax": {a: names[int(v[t].argmax())] for a, v in ablated.items()},
|
|
286
|
+
}
|
|
287
|
+
records.append(rec)
|
|
288
|
+
meta = {
|
|
289
|
+
"verb": "row_table", "T": T, "X": X, "R": R, "letters": ids,
|
|
290
|
+
"bindings": {b: _span(rows) for b, rows in binds.items()},
|
|
291
|
+
"arms": {a: _span(cols) for a, cols in arms.items()},
|
|
292
|
+
"labels": {"margin": "measured", "letters": "measured", "ablated": "measured",
|
|
293
|
+
"mass": "measured", "to_consumer": "derived-exact", "share": "derived-exact"},
|
|
294
|
+
"seconds": {"native": round(t_native, 3), "total": round(time.time() - t0, 3)},
|
|
295
|
+
"chunk": chunk,
|
|
296
|
+
}
|
|
297
|
+
if check:
|
|
298
|
+
meta["trace_check_max_abs"] = _check_against_symbols(run, binds, ids, xi, ri, records[-1])
|
|
299
|
+
return Trace("rows", records, meta, from_checkpoint=getattr(run, "from_checkpoint", None))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _span(rows: list[int]) -> Any:
|
|
303
|
+
if not rows:
|
|
304
|
+
return []
|
|
305
|
+
if rows == list(range(rows[0], rows[-1] + 1)):
|
|
306
|
+
return f"{rows[0]}:{rows[-1] + 1}"
|
|
307
|
+
return rows
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _row_ablation(run: Any, cache: Any, tokens: list[int], cols: list[int], ids: list[int],
|
|
311
|
+
chunk: int) -> Any:
|
|
312
|
+
"""Letter logits of every row with that row's reads of ``cols`` zeroed (module doc)."""
|
|
313
|
+
torch = _torch()
|
|
314
|
+
base, _, _ = decoder_parts(run)
|
|
315
|
+
device = next(base.parameters()).device
|
|
316
|
+
T = len(tokens)
|
|
317
|
+
out = torch.empty(T, len(ids), dtype=torch.float64, device=device)
|
|
318
|
+
if not cols:
|
|
319
|
+
raise Refusal("an arm needs at least one column")
|
|
320
|
+
index = torch.as_tensor(cols, device=device)
|
|
321
|
+
saved = [layer.values[:, :, index].clone() for layer in cache.layers]
|
|
322
|
+
for layer in cache.layers:
|
|
323
|
+
layer.values[:, :, index] = 0
|
|
324
|
+
neg = torch.finfo(next(base.parameters()).dtype).min
|
|
325
|
+
arm = set(cols)
|
|
326
|
+
try:
|
|
327
|
+
for a in range(0, T, chunk):
|
|
328
|
+
b = min(T, a + chunk)
|
|
329
|
+
C = b - a
|
|
330
|
+
rows = torch.arange(a, b, device=device)
|
|
331
|
+
mask = torch.full((C, T + C), neg, device=device)
|
|
332
|
+
mask[:, :T] = torch.where(torch.arange(T, device=device)[None, :] < rows[:, None],
|
|
333
|
+
0.0, neg)
|
|
334
|
+
mask[torch.arange(C, device=device), T + torch.arange(C, device=device)] = 0.0
|
|
335
|
+
# a row inside the arm reads its own value cell on the diagonal (the freshly
|
|
336
|
+
# appended V, which the zeroed cache rows do not cover): zero it there too, so the
|
|
337
|
+
# row's read of its own column is ablated like the stepped p-zero
|
|
338
|
+
own = [i for i in range(C) if a + i in arm]
|
|
339
|
+
with torch.no_grad(), _zero_appended_values(cache, own):
|
|
340
|
+
o = base(input_ids=torch.tensor([tokens[a:b]], device=device),
|
|
341
|
+
past_key_values=cache, attention_mask=mask[None, None],
|
|
342
|
+
position_ids=rows[None], use_cache=True)
|
|
343
|
+
out[a:b] = letter_logits(run, o.last_hidden_state[0], ids)
|
|
344
|
+
crop_to(cache, T)
|
|
345
|
+
del o
|
|
346
|
+
finally:
|
|
347
|
+
for layer, keep in zip(cache.layers, saved):
|
|
348
|
+
layer.values[:, :, index] = keep
|
|
349
|
+
return out
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
class _zero_appended_values:
|
|
353
|
+
"""While active, each cache layer's ``update`` zeroes the appended value rows ``own``
|
|
354
|
+
(positions within the appended chunk) before they are stored and read, leaving the keys
|
|
355
|
+
(so the row's weights, and the softmax, are unchanged: p-zero, no renormalisation)."""
|
|
356
|
+
|
|
357
|
+
def __init__(self, cache: Any, own: list[int]):
|
|
358
|
+
self.cache, self.own = cache, own
|
|
359
|
+
|
|
360
|
+
def __enter__(self):
|
|
361
|
+
if not self.own:
|
|
362
|
+
return self
|
|
363
|
+
own = self.own
|
|
364
|
+
|
|
365
|
+
def wrap(update):
|
|
366
|
+
def patched(key_states, value_states, *args, **kwargs):
|
|
367
|
+
value_states = value_states.clone()
|
|
368
|
+
value_states[:, :, own] = 0
|
|
369
|
+
return update(key_states, value_states, *args, **kwargs)
|
|
370
|
+
return patched
|
|
371
|
+
|
|
372
|
+
for layer in self.cache.layers:
|
|
373
|
+
layer.update = wrap(layer.update)
|
|
374
|
+
return self
|
|
375
|
+
|
|
376
|
+
def __exit__(self, *exc):
|
|
377
|
+
if self.own:
|
|
378
|
+
for layer in self.cache.layers:
|
|
379
|
+
del layer.update # back to the class method
|
|
380
|
+
return False
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _check_against_symbols(run: Any, binds: dict[str, list[int]], ids: list[int], xi: int,
|
|
384
|
+
ri: int, last: dict[str, Any]) -> float:
|
|
385
|
+
from . import binding as _binding
|
|
386
|
+
from . import table as symbols
|
|
387
|
+
|
|
388
|
+
row = len(run.tokens) - 1
|
|
389
|
+
run.until(f"t{row}.logits")
|
|
390
|
+
for name, rows in binds.items():
|
|
391
|
+
if rows:
|
|
392
|
+
_binding.declare(run, name, [f"t{s}" for s in rows])
|
|
393
|
+
tab = symbols.table(run, consumer=Margin(row, ids[xi], ids[ri]), limit=16)
|
|
394
|
+
worst = 0.0
|
|
395
|
+
for b in tab.report["bindings"]:
|
|
396
|
+
if b["symbol"] in last["to_consumer"]:
|
|
397
|
+
value = b["to_consumer"]
|
|
398
|
+
value = value["value"] if isinstance(value, dict) else value
|
|
399
|
+
worst = max(worst, abs(float(value) - last["to_consumer"][b["symbol"]]))
|
|
400
|
+
return worst
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Sealed traces, watch hits and circuit maps.
|
|
2
|
+
|
|
3
|
+
A ``rows.Trace`` was a plain dataclass and a frozen ``circuit_map.Map`` a JSON
|
|
4
|
+
file, so "sealed before scoring" rested on file times. Here each becomes a record:
|
|
5
|
+
|
|
6
|
+
* ``seal_trace(trace, ...)``: kind ``trace``. The per-step records are one sha256-checked
|
|
7
|
+
JSON blob (``core.bounded.put_json``; with no project store the bytes are held in memory on
|
|
8
|
+
the ``holder`` object); the record keeps the trace kind, the step count, the record columns,
|
|
9
|
+
a bounded ``meta`` (floats become ``measured`` claims) and the payload sha256.
|
|
10
|
+
* ``seal_watch_hits(result, trace_record, ...)``: kind ``watch-hits``, a
|
|
11
|
+
``breakpoints.replay`` result bound to the sealed trace it read (its record id), with the
|
|
12
|
+
per-step truth values in a blob.
|
|
13
|
+
* ``seal_map(m, ...)``: kind ``circuit-map``: the map's exact JSON is the blob (so
|
|
14
|
+
``Map.digest`` re-computes from it), the record holds the digest, slots, edges and candidate
|
|
15
|
+
set sizes, and optionally a ``MapTable`` blob.
|
|
16
|
+
|
|
17
|
+
``load_trace`` / ``load_map`` read a record back, checking the blob against the sha256 (and the
|
|
18
|
+
map against its digest). Values keep their labels; the record is the authority.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import numbers
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from mdb.core.bounded import load_json, put_json
|
|
27
|
+
from mdb.core.kinds import CIRCUIT_MAP, TRACE, WATCH_HITS # noqa: F401 (declares the kinds)
|
|
28
|
+
from mdb.core.records import seal_record
|
|
29
|
+
|
|
30
|
+
from ..numerics.labels import EXACT, MEASURED, num
|
|
31
|
+
|
|
32
|
+
TRACE_SCHEMA = "mdb-trace-v1"
|
|
33
|
+
WATCH_SCHEMA = "mdb-watch-hits-v1"
|
|
34
|
+
MAP_RECORD_SCHEMA = "mdb-circuit-map-record-v1"
|
|
35
|
+
_CAP = 64
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _safe(value: Any, authority: str = MEASURED) -> Any:
|
|
39
|
+
"""``value`` with every float made a claim and long lists cut to 64 items (record-safe)."""
|
|
40
|
+
if isinstance(value, bool) or value is None or isinstance(value, str):
|
|
41
|
+
return value
|
|
42
|
+
if isinstance(value, numbers.Integral):
|
|
43
|
+
return int(value) if value >= 0 else num(float(value), authority)
|
|
44
|
+
if isinstance(value, numbers.Real):
|
|
45
|
+
return num(float(value), authority)
|
|
46
|
+
if isinstance(value, dict):
|
|
47
|
+
return {str(k): _safe(v, authority) for k, v in value.items()}
|
|
48
|
+
if isinstance(value, (list, tuple)):
|
|
49
|
+
items = [_safe(v, authority) for v in list(value)[:_CAP]]
|
|
50
|
+
return items
|
|
51
|
+
return str(value)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _store_of(project: Any) -> Any:
|
|
55
|
+
return None if project is None else getattr(project, "store", project)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _identity(run: Any = None, model_identity: Any = None, execution: Any = None):
|
|
59
|
+
if run is not None:
|
|
60
|
+
return run.adapter.model_identity, dict(run.adapter.execution)
|
|
61
|
+
if model_identity is None:
|
|
62
|
+
raise ValueError("give run= or model_identity= (and execution=)")
|
|
63
|
+
return model_identity, dict(execution or {})
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def seal_trace(trace: Any, *, session_id: str, run: Any = None, model_identity: Any = None,
|
|
67
|
+
execution: Any = None, store: Any = None, holder: Any = None) -> dict[str, Any]:
|
|
68
|
+
"""A ``trace`` record of ``trace`` (``rows.Trace``) with its records as a blob."""
|
|
69
|
+
identity, exe = _identity(run, model_identity, execution)
|
|
70
|
+
payload = put_json({"kind": trace.kind, "meta": trace.meta, "records": trace.records},
|
|
71
|
+
store=_store_of(store), run=holder if holder is not None else run)
|
|
72
|
+
columns = sorted({k for r in trace.records for k in r})
|
|
73
|
+
body = {"schema": TRACE_SCHEMA, "trace_kind": trace.kind, "count": len(trace.records),
|
|
74
|
+
"meta": _safe(trace.meta), "columns": {"names": columns[:_CAP],
|
|
75
|
+
"count": len(columns)},
|
|
76
|
+
"payload": payload, "sha256": payload["sha256"]}
|
|
77
|
+
return seal_record(session_id=session_id, kind="trace", model_identity=identity,
|
|
78
|
+
execution=exe, authority=MEASURED, body=body, run=run if run is not None else trace.from_checkpoint)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def load_trace(record: dict[str, Any], *, store: Any = None, holder: Any = None) -> Any:
|
|
82
|
+
"""The ``rows.Trace`` of a sealed ``trace`` record (blob checked against its sha256)."""
|
|
83
|
+
from .rows import Trace
|
|
84
|
+
|
|
85
|
+
if record.get("kind") != "trace":
|
|
86
|
+
raise ValueError(f"not a trace record (kind {record.get('kind')!r})")
|
|
87
|
+
data = load_json(record["body"]["payload"], store=_store_of(store), run=holder)
|
|
88
|
+
return Trace(data["kind"], data["records"], data["meta"])
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def seal_watch_hits(result: dict[str, Any], trace_record: dict[str, Any], *, session_id: str,
|
|
92
|
+
store: Any = None, holder: Any = None) -> dict[str, Any]:
|
|
93
|
+
"""A ``watch-hits`` record of a ``breakpoints.replay`` result over a sealed trace."""
|
|
94
|
+
payload = put_json({"holds": result["holds"], "hits": result["hits"],
|
|
95
|
+
"undefined": result["undefined"]}, store=_store_of(store), run=holder)
|
|
96
|
+
hits = [h for h in result["hits"] if isinstance(h, int) and h >= 0]
|
|
97
|
+
body = {"schema": WATCH_SCHEMA, "trace": trace_record["id"],
|
|
98
|
+
"predicate": result["predicate"], "mode": result["mode"], "n": int(result["n"]),
|
|
99
|
+
"hits": hits[:_CAP], "hits_omitted": max(0, len(hits) - _CAP),
|
|
100
|
+
"fired_at": result["fired_at"] if isinstance(result["fired_at"], int) else None,
|
|
101
|
+
"fired_index": result["fired_index"],
|
|
102
|
+
"crossings": int(result["crossings"]),
|
|
103
|
+
"undefined": [u for u in result["undefined"] if isinstance(u, int)][:_CAP],
|
|
104
|
+
"payload": payload}
|
|
105
|
+
if result.get("fired_fraction") is not None:
|
|
106
|
+
body["fired_fraction"] = num(float(result["fired_fraction"]), EXACT)
|
|
107
|
+
return seal_record(session_id=session_id, kind="watch-hits",
|
|
108
|
+
model_identity=trace_record["model_identity"],
|
|
109
|
+
execution=trace_record["execution"], authority=EXACT, body=body)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def seal_map(m: Any, *, session_id: str, run: Any = None, model_identity: Any = None,
|
|
113
|
+
execution: Any = None, store: Any = None, holder: Any = None,
|
|
114
|
+
table: Any = None) -> dict[str, Any]:
|
|
115
|
+
"""A ``circuit-map`` record of ``m`` (``circuit_map.Map``); ``table``: a ``MapTable`` (its
|
|
116
|
+
rows go in a second blob)."""
|
|
117
|
+
identity, exe = _identity(run, model_identity, execution)
|
|
118
|
+
data = m.to_json()
|
|
119
|
+
payload = put_json(data, store=_store_of(store), run=holder if holder is not None else run)
|
|
120
|
+
body: dict[str, Any] = {
|
|
121
|
+
"schema": MAP_RECORD_SCHEMA, "map_schema": data["schema"], "digest": m.digest(),
|
|
122
|
+
"slots": [{k: (list(v) if isinstance(v, tuple) else v) for k, v in s.items()}
|
|
123
|
+
for s in data["slots"]][:_CAP],
|
|
124
|
+
"edges": data["edges"][:_CAP],
|
|
125
|
+
"candidate_sets": [{"name": k, "size": len(v)} for k, v in data["candidate_sets"].items()],
|
|
126
|
+
"payload": payload}
|
|
127
|
+
if "n_items" in data["constants"]:
|
|
128
|
+
body["n_items"] = int(data["constants"]["n_items"])
|
|
129
|
+
if table is not None:
|
|
130
|
+
body["table"] = put_json(table.to_json(), store=_store_of(store),
|
|
131
|
+
run=holder if holder is not None else run)
|
|
132
|
+
return seal_record(session_id=session_id, kind="circuit-map", model_identity=identity,
|
|
133
|
+
execution=exe, authority=EXACT, body=body, run=run)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def load_map(record: dict[str, Any], *, store: Any = None, holder: Any = None) -> Any:
|
|
137
|
+
"""The ``circuit_map.Map`` of a sealed ``circuit-map`` record; ``ValueError`` when the blob
|
|
138
|
+
fails its sha256 or the map's digest differs from the sealed one."""
|
|
139
|
+
from .circuit_map import Map
|
|
140
|
+
|
|
141
|
+
if record.get("kind") != "circuit-map":
|
|
142
|
+
raise ValueError(f"not a circuit-map record (kind {record.get('kind')!r})")
|
|
143
|
+
m = Map.from_json(load_json(record["body"]["payload"], store=_store_of(store), run=holder))
|
|
144
|
+
if m.digest() != record["body"]["digest"]:
|
|
145
|
+
raise ValueError("the stored map's digest differs from the sealed digest")
|
|
146
|
+
return m
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
__all__ = ["load_map", "load_trace", "seal_map", "seal_trace", "seal_watch_hits"]
|