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
mdb/interop/nn.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
"""nnsight <-> mdb: read ports by mdb address, and batched interventions written as mdb edits.
|
|
2
|
+
|
|
3
|
+
mdb steps one sequence; nnsight batches. ``batch_whatif`` takes edits in mdb's address language
|
|
4
|
+
and measures them over many prompts in a few batched nnsight traces:
|
|
5
|
+
|
|
6
|
+
- a port edit ``L22.A[h6]`` (``h``/``kv``/``i`` selectors) applies at each prompt's LAST row, as
|
|
7
|
+
mdb's ``whatif`` does at the pending row;
|
|
8
|
+
- a state-cell edit ``cache.L22.v[kv1,row=11]`` has two scopes. ``reader`` is mdb's meaning: only
|
|
9
|
+
the last row reads the changed cell (the native layer runs with the patched value row, then
|
|
10
|
+
every earlier row's ``o_proj`` input is put back to its clean value, so earlier rows are
|
|
11
|
+
bitwise clean). ``sequence`` is ordinary activation patching: every later row of that layer
|
|
12
|
+
reads the patched value too, and the change spreads through their residuals.
|
|
13
|
+
|
|
14
|
+
Values from a donor prompt (``value="donor"``) are taken from a batched donor pass. Prompts are
|
|
15
|
+
grouped by (recipient length, donor length) so no batch is padded. Every number returned is
|
|
16
|
+
``measured`` by native kernels in a batched program: it is not mdb's batch-1 stepped program,
|
|
17
|
+
so mdb re-measures a sample (``mdb.interop.verify``).
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import re
|
|
23
|
+
from collections.abc import Sequence
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
from mdb.core import address as addresses
|
|
28
|
+
|
|
29
|
+
from . import names
|
|
30
|
+
|
|
31
|
+
EDIT_OPS = ("replace", "add", "scale")
|
|
32
|
+
PORT_ORDER = tuple(n.port for n in names.NAMES)
|
|
33
|
+
NN_EDITABLE = ("h", "a", "q", "k", "v", "A", "o", "r", "n", "g", "sg", "u", "f", "m", "h_out")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def version() -> str:
|
|
37
|
+
from importlib.metadata import version as _v
|
|
38
|
+
|
|
39
|
+
return _v("nnsight")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def wrap(model: Any) -> Any:
|
|
43
|
+
from nnsight import NNsight
|
|
44
|
+
|
|
45
|
+
return NNsight(model)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
_STEP = re.compile(r"\.(\w+)|\[(\d+)\]")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def envoy(nm: Any, address: str) -> Any:
|
|
52
|
+
"""The nnsight proxy for ``L<l>.<port>`` (or ``emb``/``fn``/``logits``) on ``nm`` (an
|
|
53
|
+
``NNsight`` wrapper of the Hugging Face causal LM). Use inside ``nm.trace(...)``."""
|
|
54
|
+
path = names.to_nnsight(address).removeprefix("model")
|
|
55
|
+
node = nm
|
|
56
|
+
for attr, index in _STEP.findall(path):
|
|
57
|
+
node = getattr(node, attr) if attr else node[int(index)]
|
|
58
|
+
return node
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def read(nm: Any, tokens: Sequence[Sequence[int]], addresses_: Sequence[str],
|
|
62
|
+
rows: Sequence[int] | None = None) -> dict[str, Any]:
|
|
63
|
+
"""Save ``addresses_`` (``L<l>.<port>``) over a batch of equal-length prompts in one trace;
|
|
64
|
+
returns ``{t<r>.L<l>.<port>: tensor (batch, ...) in mdb layout}`` for each row."""
|
|
65
|
+
import torch
|
|
66
|
+
|
|
67
|
+
ids = torch.tensor([list(t) for t in tokens], device=_device(nm))
|
|
68
|
+
eager = [a for a in addresses_ if names._split(a)[1] in EAGER_ARGS]
|
|
69
|
+
plain = sorted((a for a in addresses_ if a not in eager), key=_read_key)
|
|
70
|
+
saved = {}
|
|
71
|
+
with torch.no_grad(), nm.trace(ids):
|
|
72
|
+
for address in plain:
|
|
73
|
+
saved[address] = envoy(nm, address).save()
|
|
74
|
+
# the eager-attention arguments come through ``.source``, which must be requested before
|
|
75
|
+
# the attention forward starts; one more trace per layer keeps the requests in order
|
|
76
|
+
# (on a weight-sharing clone: ``.source`` rewrites the attention module's forward for good)
|
|
77
|
+
if eager:
|
|
78
|
+
from .clone import shared_clone
|
|
79
|
+
|
|
80
|
+
nm_source = wrap(shared_clone(nm._module))
|
|
81
|
+
for layer in sorted({names._split(a)[0] for a in eager}):
|
|
82
|
+
here = sorted((a for a in eager if names._split(a)[0] == layer), key=_execution_key)
|
|
83
|
+
with torch.no_grad(), nm_source.trace(ids):
|
|
84
|
+
for address in here:
|
|
85
|
+
saved[address] = envoy(nm_source, address).save()
|
|
86
|
+
out = {}
|
|
87
|
+
rows = range(ids.shape[1]) if rows is None else rows
|
|
88
|
+
for address, value in saved.items():
|
|
89
|
+
layer, port = names._split(address)
|
|
90
|
+
spec = names.BY_PORT[port]
|
|
91
|
+
for row in rows:
|
|
92
|
+
out[f"t{row}.{address}"] = names.to_mdb(spec.nn_layout, value, row).detach()
|
|
93
|
+
return out
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# --- batched what-if ----------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass(frozen=True)
|
|
100
|
+
class Edit:
|
|
101
|
+
"""One edit in mdb's language. ``value``: a number; ``"donor"`` (the donor prompt's value
|
|
102
|
+
at the same port, last row; for a cell, at ``donor_row`` or the same row); or ``"self"``
|
|
103
|
+
(a cell only: the recipient's own clean value at ``donor_row``, the disruption control)."""
|
|
104
|
+
|
|
105
|
+
address: str
|
|
106
|
+
value: Any = 0.0
|
|
107
|
+
op: str = "replace"
|
|
108
|
+
scope: str = "reader"
|
|
109
|
+
donor_row: int | None = None
|
|
110
|
+
|
|
111
|
+
def __post_init__(self):
|
|
112
|
+
if self.op not in EDIT_OPS:
|
|
113
|
+
raise ValueError(f"op must be one of {EDIT_OPS}")
|
|
114
|
+
if self.scope not in ("reader", "sequence"):
|
|
115
|
+
raise ValueError("scope is 'reader' (mdb: only the last row reads the cell) or "
|
|
116
|
+
"'sequence' (activation patching)")
|
|
117
|
+
kind = value_kind(self.value)
|
|
118
|
+
if kind is None:
|
|
119
|
+
raise ValueError("value is a number, 'donor', 'self' or a per-prompt tensor "
|
|
120
|
+
"(prompts, columns)")
|
|
121
|
+
if kind == "self" and (self.donor_row is None or not
|
|
122
|
+
self.address.startswith("cache.")):
|
|
123
|
+
raise ValueError("'self' takes a cell address and a donor_row")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def value_kind(value: Any) -> str | None:
|
|
127
|
+
"""``number``, ``donor``, ``self`` or ``tensor`` (one row of columns per prompt)."""
|
|
128
|
+
if isinstance(value, str):
|
|
129
|
+
return value if value in ("donor", "self") else None
|
|
130
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
131
|
+
return "number"
|
|
132
|
+
if getattr(value, "ndim", None) == 2:
|
|
133
|
+
return "tensor"
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
EAGER_ARGS = ("qr", "kr")
|
|
138
|
+
# nnsight serves requests in execution order: the attention module's own output (``p``) is
|
|
139
|
+
# returned after o_proj has run, so ``p`` reads after ``A`` and ``o``.
|
|
140
|
+
NN_READ_ORDER = ("h", "a", "q", "qn", "k", "kn", "v", "A", "o", "p", "r", "n", "g", "sg", "u",
|
|
141
|
+
"f", "m", "h_out")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _read_key(address: str) -> tuple[int, int]:
|
|
145
|
+
layer, port = names._split(address)
|
|
146
|
+
if layer is None:
|
|
147
|
+
return ({"emb": -1}.get(port, 10**6), 0)
|
|
148
|
+
return (layer, NN_READ_ORDER.index(port))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _execution_key(address: str) -> tuple[int, int]:
|
|
152
|
+
layer, port = names._split(address)
|
|
153
|
+
if layer is None:
|
|
154
|
+
return ({"emb": -1}.get(port, 10**6), 0)
|
|
155
|
+
return (layer, PORT_ORDER.index(port))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _indices(value: Any, size: int) -> list[int]:
|
|
159
|
+
if isinstance(value, int):
|
|
160
|
+
return [value]
|
|
161
|
+
if isinstance(value, addresses.Span):
|
|
162
|
+
stop = size if value.stop is None else value.stop
|
|
163
|
+
return list(range(value.start or 0, stop))
|
|
164
|
+
if isinstance(value, addresses.AnyOf):
|
|
165
|
+
return list(value.values)
|
|
166
|
+
raise ValueError(f"selector value {value!r}")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@dataclass(frozen=True)
|
|
170
|
+
class _Plan:
|
|
171
|
+
kind: str # "port" | "cell"
|
|
172
|
+
layer: int
|
|
173
|
+
port: str # port, or "k"/"v" for a cell
|
|
174
|
+
columns: tuple[int, ...] | None # flat column indices in the native (batch, pos, X) tensor
|
|
175
|
+
rows: tuple[int, ...] # cell rows (port edits: the last row)
|
|
176
|
+
edit: Edit
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def plan(edit: Edit, config: Any) -> _Plan:
|
|
180
|
+
"""Parse an mdb address into the native columns the edit touches."""
|
|
181
|
+
heads = int(config.num_attention_heads)
|
|
182
|
+
kv = int(config.num_key_value_heads)
|
|
183
|
+
head_dim = getattr(config, "head_dim", None) or config.hidden_size // heads
|
|
184
|
+
text = edit.address.strip()
|
|
185
|
+
if text.startswith("cache."):
|
|
186
|
+
cell = addresses.parse(text)
|
|
187
|
+
keys = dict(cell.selector.keys)
|
|
188
|
+
if "row" not in keys:
|
|
189
|
+
raise ValueError(f"{text}: a cell edit names its rows (row=R)")
|
|
190
|
+
rows = tuple(_indices(keys["row"], 10**9))
|
|
191
|
+
heads_ = _indices(keys["kv"], kv) if "kv" in keys else list(range(kv))
|
|
192
|
+
cols = [h * head_dim + d for h in heads_ for d in
|
|
193
|
+
(_indices(keys["d"], head_dim) if "d" in keys else range(head_dim))]
|
|
194
|
+
if cell.tensor == "k" and value_kind(edit.value) in ("donor", "self") and edit.donor_row is not None:
|
|
195
|
+
if len(rows) != 1 or edit.donor_row != rows[0]:
|
|
196
|
+
raise ValueError(f"{text}: a key cell from another row would carry that row's "
|
|
197
|
+
"rotation; nnsight patches k before RoPE, so donor_row must "
|
|
198
|
+
"equal the row")
|
|
199
|
+
return _Plan("cell", cell.layer, cell.tensor, tuple(cols), rows, edit)
|
|
200
|
+
occurrence = addresses.parse(text if text.startswith("t") else f"t0.{text}")
|
|
201
|
+
port, layer = occurrence.port, occurrence.layer
|
|
202
|
+
if port not in NN_EDITABLE:
|
|
203
|
+
raise ValueError(f"{text}: nnsight edits ports {', '.join(NN_EDITABLE)}")
|
|
204
|
+
keys = dict(occurrence.selector.keys)
|
|
205
|
+
width = {"q": heads * head_dim, "A": heads * head_dim, "k": kv * head_dim,
|
|
206
|
+
"v": kv * head_dim, "g": config.intermediate_size, "sg": config.intermediate_size,
|
|
207
|
+
"u": config.intermediate_size, "f": config.intermediate_size}.get(
|
|
208
|
+
port, config.hidden_size)
|
|
209
|
+
cols: list[int] | None = None
|
|
210
|
+
if "h" in keys:
|
|
211
|
+
if port not in ("q", "A"):
|
|
212
|
+
raise ValueError(f"{text}: h selects query heads of q or A")
|
|
213
|
+
cols = [h * head_dim + d for h in _indices(keys["h"], heads) for d in range(head_dim)]
|
|
214
|
+
elif "kv" in keys:
|
|
215
|
+
if port not in ("k", "v"):
|
|
216
|
+
raise ValueError(f"{text}: kv selects key/value heads of k or v")
|
|
217
|
+
cols = [h * head_dim + d for h in _indices(keys["kv"], kv) for d in range(head_dim)]
|
|
218
|
+
elif "i" in keys:
|
|
219
|
+
cols = _indices(keys["i"], width)
|
|
220
|
+
elif keys:
|
|
221
|
+
raise ValueError(f"{text}: nnsight edits take h, kv or i selectors")
|
|
222
|
+
return _Plan("port", layer, port, None if cols is None else tuple(cols), (-1,), edit)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _apply(x: Any, plan_: _Plan, value: Any, rows: Sequence[int]) -> None:
|
|
226
|
+
"""In place on the native tensor ``x`` (batch, pos, X): the edit at ``rows``/columns."""
|
|
227
|
+
import torch
|
|
228
|
+
|
|
229
|
+
cols = (slice(None) if plan_.columns is None
|
|
230
|
+
else torch.tensor(plan_.columns, device=x.device))
|
|
231
|
+
for i, row in enumerate(rows):
|
|
232
|
+
current = x[:, row][:, cols]
|
|
233
|
+
operand = value if not isinstance(value, torch.Tensor) else value[:, i].to(x.dtype)
|
|
234
|
+
if plan_.edit.op == "replace":
|
|
235
|
+
new = torch.empty_like(current).copy_(operand if isinstance(operand, torch.Tensor)
|
|
236
|
+
else torch.full_like(current, operand))
|
|
237
|
+
elif plan_.edit.op == "add":
|
|
238
|
+
new = current + operand
|
|
239
|
+
else:
|
|
240
|
+
new = current * operand
|
|
241
|
+
block = x[:, row]
|
|
242
|
+
block[:, cols] = new
|
|
243
|
+
x[:, row] = block
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _value(p: _Plan, donor_vals: dict[Any, Any], device: Any, chunk: Sequence[int]) -> Any:
|
|
247
|
+
"""The edit operand: a float, or values ``(batch, rows, columns)`` (donor, own clean
|
|
248
|
+
value, or the supplied per-prompt tensor)."""
|
|
249
|
+
import torch
|
|
250
|
+
|
|
251
|
+
kind = value_kind(p.edit.value)
|
|
252
|
+
if kind == "number":
|
|
253
|
+
return float(p.edit.value)
|
|
254
|
+
if kind == "tensor":
|
|
255
|
+
rows = p.edit.value[torch.tensor(list(chunk))].to(device)
|
|
256
|
+
return rows[:, None, :].expand(-1, len(p.rows), -1)
|
|
257
|
+
src = donor_vals[(p.edit.value, p.layer, p.port)]
|
|
258
|
+
if p.kind == "cell":
|
|
259
|
+
src_rows = [p.edit.donor_row] * len(p.rows) if p.edit.donor_row is not None else p.rows
|
|
260
|
+
else:
|
|
261
|
+
src_rows = (-1,)
|
|
262
|
+
cols = slice(None) if p.columns is None else torch.tensor(p.columns, device=device)
|
|
263
|
+
return torch.stack([src[:, r][:, cols] for r in src_rows], 1)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def batch_whatif(model: Any, recipients: Sequence[Sequence[int]],
|
|
267
|
+
consumers: Sequence[tuple[int, int]], arms: dict[str, Sequence[Edit]], *,
|
|
268
|
+
donors: Sequence[Sequence[int]] | None = None,
|
|
269
|
+
batch_size: int = 32) -> dict[str, Any]:
|
|
270
|
+
"""Measure each arm (a list of ``Edit``) on every recipient prompt, batched.
|
|
271
|
+
|
|
272
|
+
``consumers[i] = (a, b)``: the margin ``logit[a] - logit[b]`` at recipient ``i``'s last row.
|
|
273
|
+
Returns ``{"base": [M_i], "arms": {name: {"edited": [...], "delta": [...]}}, "groups": n,
|
|
274
|
+
"traces": n}``; every M is float64 of the native logits.
|
|
275
|
+
"""
|
|
276
|
+
import torch
|
|
277
|
+
|
|
278
|
+
nm = wrap(model)
|
|
279
|
+
config = model.config
|
|
280
|
+
plans = {name: [plan(e, config) for e in edits] for name, edits in arms.items()}
|
|
281
|
+
needs_donor = any(value_kind(p.edit.value) == "donor" for ps in plans.values() for p in ps)
|
|
282
|
+
if needs_donor and (donors is None or len(donors) != len(recipients)):
|
|
283
|
+
raise ValueError("donor values need one donor prompt per recipient")
|
|
284
|
+
groups: dict[tuple[int, int], list[int]] = {}
|
|
285
|
+
for i, tokens in enumerate(recipients):
|
|
286
|
+
key = (len(tokens), len(donors[i]) if donors is not None else 0)
|
|
287
|
+
groups.setdefault(key, []).append(i)
|
|
288
|
+
n = len(recipients)
|
|
289
|
+
base = [None] * n
|
|
290
|
+
out = {name: [None] * n for name in arms}
|
|
291
|
+
traces = 0
|
|
292
|
+
device = _device(nm)
|
|
293
|
+
reader_layers = sorted({p.layer for ps in plans.values() for p in ps
|
|
294
|
+
if p.kind == "cell" and p.edit.scope == "reader"})
|
|
295
|
+
for _key, members in groups.items():
|
|
296
|
+
for start in range(0, len(members), batch_size):
|
|
297
|
+
chunk = members[start:start + batch_size]
|
|
298
|
+
ids = torch.tensor([list(recipients[i]) for i in chunk], device=device)
|
|
299
|
+
a_ids = torch.tensor([consumers[i][0] for i in chunk], device=device)
|
|
300
|
+
b_ids = torch.tensor([consumers[i][1] for i in chunk], device=device)
|
|
301
|
+
|
|
302
|
+
def margin(last):
|
|
303
|
+
# ``last``: the last row's logits (batch, vocab); only that row is saved
|
|
304
|
+
last = last.to(torch.float64)
|
|
305
|
+
return (last.gather(1, a_ids[:, None]) - last.gather(1, b_ids[:, None]))[:, 0]
|
|
306
|
+
|
|
307
|
+
clean_A, donor_vals = {}, {}
|
|
308
|
+
own = {(p.layer, p.port) for ps in plans.values() for p in ps if value_kind(p.edit.value) == "self"}
|
|
309
|
+
keys = sorted({(layer, "A") for layer in reader_layers} | own,
|
|
310
|
+
key=lambda lp: (lp[0], PORT_ORDER.index(lp[1])))
|
|
311
|
+
with torch.no_grad(), nm.trace(ids):
|
|
312
|
+
for layer, port in keys:
|
|
313
|
+
saved = envoy(nm, f"L{layer}.{port}").save()
|
|
314
|
+
if port == "A" and layer in reader_layers:
|
|
315
|
+
clean_A[layer] = saved
|
|
316
|
+
if (layer, port) in own:
|
|
317
|
+
donor_vals[("self", layer, port)] = saved
|
|
318
|
+
# a copy: saving a view would pin the whole (batch, pos, vocab) logits
|
|
319
|
+
logits = nm.output.logits[:, -1].clone().save()
|
|
320
|
+
traces += 1
|
|
321
|
+
for j, i in enumerate(chunk):
|
|
322
|
+
base[i] = float(margin(logits)[j])
|
|
323
|
+
if needs_donor:
|
|
324
|
+
d_ids = torch.tensor([list(donors[i]) for i in chunk], device=device)
|
|
325
|
+
wanted = sorted({(p.layer, p.port) for ps in plans.values() for p in ps
|
|
326
|
+
if value_kind(p.edit.value) == "donor"},
|
|
327
|
+
key=lambda lp: (lp[0], PORT_ORDER.index(lp[1])))
|
|
328
|
+
with torch.no_grad(), nm.trace(d_ids):
|
|
329
|
+
for layer, port in wanted:
|
|
330
|
+
donor_vals[("donor", layer, port)] = envoy(nm, f"L{layer}.{port}").save()
|
|
331
|
+
traces += 1
|
|
332
|
+
for name, ps in plans.items():
|
|
333
|
+
ordered = sorted(ps, key=lambda p: (p.layer, PORT_ORDER.index(p.port)))
|
|
334
|
+
with torch.no_grad(), nm.trace(ids):
|
|
335
|
+
for layer in sorted({p.layer for p in ordered}):
|
|
336
|
+
here = [p for p in ordered if p.layer == layer]
|
|
337
|
+
restore = any(p.kind == "cell" and p.edit.scope == "reader" for p in here)
|
|
338
|
+
ports = {p.port for p in here} | ({"A"} if restore else set())
|
|
339
|
+
for port in sorted(ports, key=PORT_ORDER.index):
|
|
340
|
+
x = envoy(nm, f"L{layer}.{port}")
|
|
341
|
+
if port == "A" and restore:
|
|
342
|
+
# reader scope: earlier rows read the clean cache at this layer
|
|
343
|
+
x[:, :-1] = clean_A[layer][:, :-1]
|
|
344
|
+
for p in [p for p in here if p.port == port]:
|
|
345
|
+
_apply(x, p, _value(p, donor_vals, device, chunk), p.rows)
|
|
346
|
+
edited = nm.output.logits[:, -1].clone().save()
|
|
347
|
+
traces += 1
|
|
348
|
+
for j, i in enumerate(chunk):
|
|
349
|
+
out[name][i] = float(margin(edited)[j])
|
|
350
|
+
return {"base": base,
|
|
351
|
+
"arms": {name: {"edited": vals, "delta": [e - b for e, b in zip(vals, base)]}
|
|
352
|
+
for name, vals in out.items()},
|
|
353
|
+
"groups": len(groups), "traces": traces, "nnsight": version()}
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _device(nm: Any) -> Any:
|
|
357
|
+
return next(nm._module.parameters()).device
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
# --- gradients ----------------------------------------------------------------------------
|
|
361
|
+
|
|
362
|
+
GRAD_PORTS = tuple(n.port for n in names.NAMES if n.nn_layout == "seq")
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
class _Frozen:
|
|
366
|
+
"""Parameters set ``requires_grad=False`` for the duration, then restored. An input-only
|
|
367
|
+
backward then builds no weight gradients (Qwen3-1.7B: +3.4 GB when they were left on)."""
|
|
368
|
+
|
|
369
|
+
def __init__(self, model: Any):
|
|
370
|
+
self.model = model
|
|
371
|
+
self.flags: list[tuple[Any, bool]] = []
|
|
372
|
+
|
|
373
|
+
def __enter__(self) -> None:
|
|
374
|
+
self.flags = [(p, p.requires_grad) for p in self.model.parameters()]
|
|
375
|
+
for p, _ in self.flags:
|
|
376
|
+
p.requires_grad_(False)
|
|
377
|
+
|
|
378
|
+
def __exit__(self, *exc: Any) -> None:
|
|
379
|
+
for p, flag in self.flags:
|
|
380
|
+
p.requires_grad_(flag)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def grads(model: Any, tokens: Sequence[Sequence[int]], addresses_: Sequence[str],
|
|
384
|
+
consumers: Sequence[tuple[int, int]]) -> dict[str, Any]:
|
|
385
|
+
"""Values and input gradients ``dM_i/dx`` of ``M_i = logit[a_i] - logit[b_i]`` at each
|
|
386
|
+
prompt's last row, for residual-shaped ports (``L<l>.h``, ``.h_out``, ``.o``, ``.m``, ...),
|
|
387
|
+
over a batch of equal-length prompts in ONE nnsight forward and ONE backward.
|
|
388
|
+
|
|
389
|
+
The prompts are independent rows of one batch, so the backward of ``sum_i M_i`` gives every
|
|
390
|
+
prompt its own gradient. Weights are frozen for the call (no weight gradients are built) and
|
|
391
|
+
the embedding output is the leaf that carries ``requires_grad``. Returns ``{"values":
|
|
392
|
+
{address: (batch, pos, X)}, "grads": {address: (batch, pos, X)}, "margin": [M_i]}``
|
|
393
|
+
(native dtype; ``measured`` by native kernels in a batched program).
|
|
394
|
+
|
|
395
|
+
nnsight 0.8 semantics this follows (``nnsight/tracing/tracer.py``, ``intervention/
|
|
396
|
+
backward.py``): the outermost trace hands back only names bound to ``.save()``d objects,
|
|
397
|
+
so the result containers are created inside the trace with ``nnsight.save``; ``.grad`` is
|
|
398
|
+
served only inside ``with M.backward():`` and must be requested in reverse forward order.
|
|
399
|
+
"""
|
|
400
|
+
import nnsight
|
|
401
|
+
import torch
|
|
402
|
+
|
|
403
|
+
bad = [a for a in addresses_ if names._split(a)[1] not in GRAD_PORTS]
|
|
404
|
+
if bad:
|
|
405
|
+
raise ValueError(f"grads reads ports {', '.join(GRAD_PORTS)}; not {', '.join(bad)}")
|
|
406
|
+
if len({len(t) for t in tokens}) != 1:
|
|
407
|
+
raise ValueError("grads takes equal-length prompts (no padding inside one batch)")
|
|
408
|
+
nm = wrap(model)
|
|
409
|
+
device = _device(nm)
|
|
410
|
+
ids = torch.tensor([list(t) for t in tokens], device=device)
|
|
411
|
+
a_ids = torch.tensor([c[0] for c in consumers], device=device)
|
|
412
|
+
b_ids = torch.tensor([c[1] for c in consumers], device=device)
|
|
413
|
+
ordered = sorted(dict.fromkeys(addresses_), key=_read_key)
|
|
414
|
+
with _Frozen(model), torch.enable_grad(), nm.trace(ids):
|
|
415
|
+
emb = nm.model.embed_tokens.output
|
|
416
|
+
emb.requires_grad_(True)
|
|
417
|
+
acts = [(address, envoy(nm, address)) for address in ordered]
|
|
418
|
+
values = nnsight.save({address: x.detach() for address, x in acts})
|
|
419
|
+
last = nm.lm_head.output[:, -1].float()
|
|
420
|
+
margins = last.gather(1, a_ids[:, None])[:, 0] - last.gather(1, b_ids[:, None])[:, 0]
|
|
421
|
+
margin = nnsight.save(margins.detach())
|
|
422
|
+
gradients = nnsight.save({})
|
|
423
|
+
with margins.sum().backward():
|
|
424
|
+
# L<l>.h_out and L<l+1>.h are one tensor: ask autograd for it once
|
|
425
|
+
by_tensor = {}
|
|
426
|
+
for address, x in reversed(acts):
|
|
427
|
+
if id(x) not in by_tensor:
|
|
428
|
+
by_tensor[id(x)] = x.grad.detach()
|
|
429
|
+
gradients[address] = by_tensor[id(x)]
|
|
430
|
+
return {"values": dict(values), "grads": {a: gradients[a] for a in ordered},
|
|
431
|
+
"margin": [float(m) for m in margin], "nnsight": version()}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""pyvene <-> mdb: the Qwen3 model-card shim and the cell-level interchange config.
|
|
2
|
+
|
|
3
|
+
pyvene 0.1.8 maps Qwen2 but not Qwen3 (``KeyError: Qwen3ForCausalLM`` in
|
|
4
|
+
``IntervenableModel``). Qwen3's decoder module tree is Qwen2's (``model.layers[l].self_attn
|
|
5
|
+
.{q,k,v,o}_proj``, ``mlp``), so ``register_qwen3()`` copies the Qwen2 entries of
|
|
6
|
+
``type_to_module_mapping`` and ``type_to_dimension_mapping`` to the Qwen3 classes (verified on
|
|
7
|
+
Qwen3-0.6B-Base). Idempotent.
|
|
8
|
+
|
|
9
|
+
``value_cell_config(layer, kv, head_dim)``: the pyvene config of mdb's cell
|
|
10
|
+
``cache.L<l>.v[kv<g>,row=r]`` as a sequence-scope interchange at position ``r`` of
|
|
11
|
+
``model.layers[l].self_attn.v_proj.output`` restricted to the KV group's ``head_dim`` columns
|
|
12
|
+
(a ``subspace_partition`` of the projection output). mdb's ``set_cell`` at the same cell with
|
|
13
|
+
prefill <= r reproduces it (both change every reader of row r at layer l).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def register_qwen3() -> list[str]:
|
|
22
|
+
"""Alias of ``mdb.interop.pyvene_names.qwen3_shim`` (one shim; kept for older scripts)."""
|
|
23
|
+
from .pyvene_names import qwen3_shim
|
|
24
|
+
|
|
25
|
+
return qwen3_shim()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def value_cell_config(layer: int, kv: int, head_dim: int, num_kv: int) -> dict[str, Any]:
|
|
29
|
+
"""The pyvene representation config of value cell ``cache.L<layer>.v[kv<kv>]`` (the row is
|
|
30
|
+
the ``unit_locations`` position at call time)."""
|
|
31
|
+
import pyvene as pv
|
|
32
|
+
|
|
33
|
+
return {"layer": layer, "component": f"model.layers[{layer}].self_attn.v_proj.output",
|
|
34
|
+
"unit": "pos", "max_number_of_units": 1,
|
|
35
|
+
"intervention_type": pv.VanillaIntervention,
|
|
36
|
+
"subspace_partition": [[i * head_dim, (i + 1) * head_dim] for i in range(num_kv)],
|
|
37
|
+
"kv": kv}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
__all__ = ["register_qwen3", "value_cell_config"]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""pyvene interop: the Qwen3 model-card shim and the specs of mdb addresses
|
|
2
|
+
(``core.foreign_names`` attaches the specs to symbol-table rows).
|
|
3
|
+
|
|
4
|
+
pyvene 0.1.8 has Qwen2 entries only, so ``IntervenableModel`` on a Qwen3 model raises
|
|
5
|
+
``KeyError: Qwen3ForCausalLM``. Qwen3's decoder modules carry the same names as Qwen2's
|
|
6
|
+
(``layers[l].self_attn.{q,k,v,o}_proj``, ``layers[l].mlp``), so ``qwen3_shim`` copies the
|
|
7
|
+
Qwen2 entries of ``pyvene.models.intervenable_modelcard`` to the Qwen3 classes (the workaround).
|
|
8
|
+
Residual sites use an explicit module
|
|
9
|
+
path (``"model.layers[l].output"``, unit ``pos``), which needs no model-card entry.
|
|
10
|
+
|
|
11
|
+
Measured on tiny Qwen3 (``tests/test_interop_symtab.py``): ``collect`` of a value cell's spec
|
|
12
|
+
(``head_value_output``, unit ``h.pos``) equals mdb's cache cell, and of a ``h_out`` spec equals
|
|
13
|
+
mdb's ``t<r>.L<l>.h_out``, within float32 rounding.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
_CELL = re.compile(r"^cache\.L(\d+)\.v\[kv(\d+),row=(\d+)\]$")
|
|
22
|
+
_PORT = re.compile(r"^t(\d+)\.L(\d+)\.(h_out|h)$")
|
|
23
|
+
_PAIRS = (("Qwen2Model", "Qwen3Model"), ("Qwen2ForCausalLM", "Qwen3ForCausalLM"),
|
|
24
|
+
("Qwen2ForSequenceClassification", "Qwen3ForSequenceClassification"))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def qwen3_shim() -> list[str]:
|
|
28
|
+
"""Give pyvene's model card Qwen3 entries copied from Qwen2 (idempotent); the classes added."""
|
|
29
|
+
from pyvene.models import intervenable_modelcard as card
|
|
30
|
+
from transformers.models.qwen2 import modeling_qwen2 as q2
|
|
31
|
+
from transformers.models.qwen3 import modeling_qwen3 as q3
|
|
32
|
+
|
|
33
|
+
added = []
|
|
34
|
+
for old, new in _PAIRS:
|
|
35
|
+
src, dst = getattr(q2, old, None), getattr(q3, new, None)
|
|
36
|
+
if src is None or dst is None or src not in card.type_to_module_mapping:
|
|
37
|
+
continue
|
|
38
|
+
if dst not in card.type_to_module_mapping:
|
|
39
|
+
card.type_to_module_mapping[dst] = card.type_to_module_mapping[src]
|
|
40
|
+
card.type_to_dimension_mapping[dst] = card.type_to_dimension_mapping[src]
|
|
41
|
+
added.append(new)
|
|
42
|
+
return added
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def spec(address: str) -> dict[str, Any]:
|
|
46
|
+
"""The pyvene representation of an mdb address: ``cache.L<l>.v[kv<g>,row=<r>]`` (one KV
|
|
47
|
+
head's value at one position) or ``t<r>.L<l>.h_out`` / ``t<r>.L<l>.h`` (the residual
|
|
48
|
+
leaving / entering block ``l``). ``unit_locations`` is in pyvene's call form."""
|
|
49
|
+
text = address.replace(" ", "")
|
|
50
|
+
match = _CELL.match(text)
|
|
51
|
+
if match:
|
|
52
|
+
layer, kv, row = (int(x) for x in match.groups())
|
|
53
|
+
return {"layer": layer, "component": "head_value_output", "unit": "h.pos",
|
|
54
|
+
"unit_locations": (([[kv]], [[row]]),)}
|
|
55
|
+
match = _PORT.match(text)
|
|
56
|
+
if match:
|
|
57
|
+
row, layer, port = int(match[1]), int(match[2]), match[3]
|
|
58
|
+
component = f"model.layers[{layer}].output" if port == "h_out" else "block_input"
|
|
59
|
+
return {"layer": layer, "component": component, "unit": "pos",
|
|
60
|
+
"unit_locations": [[[row]]]}
|
|
61
|
+
raise KeyError(f"no pyvene spec for {address!r} (a value cell or t<r>.L<l>.h|h_out)")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def collect(model: Any, tokens: list[int], address: str) -> Any:
|
|
65
|
+
"""The value pyvene's ``CollectIntervention`` gathers at ``address``'s spec in one forward
|
|
66
|
+
of ``tokens`` (batch 1)."""
|
|
67
|
+
import pyvene as pv
|
|
68
|
+
import torch
|
|
69
|
+
|
|
70
|
+
qwen3_shim()
|
|
71
|
+
found = spec(address)
|
|
72
|
+
config = pv.IntervenableConfig(representations=[pv.RepresentationConfig(
|
|
73
|
+
layer=found["layer"], component=found["component"], unit=found["unit"],
|
|
74
|
+
max_number_of_units=1, intervention_type=pv.CollectIntervention)])
|
|
75
|
+
wrapped = pv.IntervenableModel(config, model)
|
|
76
|
+
ids = torch.tensor([list(tokens)], device=next(model.parameters()).device)
|
|
77
|
+
with torch.no_grad():
|
|
78
|
+
out = wrapped({"input_ids": ids}, unit_locations={"base": found["unit_locations"]})
|
|
79
|
+
return out[0][1][0]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
__all__ = ["collect", "qwen3_shim", "spec"]
|