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,436 @@
|
|
|
1
|
+
"""Component bindings: a value cell split into named parts by a feature basis.
|
|
2
|
+
|
|
3
|
+
A value cell ``cache.L<l>.v[kv<g>,row=<r>]`` of a model with no V norm is a linear image of the
|
|
4
|
+
residual entering layer ``l`` at row ``r`` (``h = t<r>.L<l>.h``):
|
|
5
|
+
|
|
6
|
+
v_lin = W_V^g (rho gamma * h) (+ b_V^g), rho = (mean(h^2) + eps)^-1/2 at the native h
|
|
7
|
+
|
|
8
|
+
(Qwen3: no V bias and no v_norm, checked here; a V bias is its own ``v_bias`` component). A
|
|
9
|
+
residual feature basis whose site holds ``h`` (Qwen-Scope ``resid_post`` of layer ``l - 1``)
|
|
10
|
+
splits ``h = b_dec + sum_f a_f d_f + e`` exactly (``sae.FeatureBasis.decompose``), so
|
|
11
|
+
|
|
12
|
+
v_lin = sum_f v_f + v_bdec + v_err (+ b_V^g), v_f = W_V^g (rho gamma * a_f d_f)
|
|
13
|
+
|
|
14
|
+
in float64, every term at the same native ``rho``. A ``ComponentBinding`` holds those parts
|
|
15
|
+
for one cell: one component per listed feature (``feature[f]``), the rest of the active
|
|
16
|
+
features lumped (``other_features``), the decoder bias (``bdec``) and the error (``error``, the
|
|
17
|
+
cell's ``Unbound``). ``closure`` is ``|sum of components - v_lin|`` (float64 summation only);
|
|
18
|
+
``rounding`` is ``v_native - v_lin`` (the bf16 V projection against its float64 image,
|
|
19
|
+
measured, never folded into a component).
|
|
20
|
+
|
|
21
|
+
At fixed attention weights the cell reaches a scalar consumer read at row ``j`` through the
|
|
22
|
+
heads of KV group ``g`` only (P06/P07): ``to_consumer(v) = sum_{h in kappa^-1(g)} p[h, r]
|
|
23
|
+
c . W_O,h v`` with ``c`` the consumer's readout vector (P19). It is linear in ``v``, so the
|
|
24
|
+
components' shares add to the cell's (``derived-exact``); ``mass`` (``sum_h p[h, r]``) is the
|
|
25
|
+
cell's and is reported as inherited. ``content`` reads each component's write
|
|
26
|
+
``sum_h p[h, r] W_O,h v_i`` through ``symbols.content``.
|
|
27
|
+
|
|
28
|
+
Offline: ``component_binding`` needs ``h = t<r>.L<l>.h`` and the native cell, which a live run
|
|
29
|
+
has only for a row it stepped. ``ResidualCapture`` saves ``h`` at declared (row, layer) pairs
|
|
30
|
+
(and, optionally, the native value cache of those layers) from a run, to disk if wanted
|
|
31
|
+
(``save``/``load``); ``component_binding(None, ..., capture=cap, adapter=adapter)`` then builds
|
|
32
|
+
the same binding with no forward pass. K/V-only captures cannot: ``h`` is not recoverable from
|
|
33
|
+
them. ``ComponentBinding.provenance`` says where ``h`` and the native cell came from.
|
|
34
|
+
|
|
35
|
+
Refusals: row 0 (the first token is off a residual SAE's training distribution, Qwen-Scope
|
|
36
|
+
report section 2.2; ``sae.FIRST_ROW_CAVEAT``), a prefilled row (its residual was never
|
|
37
|
+
stopped at), a basis whose site does not hold ``h``, a model with a V norm.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import re
|
|
43
|
+
from dataclasses import dataclass, field
|
|
44
|
+
from typing import Any
|
|
45
|
+
|
|
46
|
+
from ..numerics.labels import EXACT, MEASURED, f64, num
|
|
47
|
+
from ..predict.consumers import Refusal
|
|
48
|
+
from .binding import Binding, Candidates
|
|
49
|
+
from .table import content, readout_basis
|
|
50
|
+
|
|
51
|
+
_CELL = re.compile(r"^cache\.L(\d+)\.v\[kv(\d+),row=(\d+)\]$")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _torch():
|
|
55
|
+
import torch
|
|
56
|
+
|
|
57
|
+
return torch
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class ResidualCapture:
|
|
62
|
+
"""The residual ``h = t<r>.L<l>.h`` at declared (row, layer) pairs, native dtype, and
|
|
63
|
+
optionally the native value cache (``values[l]``: (1, H_KV, T, d_h)) of the captured layers.
|
|
64
|
+
``provenance`` records where they were read (``Run.read`` / ``Run.read_cache(staged=False)``,
|
|
65
|
+
the tokens and the cursor at capture); ``adapter`` is only needed to build a binding."""
|
|
66
|
+
|
|
67
|
+
h: dict[tuple[int, int], Any] = field(default_factory=dict)
|
|
68
|
+
values: dict[int, Any] = field(default_factory=dict)
|
|
69
|
+
provenance: dict[str, Any] = field(default_factory=dict)
|
|
70
|
+
adapter: Any = None
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def from_run(cls, run: Any, rows: list[int], layers: list[int], *,
|
|
74
|
+
values: bool = True) -> "ResidualCapture":
|
|
75
|
+
"""Save ``h`` of every (row, layer) in ``rows x layers`` the run has stepped, and (with
|
|
76
|
+
``values``) the committed value cache of those layers. Refuses a row the run prefilled
|
|
77
|
+
or has not reached (its residual was never stopped at)."""
|
|
78
|
+
here = int(run.where.split(".")[0][1:])
|
|
79
|
+
cap = cls(adapter=run.adapter)
|
|
80
|
+
for row in rows:
|
|
81
|
+
if int(row) < int(run.first_row) or int(row) > here:
|
|
82
|
+
raise Refusal(f"t{row}: not stepped by this run (first stepped row "
|
|
83
|
+
f"t{run.first_row}, cursor {run.where})")
|
|
84
|
+
for layer in layers:
|
|
85
|
+
cap.h[(int(row), int(layer))] = run.read(f"t{row}.L{layer}.h").detach().clone()
|
|
86
|
+
if values:
|
|
87
|
+
for layer in layers:
|
|
88
|
+
cap.values[int(layer)] = run.read_cache(int(layer), "v",
|
|
89
|
+
staged=False).detach().clone()
|
|
90
|
+
cap.provenance = {"h": "Run.read(t<r>.L<l>.h) at capture", "rows": [int(r) for r in rows],
|
|
91
|
+
"layers": [int(x) for x in layers], "cursor": run.where,
|
|
92
|
+
"values": "Run.read_cache(v, staged=False)" if values else None,
|
|
93
|
+
"tokens": [int(t) for t in run.session.read("tokens")[0].tolist()]}
|
|
94
|
+
return cap
|
|
95
|
+
|
|
96
|
+
def save(self, path: str) -> None:
|
|
97
|
+
_torch().save({"h": {f"{r}.{l}": v for (r, l), v in self.h.items()},
|
|
98
|
+
"values": {str(l): v for l, v in self.values.items()},
|
|
99
|
+
"provenance": self.provenance}, path)
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def load(cls, path: str, adapter: Any = None) -> "ResidualCapture":
|
|
103
|
+
state = _torch().load(path, map_location="cpu", weights_only=True)
|
|
104
|
+
return cls({tuple(int(x) for x in k.split(".")): v for k, v in state["h"].items()},
|
|
105
|
+
{int(k): v for k, v in state["values"].items()}, state["provenance"], adapter)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass
|
|
109
|
+
class Component:
|
|
110
|
+
"""One part of a cell: ``residual`` (d,) is its part of ``h``, ``value`` (d_h,) its image in
|
|
111
|
+
the cell (both float64); ``activation`` for a feature."""
|
|
112
|
+
|
|
113
|
+
name: str
|
|
114
|
+
feature: int | None
|
|
115
|
+
activation: float | None
|
|
116
|
+
residual: Any
|
|
117
|
+
value: Any
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass
|
|
121
|
+
class ComponentBinding(Binding):
|
|
122
|
+
"""A value cell split into components (module docstring). ``map`` is ``W_V^g diag(rho
|
|
123
|
+
gamma)`` (d_h, d) in float64, so ``map @ x`` is the cell image of a residual vector ``x`` at
|
|
124
|
+
the native ``rho``."""
|
|
125
|
+
|
|
126
|
+
row: int = -1
|
|
127
|
+
layer: int = -1
|
|
128
|
+
kv: int = -1
|
|
129
|
+
rho: float = 0.0
|
|
130
|
+
basis: dict[str, Any] = field(default_factory=dict)
|
|
131
|
+
components: list[Component] = field(default_factory=list)
|
|
132
|
+
native: Any = None
|
|
133
|
+
linear: Any = None
|
|
134
|
+
v_bias: Any = None
|
|
135
|
+
map: Any = None
|
|
136
|
+
active: list[int] = field(default_factory=list)
|
|
137
|
+
acts: dict[int, float] = field(default_factory=dict)
|
|
138
|
+
provenance: dict[str, Any] = field(default_factory=dict)
|
|
139
|
+
site: str = "value-cell" # "value-cell" (a V cell) | "mlp-write" (t<r>.L<l>.m)
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def cell(self) -> str:
|
|
143
|
+
if self.site == "mlp-write":
|
|
144
|
+
return f"t{self.row}.L{self.layer}.m"
|
|
145
|
+
return f"cache.L{self.layer}.v[kv{self.kv},row={self.row}]"
|
|
146
|
+
|
|
147
|
+
def get(self, name: str) -> Component:
|
|
148
|
+
for c in self.components:
|
|
149
|
+
if c.name == name:
|
|
150
|
+
return c
|
|
151
|
+
raise Refusal(f"{self.name} has no component {name}")
|
|
152
|
+
|
|
153
|
+
def closure(self) -> dict[str, Any]:
|
|
154
|
+
"""``sum of components (+ b_V) - v_lin`` (float64 order only) and ``v_native - v_lin``."""
|
|
155
|
+
total = sum(c.value for c in self.components)
|
|
156
|
+
if self.v_bias is not None:
|
|
157
|
+
total = total + self.v_bias
|
|
158
|
+
gap = float((total - self.linear).abs().max())
|
|
159
|
+
scale = float(self.linear.abs().max()) or 1.0
|
|
160
|
+
rounding = self.native - self.linear
|
|
161
|
+
return {"max_gap": num(gap, EXACT), "relative_gap": num(gap / scale, EXACT),
|
|
162
|
+
"within_f64": gap <= 64 * 2.0 ** -53 * scale * max(1, len(self.components)),
|
|
163
|
+
"rounding_norm": num(float(rounding.norm()), MEASURED),
|
|
164
|
+
"rounding_relative": num(float(rounding.norm() / (self.linear.norm() or 1.0)),
|
|
165
|
+
MEASURED),
|
|
166
|
+
"meaning": "max_gap: components + b_V against W_V^g(rho gamma h) in float64 "
|
|
167
|
+
"(an identity; checks the split); rounding: the native bf16 cell "
|
|
168
|
+
"against its float64 image (measured, not a component)"}
|
|
169
|
+
|
|
170
|
+
def image(self, residual: Any) -> Any:
|
|
171
|
+
"""The cell image ``W_V^g (rho gamma * x)`` of a residual vector at the native rho (an
|
|
172
|
+
MLP-write binding's site is the residual stream itself: the identity)."""
|
|
173
|
+
if self.map is None:
|
|
174
|
+
return f64(residual).reshape(-1)
|
|
175
|
+
return self.map @ f64(residual).reshape(-1)
|
|
176
|
+
|
|
177
|
+
def feature_value(self, feature: int, activation: float, basis: Any) -> Any:
|
|
178
|
+
"""The site image of ``activation * d_f`` (a supplied activation, e.g. a donor's)."""
|
|
179
|
+
return self.image(basis.direction(int(feature)) * float(activation))
|
|
180
|
+
|
|
181
|
+
def edited(self, *, remove: tuple[str, ...] = (), add: Any = None) -> Any:
|
|
182
|
+
"""The native cell minus the named components plus ``add`` (d_h, float64 or None):
|
|
183
|
+
the value a ``set_cell`` writes (cast by the caller to the cache dtype)."""
|
|
184
|
+
out = self.native.clone()
|
|
185
|
+
for name in remove:
|
|
186
|
+
out = out - self.get(name).value
|
|
187
|
+
if add is not None:
|
|
188
|
+
out = out + f64(add).reshape(-1)
|
|
189
|
+
return out
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def component_binding(run: Any, name: str, cell: str, basis: Any, *,
|
|
193
|
+
features: list[int] | None = None, capture: ResidualCapture | None = None,
|
|
194
|
+
adapter: Any = None) -> ComponentBinding:
|
|
195
|
+
"""Split ``cell`` (``cache.L<l>.v[kv<g>,row=<r>]``) over ``basis``; ``features`` lists the
|
|
196
|
+
features kept as their own components (default: every active one).
|
|
197
|
+
|
|
198
|
+
With ``capture`` (a ``ResidualCapture``) ``h`` is read from it, not from ``run``; ``run`` may
|
|
199
|
+
then be None and the weights come from ``adapter`` (default ``capture.adapter``). The native
|
|
200
|
+
cell comes from ``capture.values`` when held, else from ``run.read_cache``; with neither the
|
|
201
|
+
refusal says so. The result is bitwise the live binding when the capture holds the live
|
|
202
|
+
run's ``h`` and cache."""
|
|
203
|
+
from ..measure.readout import layer_module
|
|
204
|
+
|
|
205
|
+
torch = _torch()
|
|
206
|
+
match = _CELL.match(cell.replace(" ", ""))
|
|
207
|
+
if not match:
|
|
208
|
+
raise Refusal(f"a component binding is over one value cell "
|
|
209
|
+
f"cache.L<l>.v[kv<g>,row=<r>], not {cell!r}")
|
|
210
|
+
layer, kv, row = (int(x) for x in match.groups())
|
|
211
|
+
adapter = adapter or (run.adapter if run is not None else None) \
|
|
212
|
+
or (capture.adapter if capture is not None else None)
|
|
213
|
+
if adapter is None:
|
|
214
|
+
raise Refusal("component_binding needs a run, or a capture plus an adapter")
|
|
215
|
+
if capture is not None and run is not None and adapter is not run.adapter:
|
|
216
|
+
raise Refusal("the supplied adapter is not the run's")
|
|
217
|
+
if row == 0:
|
|
218
|
+
raise Refusal(f"{cell}: {FIRST_ROW_CAVEAT}")
|
|
219
|
+
if capture is not None:
|
|
220
|
+
if (row, layer) not in capture.h:
|
|
221
|
+
raise Refusal(f"{cell}: the capture holds no h at t{row}.L{layer} (it holds "
|
|
222
|
+
f"{sorted(capture.h)})")
|
|
223
|
+
elif run is None:
|
|
224
|
+
raise Refusal("component_binding needs a run or a capture")
|
|
225
|
+
elif row < int(run.first_row):
|
|
226
|
+
raise Refusal(f"{cell}: t{row} was prefilled (first stepped row t{run.first_row}); its "
|
|
227
|
+
f"residual was never stopped at")
|
|
228
|
+
if not basis.covers(layer, "h"):
|
|
229
|
+
raise Refusal(f"basis {basis.name} at {basis.site} does not hold L{layer}.h")
|
|
230
|
+
module = layer_module(adapter, layer)
|
|
231
|
+
if getattr(module.self_attn, "v_norm", None) is not None:
|
|
232
|
+
raise Refusal("component binding: the model normalises V (not a linear image of h)")
|
|
233
|
+
dh = adapter.head_dim
|
|
234
|
+
rows = slice(kv * dh, (kv + 1) * dh)
|
|
235
|
+
w_v = f64(module.self_attn.v_proj.weight[rows]).cpu() # (dh, d)
|
|
236
|
+
b = getattr(module.self_attn.v_proj, "bias", None)
|
|
237
|
+
v_bias = None if b is None else f64(b[rows]).cpu()
|
|
238
|
+
norm = module.input_layernorm
|
|
239
|
+
gamma, eps = f64(norm.weight).reshape(-1).cpu(), float(norm.variance_epsilon)
|
|
240
|
+
h = (capture.h[(row, layer)] if capture is not None
|
|
241
|
+
else run.read(f"t{row}.L{layer}.h")).reshape(-1)
|
|
242
|
+
h64 = f64(h).cpu()
|
|
243
|
+
rho = float((h64.pow(2).mean() + eps) ** -0.5)
|
|
244
|
+
vmap = w_v * (rho * gamma)[None, :]
|
|
245
|
+
dec = basis.decompose(h)
|
|
246
|
+
acts = {int(f): float(a) for f, a in zip(dec.ids, dec.acts.tolist())}
|
|
247
|
+
keep = list(dec.ids) if features is None else [int(f) for f in features]
|
|
248
|
+
twice = sorted({f for f in keep if keep.count(f) > 1})
|
|
249
|
+
if twice:
|
|
250
|
+
raise Refusal(f"features repeats id(s) {twice}: each feature is one component")
|
|
251
|
+
comps: list[Component] = []
|
|
252
|
+
lumped = torch.zeros_like(h64)
|
|
253
|
+
for col, f in enumerate(dec.ids):
|
|
254
|
+
if f in keep:
|
|
255
|
+
continue
|
|
256
|
+
lumped = lumped + dec.parts[:, col]
|
|
257
|
+
for f in keep:
|
|
258
|
+
if f in acts:
|
|
259
|
+
part = dec.parts[:, dec.ids.index(f)]
|
|
260
|
+
else:
|
|
261
|
+
part = torch.zeros_like(h64)
|
|
262
|
+
comps.append(Component(f"feature[{f}]", f, acts.get(f, 0.0), part, vmap @ part))
|
|
263
|
+
comps.append(Component("other_features", None, None, lumped, vmap @ lumped))
|
|
264
|
+
comps.append(Component("bdec", None, None, dec.bias, vmap @ dec.bias))
|
|
265
|
+
comps.append(Component("error", None, None, dec.error, vmap @ dec.error))
|
|
266
|
+
linear = vmap @ h64 + (0 if v_bias is None else v_bias)
|
|
267
|
+
if capture is not None and layer in capture.values:
|
|
268
|
+
cache, cache_from = capture.values[layer], "capture.values"
|
|
269
|
+
elif run is not None:
|
|
270
|
+
cache, cache_from = run.read_cache(layer, "v", staged=False), "Run.read_cache(staged=False)"
|
|
271
|
+
else:
|
|
272
|
+
raise Refusal(f"{cell}: the capture holds no value cache of L{layer} and there is no run")
|
|
273
|
+
native = f64(cache[0, kv, row]).cpu()
|
|
274
|
+
provenance = {"h": (f"capture ({capture.provenance.get('h')}; cursor "
|
|
275
|
+
f"{capture.provenance.get('cursor')})" if capture is not None
|
|
276
|
+
else "live Run.read"),
|
|
277
|
+
"native_cell": cache_from, "offline": capture is not None}
|
|
278
|
+
return ComponentBinding(name, "component", [], [cell], row=row, layer=layer, kv=kv, rho=rho,
|
|
279
|
+
basis=basis.describe(), components=comps, native=native,
|
|
280
|
+
linear=linear, v_bias=v_bias, map=vmap, active=list(dec.ids),
|
|
281
|
+
acts=acts, provenance=provenance)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def transcoder_binding(run: Any, name: str, site: str, basis: Any, *,
|
|
285
|
+
features: list[int] | None = None) -> ComponentBinding:
|
|
286
|
+
"""The MLP write ``t<r>.L<l>.m`` split by a transcoder (``sae.TranscoderBasis``):
|
|
287
|
+
one component per listed feature (default: every active one), ``other_features``,
|
|
288
|
+
``bdec`` and ``error`` (= native ``m`` minus the reconstruction: the binding's ``Unbound``).
|
|
289
|
+
The same decomposition family as the value-cell binding and ``SubspaceBinding.decompose``:
|
|
290
|
+
``component_table`` reads it (the write reaches a scalar consumer at row ``r`` directly, P19),
|
|
291
|
+
``edited(remove=...)`` gives the value a ``Run.set`` at ``m`` writes, ``feature_value`` a
|
|
292
|
+
supplied activation's write. ``native`` is the measured ``m``; ``linear`` equals it (the
|
|
293
|
+
error closes the identity)."""
|
|
294
|
+
match = re.match(r"^t(\d+)\.L(\d+)\.m$", site.replace(" ", ""))
|
|
295
|
+
if not match:
|
|
296
|
+
raise Refusal(f"a transcoder binding is over one MLP write t<r>.L<l>.m, not {site!r}")
|
|
297
|
+
row, layer = (int(x) for x in match.groups())
|
|
298
|
+
if getattr(basis, "kind", None) != "transcoder":
|
|
299
|
+
raise Refusal(f"{getattr(basis, 'name', basis)} is not a transcoder (reads L<l>.n, "
|
|
300
|
+
"writes L<l>.m)")
|
|
301
|
+
if basis.layer != layer:
|
|
302
|
+
raise Refusal(f"transcoder {basis.name} is of L{basis.layer}, not L{layer}")
|
|
303
|
+
if row < int(run.first_row):
|
|
304
|
+
raise Refusal(f"t{row} was prefilled (first stepped row t{run.first_row}): its MLP "
|
|
305
|
+
"input was never stopped at")
|
|
306
|
+
torch = _torch()
|
|
307
|
+
n = run.read(f"t{row}.L{layer}.n")
|
|
308
|
+
m = run.read(f"t{row}.L{layer}.m")
|
|
309
|
+
dec = basis.decompose(n, m)
|
|
310
|
+
acts = {int(f): float(a) for f, a in zip(dec.ids, dec.acts.tolist())}
|
|
311
|
+
keep = list(dec.ids) if features is None else [int(f) for f in features]
|
|
312
|
+
twice = sorted({f for f in keep if keep.count(f) > 1})
|
|
313
|
+
if twice:
|
|
314
|
+
raise Refusal(f"features repeats id(s) {twice}: each feature is one component")
|
|
315
|
+
comps: list[Component] = []
|
|
316
|
+
lumped = torch.zeros_like(dec.x)
|
|
317
|
+
for col, f in enumerate(dec.ids):
|
|
318
|
+
if f not in keep:
|
|
319
|
+
lumped = lumped + dec.parts[:, col]
|
|
320
|
+
for f in keep:
|
|
321
|
+
part = dec.parts[:, dec.ids.index(f)] if f in acts else torch.zeros_like(dec.x)
|
|
322
|
+
comps.append(Component(f"feature[{f}]", f, acts.get(f, 0.0), part, part))
|
|
323
|
+
comps.append(Component("other_features", None, None, lumped, lumped))
|
|
324
|
+
comps.append(Component("bdec", None, None, dec.bias, dec.bias))
|
|
325
|
+
comps.append(Component("error", None, None, dec.error, dec.error))
|
|
326
|
+
return ComponentBinding(name, "component", [], [site], row=row, layer=layer, kv=-1, rho=0.0,
|
|
327
|
+
basis=basis.describe(), components=comps, native=dec.x,
|
|
328
|
+
linear=dec.x, v_bias=None, map=None, active=list(dec.ids),
|
|
329
|
+
acts=acts, site="mlp-write",
|
|
330
|
+
provenance={"decomposition": "transcoder", "n": "live Run.read",
|
|
331
|
+
"native_write": "live Run.read", "offline": False})
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _group(run: Any, binding: ComponentBinding, reader_row: int) -> tuple[Any, list[int], Any]:
|
|
335
|
+
"""``(p[h, r] for heads of the group, heads, W_O blocks (H_g, d, d_h))`` at reader row."""
|
|
336
|
+
from ..measure.readout import head_mix, layer_module
|
|
337
|
+
|
|
338
|
+
mix = head_mix(run, reader_row, binding.layer, lazy=True)
|
|
339
|
+
heads = [h for h, g in enumerate(mix.kappa) if g == binding.kv]
|
|
340
|
+
if binding.row >= mix.p.shape[1]:
|
|
341
|
+
raise Refusal(f"t{reader_row} does not read row {binding.row}")
|
|
342
|
+
p = mix.p[heads, binding.row]
|
|
343
|
+
dh = run.adapter.head_dim
|
|
344
|
+
weight = layer_module(run.adapter, binding.layer).self_attn.o_proj.weight
|
|
345
|
+
blocks = [f64(weight[:, h * dh:(h + 1) * dh]).cpu() for h in heads]
|
|
346
|
+
return p.cpu(), heads, blocks
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def write_of(run: Any, binding: ComponentBinding, value: Any, reader_row: int,
|
|
350
|
+
group: tuple | None = None) -> Any:
|
|
351
|
+
"""``sum_h p[h, r] W_O,h value`` (d,) float64: what a cell value writes into the reader row
|
|
352
|
+
at the native attention weights. An MLP-write binding writes its value into its own row
|
|
353
|
+
(the reader row must be that row)."""
|
|
354
|
+
if getattr(binding, "site", "value-cell") == "mlp-write":
|
|
355
|
+
if reader_row != binding.row:
|
|
356
|
+
raise Refusal(f"{binding.cell} writes row {binding.row} only; a consumer at "
|
|
357
|
+
f"t{reader_row} reads it through later layers (not a direct term)")
|
|
358
|
+
return f64(value).reshape(-1)
|
|
359
|
+
p, heads, blocks = group or _group(run, binding, reader_row)
|
|
360
|
+
v = f64(value).reshape(-1)
|
|
361
|
+
return sum(float(p[i]) * (blocks[i] @ v) for i in range(len(heads)))
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def component_table(run: Any, binding: ComponentBinding, consumer: Any = None, *,
|
|
365
|
+
sets: list[Candidates] | None = None, tokenizer: Any = None) -> dict[str, Any]:
|
|
366
|
+
"""Per component: the exact share of a scalar consumer at fixed attention weights, the
|
|
367
|
+
share of the cell's native read, and optionally the content readout of its write."""
|
|
368
|
+
from ..measure.readout import readout
|
|
369
|
+
|
|
370
|
+
if consumer is None:
|
|
371
|
+
raise Refusal("component_table needs a scalar consumer (Margin or Logit)")
|
|
372
|
+
reader = readout(run, consumer)
|
|
373
|
+
if not reader.scalar:
|
|
374
|
+
raise Refusal("component_table needs a scalar consumer (Margin or Logit)")
|
|
375
|
+
j = int(reader.row)
|
|
376
|
+
mlp = getattr(binding, "site", "value-cell") == "mlp-write"
|
|
377
|
+
group = None if mlp else _group(run, binding, j)
|
|
378
|
+
if mlp and j != binding.row:
|
|
379
|
+
raise Refusal(f"{binding.cell} reaches t{j} only through later layers: use a consumer "
|
|
380
|
+
f"at t{binding.row}")
|
|
381
|
+
p = None if mlp else group[0]
|
|
382
|
+
c = f64(reader.vector).reshape(-1).cpu()
|
|
383
|
+
native_effect = float(c @ write_of(run, binding, binding.native, j, group))
|
|
384
|
+
linear_effect = float(c @ write_of(run, binding, binding.linear, j, group))
|
|
385
|
+
basis = readout_basis(run, j) if sets else None
|
|
386
|
+
rows = []
|
|
387
|
+
for comp in binding.components:
|
|
388
|
+
w = write_of(run, binding, comp.value, j, group)
|
|
389
|
+
effect = float(c @ w)
|
|
390
|
+
entry: dict[str, Any] = {
|
|
391
|
+
"component": comp.name, "to_consumer": num(effect, EXACT, "P19"),
|
|
392
|
+
"share_of_cell": (num(effect / native_effect, EXACT) if native_effect else None),
|
|
393
|
+
"value_norm": num(float(comp.value.norm()), EXACT)}
|
|
394
|
+
if comp.feature is not None:
|
|
395
|
+
entry["feature"] = comp.feature
|
|
396
|
+
entry["activation"] = num(float(comp.activation or 0.0), EXACT)
|
|
397
|
+
if sets:
|
|
398
|
+
entry["content"] = content(run, w, sets, basis, tokenizer=tokenizer)
|
|
399
|
+
rows.append(entry)
|
|
400
|
+
effects = [float(r["to_consumer"]["value"]) for r in rows]
|
|
401
|
+
vb = 0.0
|
|
402
|
+
if binding.v_bias is not None:
|
|
403
|
+
vb = float(c @ write_of(run, binding, binding.v_bias, j, group))
|
|
404
|
+
gap = abs(sum(effects) + vb - linear_effect)
|
|
405
|
+
return {
|
|
406
|
+
"cell": binding.cell, "binding": binding.name, "consumer": reader.text,
|
|
407
|
+
"reader_row": j,
|
|
408
|
+
"mass": ({"state": "not applicable", "reason": "an MLP write is added to its own row's "
|
|
409
|
+
"residual stream (no attention weight)"} if mlp else
|
|
410
|
+
{**num(float(p.sum()), EXACT), "inherited": "the cell's mass (sum of p over "
|
|
411
|
+
"the KV group's heads at the reader row); a component has no mass of its own"}),
|
|
412
|
+
"cell_to_consumer": num(native_effect, EXACT, "P19"),
|
|
413
|
+
"linear_to_consumer": num(linear_effect, EXACT, "P19"),
|
|
414
|
+
"rounding_to_consumer": num(native_effect - linear_effect, MEASURED),
|
|
415
|
+
"components": rows,
|
|
416
|
+
"partition": {"gap": num(gap, EXACT),
|
|
417
|
+
"holds": gap <= 1e-9 * max(1.0, abs(linear_effect)),
|
|
418
|
+
"meaning": "sum of component shares (+ V bias) = the float64 image's "
|
|
419
|
+
"share; the native cell differs by rounding_to_consumer"},
|
|
420
|
+
"closure": binding.closure(),
|
|
421
|
+
"basis": {k: binding.basis.get(k) for k in ("name", "site", "k")},
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
# Rows where a residual SAE is off its training distribution: Qwen-Scope's report (arXiv
|
|
426
|
+
# 2605.11887, section 2.2) filters activations with extreme L2 norm from training, "especially
|
|
427
|
+
# ... the first token of each input sequence" (the attention-sink row). mdb prompts carry no BOS,
|
|
428
|
+
# so row 0 is the first text token.
|
|
429
|
+
FIRST_ROW_CAVEAT = ("row 0 is the first token (the attention-sink row, massive norm); the SAE's "
|
|
430
|
+
"training filtered extreme-norm activations, most of them first-token "
|
|
431
|
+
"(Qwen-Scope report section 2.2), so features and error here are read off "
|
|
432
|
+
"the training distribution")
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
__all__ = ["ResidualCapture", "Component", "ComponentBinding", "component_binding",
|
|
436
|
+
"component_table", "transcoder_binding", "write_of", "FIRST_ROW_CAVEAT"]
|