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/engine/trace.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
"""Passive capture of named ports during a forward the caller already runs (``mdb.trace``).
|
|
2
|
+
|
|
3
|
+
with mdb.trace(model, ports=["L1.p", "L1.m", "L0.h"]) as t:
|
|
4
|
+
model(input_ids) # any forward: batch > 1, sdpa, generate, training
|
|
5
|
+
t["L1.m"] # the value native code produced (one traced call)
|
|
6
|
+
t["L1.m", 1] # the value of the second call
|
|
7
|
+
t.info("L1.p") # state, authority, reason, kind, shape, dtype, axes
|
|
8
|
+
t.record() # sealed JSON (<= 64 KiB, no arrays): digests, labels
|
|
9
|
+
|
|
10
|
+
``mdb.attach`` drives the model itself, one sequence at a time. A trace only watches: it
|
|
11
|
+
installs forward hooks at the sites the family's port program names (``PortSpec.site`` and
|
|
12
|
+
``PortSpec.hook``, the table the stepping debugger uses) and registers itself with the one
|
|
13
|
+
process-wide eager-attention interceptor of ``mdb.engine.ports``. Every hook returns nothing
|
|
14
|
+
and the interceptor returns the native result object, so the forward's outputs are unchanged
|
|
15
|
+
bit for bit. A port name means what it means in the stepper: on the same native call (one
|
|
16
|
+
token on top of the same key/value cache) the captured value equals ``Run.read`` bit for bit.
|
|
17
|
+
|
|
18
|
+
Calls. One call is one outermost forward of the model's decoder stack (``model.base_model``,
|
|
19
|
+
``model.model`` for Qwen) in the thread that entered the ``with`` block; several forwards in
|
|
20
|
+
one block give several calls, kept in order. A layer called directly, outside the stack, and
|
|
21
|
+
forwards from other threads pass through uncaptured.
|
|
22
|
+
|
|
23
|
+
Rows. Values keep the batch dimension and every row of the call. Each port's axes come from
|
|
24
|
+
the program (``t.info(address)["axes"]``): most ports are ``(batch, row, ...)``, so batch
|
|
25
|
+
item ``b``, row ``r`` is ``t[address][b, r]``; ``qr`` is ``(batch, head, row, head_dim)``,
|
|
26
|
+
``kr`` is ``(batch, kv_head, src, head_dim)`` and ``s``, ``p`` are ``(batch, head, row, src)``,
|
|
27
|
+
so their row is ``t[address][b, :, r]``. ``row`` counts the tokens this call fed in; ``src``
|
|
28
|
+
counts every position attention saw (cached ones included).
|
|
29
|
+
|
|
30
|
+
Labels. A captured port is ``measured``, ``kind: native``. ``s`` (the pre-softmax scores) is
|
|
31
|
+
not a native intermediate: it is computed from the captured ``qr`` and ``kr`` and the mask the
|
|
32
|
+
native eager call received, by the native expression, and labelled ``derived-exact``,
|
|
33
|
+
``kind: replica``; ``softmax(s)`` must equal the native ``p`` bit for bit or ``s`` is refused.
|
|
34
|
+
|
|
35
|
+
Refusals (state ``refused``, ``authority`` None, a ``reason``; never a wrong tensor):
|
|
36
|
+
``qr``, ``kr``, ``s`` and ``p`` when the layer did not run eager attention (sdpa and other
|
|
37
|
+
kernels); ``s`` and ``p`` when attention dropout is active; every port of a layer that did not
|
|
38
|
+
run in the call; every value after the ``max_bytes`` cap would be exceeded (default 1 GiB,
|
|
39
|
+
counted over the captured copies; capture stops there for the rest of the trace).
|
|
40
|
+
|
|
41
|
+
Captured values are detached copies on the device that produced them (a copy, because a cache
|
|
42
|
+
may later be written in place). Hooks and the interceptor registration are removed when the
|
|
43
|
+
block exits, also when the forward raises. One trace may be active per process: a second
|
|
44
|
+
``trace`` (nested or concurrent) is refused.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
import re
|
|
50
|
+
import threading
|
|
51
|
+
from collections.abc import Iterable
|
|
52
|
+
from dataclasses import dataclass, field
|
|
53
|
+
from typing import Any
|
|
54
|
+
|
|
55
|
+
import torch
|
|
56
|
+
|
|
57
|
+
from saturn.core import own_hook
|
|
58
|
+
|
|
59
|
+
from mdb.core.errors import BadArgs, Refused
|
|
60
|
+
from mdb.core.pointers import RecordError, check_bounded, seal_digest
|
|
61
|
+
|
|
62
|
+
from .ports import _acquire, _equality, _release, config_refusal, program_for, tensor_digest
|
|
63
|
+
|
|
64
|
+
DEFAULT_MAX_BYTES = 1 << 30
|
|
65
|
+
SCHEMA = "mdb-trace-v1"
|
|
66
|
+
EAGER_PORTS = ("qr", "kr", "s", "p")
|
|
67
|
+
_ADDRESS = re.compile(r"L(?P<layer>\d+)\.(?P<port>\w+)")
|
|
68
|
+
_LOCK = threading.Lock()
|
|
69
|
+
_ACTIVE: list[Trace] = []
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class _Call:
|
|
74
|
+
"""What one outermost forward of the decoder stack left behind."""
|
|
75
|
+
|
|
76
|
+
index: int
|
|
77
|
+
attention: str | None
|
|
78
|
+
values: dict[str, torch.Tensor] = field(default_factory=dict)
|
|
79
|
+
refused: dict[str, str] = field(default_factory=dict)
|
|
80
|
+
replica: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
81
|
+
layers: set[int] = field(default_factory=set)
|
|
82
|
+
eager: set[int] = field(default_factory=set)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class _AttentionTap:
|
|
86
|
+
"""The trace's owner entry in the eager-attention interceptor for one layer.
|
|
87
|
+
|
|
88
|
+
Implements the two methods the interceptor calls on an owner (``_engaged`` and
|
|
89
|
+
``_eager``); ``_eager`` returns the native function's own result.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
def __init__(self, trace: Trace, layer: int):
|
|
93
|
+
self.trace = trace
|
|
94
|
+
self.layer = layer
|
|
95
|
+
|
|
96
|
+
def _engaged(self) -> bool:
|
|
97
|
+
return self.trace._engaged(self.layer)
|
|
98
|
+
|
|
99
|
+
def _eager(self, patch, module, query, key, value, attention_mask, *args, **kwargs):
|
|
100
|
+
trace, layer = self.trace, self.layer
|
|
101
|
+
trace._calls[-1].eager.add(layer)
|
|
102
|
+
trace._capture(layer, "qr", query)
|
|
103
|
+
trace._capture(layer, "kr", key)
|
|
104
|
+
output = patch.original(module, query, key, value, attention_mask, *args, **kwargs)
|
|
105
|
+
weights = output[1]
|
|
106
|
+
if module.training and kwargs.get("dropout", 0.0):
|
|
107
|
+
reason = "attention dropout is active (training mode): p is not softmax(s)"
|
|
108
|
+
trace._refuse(layer, "s", reason)
|
|
109
|
+
trace._refuse(layer, "p", reason)
|
|
110
|
+
return output
|
|
111
|
+
if trace._wants(layer, "s"):
|
|
112
|
+
trace._scores(layer, patch, module, query, key, attention_mask, weights, kwargs)
|
|
113
|
+
trace._capture(layer, "p", weights)
|
|
114
|
+
return output
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class Trace:
|
|
118
|
+
"""Passive port capture over the forwards run inside one ``with`` block.
|
|
119
|
+
|
|
120
|
+
``ports``: addresses ``L<layer>.<port>`` of the model's port program. ``max_bytes``: cap on
|
|
121
|
+
the bytes of captured copies (default 1 GiB). ``project``: must be None (persistence is not
|
|
122
|
+
built yet). See the module docstring for calls, rows, labels and refusals.
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
model: Any,
|
|
128
|
+
ports: Iterable[str],
|
|
129
|
+
*,
|
|
130
|
+
max_bytes: int = DEFAULT_MAX_BYTES,
|
|
131
|
+
project: Any = None,
|
|
132
|
+
):
|
|
133
|
+
if project is not None:
|
|
134
|
+
raise Refused(
|
|
135
|
+
"mdb.trace does not write to a project; call it without project= (a debugger "
|
|
136
|
+
"attached with a project records cuts and records)"
|
|
137
|
+
)
|
|
138
|
+
if type(max_bytes) is not int or max_bytes <= 0:
|
|
139
|
+
raise BadArgs("max_bytes must be a positive integer")
|
|
140
|
+
config = getattr(model, "config", None)
|
|
141
|
+
backbone = getattr(model, "base_model", None)
|
|
142
|
+
layers = getattr(backbone, "layers", None)
|
|
143
|
+
if config is None or layers is None:
|
|
144
|
+
raise Refused("trace needs a loaded Hugging Face decoder (model.base_model.layers)")
|
|
145
|
+
try:
|
|
146
|
+
self.program = program_for(getattr(config, "model_type", None))
|
|
147
|
+
except ValueError as error:
|
|
148
|
+
raise Refused(str(error)) from None
|
|
149
|
+
refusal = config_refusal(self.program.family, config)
|
|
150
|
+
if refusal is not None:
|
|
151
|
+
raise Refused(refusal)
|
|
152
|
+
if isinstance(ports, str):
|
|
153
|
+
raise BadArgs("ports is a list of addresses, e.g. ['L0.m']")
|
|
154
|
+
self.model = model
|
|
155
|
+
self.max_bytes = max_bytes
|
|
156
|
+
self.ports = tuple(dict.fromkeys(self._parse(address, len(layers)) for address in ports))
|
|
157
|
+
if not self.ports:
|
|
158
|
+
raise BadArgs("name at least one port, e.g. ports=['L0.m']")
|
|
159
|
+
self._backbone = backbone
|
|
160
|
+
self._layers = layers
|
|
161
|
+
self._wanted: dict[int, set[str]] = {}
|
|
162
|
+
for address in self.ports:
|
|
163
|
+
layer, port = self._split(address)
|
|
164
|
+
self._wanted.setdefault(layer, set()).add(port)
|
|
165
|
+
self._calls: list[_Call] = []
|
|
166
|
+
self._held = 0
|
|
167
|
+
self._stopped: str | None = None
|
|
168
|
+
self._handles: list[Any] = []
|
|
169
|
+
self._patches: list[tuple[Any, Any]] = []
|
|
170
|
+
self._thread: int | None = None
|
|
171
|
+
self._depth = 0
|
|
172
|
+
self._layer_depth: dict[int, int] = {}
|
|
173
|
+
self._entered = False
|
|
174
|
+
|
|
175
|
+
# --- addresses ----------------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
def _parse(self, address: Any, layers: int) -> str:
|
|
178
|
+
match = _ADDRESS.fullmatch(address.strip()) if isinstance(address, str) else None
|
|
179
|
+
if match is None:
|
|
180
|
+
raise BadArgs(f"trace ports are L<layer>.<port> addresses, got {address!r}")
|
|
181
|
+
layer, port = int(match["layer"]), match["port"]
|
|
182
|
+
if layer >= layers:
|
|
183
|
+
raise BadArgs(f"layer {layer} does not exist in a {layers}-layer model")
|
|
184
|
+
try:
|
|
185
|
+
name = self.program.spec(port).name
|
|
186
|
+
except ValueError as error:
|
|
187
|
+
raise BadArgs(str(error)) from None
|
|
188
|
+
return f"L{layer}.{name}"
|
|
189
|
+
|
|
190
|
+
@staticmethod
|
|
191
|
+
def _split(address: str) -> tuple[int, str]:
|
|
192
|
+
match = _ADDRESS.fullmatch(address)
|
|
193
|
+
return int(match["layer"]), match["port"]
|
|
194
|
+
|
|
195
|
+
def _wants(self, layer: int, port: str) -> bool:
|
|
196
|
+
return port in self._wanted.get(layer, ())
|
|
197
|
+
|
|
198
|
+
# --- install / remove ---------------------------------------------------------------
|
|
199
|
+
|
|
200
|
+
def __enter__(self) -> Trace:
|
|
201
|
+
if self._entered:
|
|
202
|
+
raise Refused("a trace is entered once; start a new mdb.trace for more forwards")
|
|
203
|
+
with _LOCK:
|
|
204
|
+
if _ACTIVE:
|
|
205
|
+
raise Refused(
|
|
206
|
+
"a trace is already active in this process (nested or concurrent traces "
|
|
207
|
+
"are refused)"
|
|
208
|
+
)
|
|
209
|
+
_ACTIVE.append(self)
|
|
210
|
+
self._entered = True
|
|
211
|
+
self._thread = threading.get_ident()
|
|
212
|
+
try:
|
|
213
|
+
self._install()
|
|
214
|
+
except BaseException:
|
|
215
|
+
self._remove()
|
|
216
|
+
raise
|
|
217
|
+
return self
|
|
218
|
+
|
|
219
|
+
def __exit__(self, *exc: Any) -> bool:
|
|
220
|
+
self._remove()
|
|
221
|
+
return False
|
|
222
|
+
|
|
223
|
+
def _install(self) -> None:
|
|
224
|
+
self._handles.append(self._backbone.register_forward_pre_hook(self._begin))
|
|
225
|
+
self._handles.append(
|
|
226
|
+
self._backbone.register_forward_hook(self._end, always_call=True)
|
|
227
|
+
)
|
|
228
|
+
modeling = self.program.modeling_module()
|
|
229
|
+
for layer in sorted(self._wanted):
|
|
230
|
+
module = self._layers[layer]
|
|
231
|
+
self._layer_depth[layer] = 0
|
|
232
|
+
self._handles.append(
|
|
233
|
+
module.register_forward_pre_hook(self._enter(layer), with_kwargs=True)
|
|
234
|
+
)
|
|
235
|
+
for port in self.program.ports:
|
|
236
|
+
if port.name not in self._wanted[layer] or not port.site:
|
|
237
|
+
continue
|
|
238
|
+
if port.hook == "pre":
|
|
239
|
+
hook = self._pre(layer, port.name)
|
|
240
|
+
handle = module.get_submodule(port.site).register_forward_pre_hook(
|
|
241
|
+
hook, with_kwargs=True
|
|
242
|
+
)
|
|
243
|
+
elif port.hook == "out":
|
|
244
|
+
hook = self._out(layer, port.name)
|
|
245
|
+
handle = module.get_submodule(port.site).register_forward_hook(hook)
|
|
246
|
+
else:
|
|
247
|
+
continue
|
|
248
|
+
self._handles.append(handle)
|
|
249
|
+
self._handles.append(module.register_forward_hook(self._exit(layer), always_call=True))
|
|
250
|
+
if self._wanted[layer] & set(EAGER_PORTS):
|
|
251
|
+
attention = module.self_attn
|
|
252
|
+
patch = _acquire(_AttentionTap(self, layer), modeling, attention)
|
|
253
|
+
self._patches.append((patch, attention))
|
|
254
|
+
|
|
255
|
+
def _remove(self) -> None:
|
|
256
|
+
try:
|
|
257
|
+
for handle in self._handles:
|
|
258
|
+
handle.remove()
|
|
259
|
+
for patch, attention in self._patches:
|
|
260
|
+
_release(patch, attention)
|
|
261
|
+
finally:
|
|
262
|
+
self._handles, self._patches = [], []
|
|
263
|
+
self._depth = 0
|
|
264
|
+
self._layer_depth = {layer: 0 for layer in self._layer_depth}
|
|
265
|
+
with _LOCK:
|
|
266
|
+
if self in _ACTIVE:
|
|
267
|
+
_ACTIVE.remove(self)
|
|
268
|
+
|
|
269
|
+
# --- hooks --------------------------------------------------------------------------
|
|
270
|
+
|
|
271
|
+
def _mine(self) -> bool:
|
|
272
|
+
return threading.get_ident() == self._thread
|
|
273
|
+
|
|
274
|
+
def _engaged(self, layer: int) -> bool:
|
|
275
|
+
"""Inside an outermost stack forward and the outermost entry of ``layer``, in the
|
|
276
|
+
thread that entered the trace."""
|
|
277
|
+
return self._mine() and self._depth == 1 and self._layer_depth.get(layer) == 1
|
|
278
|
+
|
|
279
|
+
@own_hook
|
|
280
|
+
def _begin(self, module: Any, args: tuple[Any, ...]) -> None:
|
|
281
|
+
if not self._mine():
|
|
282
|
+
return
|
|
283
|
+
self._depth += 1
|
|
284
|
+
if self._depth == 1:
|
|
285
|
+
attention = getattr(self.model.config, "_attn_implementation", None)
|
|
286
|
+
self._calls.append(_Call(len(self._calls), attention))
|
|
287
|
+
|
|
288
|
+
@own_hook
|
|
289
|
+
def _end(self, module: Any, args: tuple[Any, ...], output: Any) -> None:
|
|
290
|
+
if self._mine():
|
|
291
|
+
self._depth = max(self._depth - 1, 0)
|
|
292
|
+
|
|
293
|
+
def _enter(self, layer: int):
|
|
294
|
+
@own_hook
|
|
295
|
+
def hook(module: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
|
|
296
|
+
if not self._mine():
|
|
297
|
+
return
|
|
298
|
+
self._layer_depth[layer] += 1
|
|
299
|
+
if self._engaged(layer):
|
|
300
|
+
self._calls[-1].layers.add(layer)
|
|
301
|
+
if self._wants(layer, "h"):
|
|
302
|
+
self._capture(layer, "h", _first(args, kwargs))
|
|
303
|
+
|
|
304
|
+
return hook
|
|
305
|
+
|
|
306
|
+
def _exit(self, layer: int):
|
|
307
|
+
@own_hook
|
|
308
|
+
def hook(module: Any, args: tuple[Any, ...], output: Any) -> None:
|
|
309
|
+
if not self._mine():
|
|
310
|
+
return
|
|
311
|
+
if self._engaged(layer) and output is not None and self._wants(layer, "h_out"):
|
|
312
|
+
self._capture(layer, "h_out", output[0] if isinstance(output, tuple) else output)
|
|
313
|
+
self._layer_depth[layer] = max(self._layer_depth[layer] - 1, 0)
|
|
314
|
+
|
|
315
|
+
return hook
|
|
316
|
+
|
|
317
|
+
def _pre(self, layer: int, port: str):
|
|
318
|
+
@own_hook
|
|
319
|
+
def hook(module: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
|
|
320
|
+
if self._engaged(layer):
|
|
321
|
+
self._capture(layer, port, _first(args, kwargs))
|
|
322
|
+
|
|
323
|
+
return hook
|
|
324
|
+
|
|
325
|
+
def _out(self, layer: int, port: str):
|
|
326
|
+
@own_hook
|
|
327
|
+
def hook(module: Any, args: tuple[Any, ...], output: Any) -> None:
|
|
328
|
+
if self._engaged(layer):
|
|
329
|
+
self._capture(layer, port, output[0] if isinstance(output, tuple) else output)
|
|
330
|
+
|
|
331
|
+
return hook
|
|
332
|
+
|
|
333
|
+
# --- capture ------------------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
def _refuse(self, layer: int, port: str, reason: str) -> None:
|
|
336
|
+
if self._wants(layer, port):
|
|
337
|
+
self._calls[-1].refused[f"L{layer}.{port}"] = reason
|
|
338
|
+
|
|
339
|
+
def _capture(self, layer: int, port: str, value: Any) -> None:
|
|
340
|
+
if not self._wants(layer, port) or not isinstance(value, torch.Tensor):
|
|
341
|
+
return
|
|
342
|
+
call = self._calls[-1]
|
|
343
|
+
address = f"L{layer}.{port}"
|
|
344
|
+
if self._stopped is None:
|
|
345
|
+
size = value.numel() * value.element_size()
|
|
346
|
+
if self._held + size > self.max_bytes:
|
|
347
|
+
self._stopped = (
|
|
348
|
+
f"capture stopped: max_bytes={self.max_bytes} would be exceeded at call "
|
|
349
|
+
f"{call.index}, {address} ({size} bytes on top of {self._held} held); no "
|
|
350
|
+
"later value of this trace is captured"
|
|
351
|
+
)
|
|
352
|
+
else:
|
|
353
|
+
call.values[address] = value.detach().clone()
|
|
354
|
+
self._held += size
|
|
355
|
+
return
|
|
356
|
+
call.refused[address] = self._stopped
|
|
357
|
+
|
|
358
|
+
def _scores(self, layer, patch, module, query, key, attention_mask, weights, kwargs) -> None:
|
|
359
|
+
"""``s`` by the native expression on the captured operands, checked against ``p``."""
|
|
360
|
+
with torch.no_grad():
|
|
361
|
+
scaling = kwargs.get("scaling", getattr(module, "scaling", None))
|
|
362
|
+
keys = patch.repeat_kv(key.detach(), module.num_key_value_groups)
|
|
363
|
+
scores = torch.matmul(query.detach(), keys.transpose(2, 3)) * scaling
|
|
364
|
+
if attention_mask is not None:
|
|
365
|
+
scores = scores + attention_mask
|
|
366
|
+
reference = torch.nn.functional.softmax(scores, dim=-1, dtype=torch.float32).to(
|
|
367
|
+
query.dtype
|
|
368
|
+
)
|
|
369
|
+
check = _equality(reference, weights.detach())
|
|
370
|
+
self._calls[-1].replica[f"L{layer}.s"] = check
|
|
371
|
+
if not check["equal"]:
|
|
372
|
+
self._refuse(
|
|
373
|
+
layer, "s",
|
|
374
|
+
f"replica check failed: max |softmax(s) - p| = {check['max_abs_diff']}",
|
|
375
|
+
)
|
|
376
|
+
return
|
|
377
|
+
self._capture(layer, "s", scores)
|
|
378
|
+
|
|
379
|
+
# --- reading ------------------------------------------------------------------------
|
|
380
|
+
|
|
381
|
+
@property
|
|
382
|
+
def calls(self) -> int:
|
|
383
|
+
"""Number of traced calls (outermost decoder-stack forwards)."""
|
|
384
|
+
return len(self._calls)
|
|
385
|
+
|
|
386
|
+
def _call(self, call: int | None) -> _Call | None:
|
|
387
|
+
if call is None:
|
|
388
|
+
if len(self._calls) > 1:
|
|
389
|
+
raise BadArgs(
|
|
390
|
+
f"{len(self._calls)} calls were traced; name one: t[address, i] or "
|
|
391
|
+
"t.info(address, call=i)"
|
|
392
|
+
)
|
|
393
|
+
return self._calls[0] if self._calls else None
|
|
394
|
+
if type(call) is not int or not -len(self._calls) <= call < len(self._calls):
|
|
395
|
+
raise BadArgs(f"call {call!r} is out of range ({len(self._calls)} traced)")
|
|
396
|
+
return self._calls[call]
|
|
397
|
+
|
|
398
|
+
def _address(self, address: str) -> str:
|
|
399
|
+
name = self._parse(address, len(self._layers))
|
|
400
|
+
if name not in self.ports:
|
|
401
|
+
raise BadArgs(f"{name} was not requested; ports: {', '.join(self.ports)}")
|
|
402
|
+
return name
|
|
403
|
+
|
|
404
|
+
def info(self, address: str, call: int | None = None) -> dict[str, Any]:
|
|
405
|
+
"""How the value at ``address`` in one call was obtained. Always these keys:
|
|
406
|
+
``address, call, state, authority, reason, kind, shape, dtype, axes, replica_equal,
|
|
407
|
+
max_abs_diff, max_abs_diff_authority``."""
|
|
408
|
+
name = self._address(address)
|
|
409
|
+
chosen = self._call(call)
|
|
410
|
+
layer, port = self._split(name)
|
|
411
|
+
info: dict[str, Any] = {
|
|
412
|
+
"address": name,
|
|
413
|
+
"call": None if chosen is None else chosen.index,
|
|
414
|
+
"state": "refused",
|
|
415
|
+
"authority": None,
|
|
416
|
+
"reason": None,
|
|
417
|
+
"kind": None,
|
|
418
|
+
"shape": None,
|
|
419
|
+
"dtype": None,
|
|
420
|
+
"axes": list(self.program.spec(port).axes),
|
|
421
|
+
"replica_equal": None,
|
|
422
|
+
"max_abs_diff": None,
|
|
423
|
+
"max_abs_diff_authority": None,
|
|
424
|
+
}
|
|
425
|
+
if chosen is not None and name in chosen.replica:
|
|
426
|
+
check = chosen.replica[name]
|
|
427
|
+
info["replica_equal"] = bool(check["equal"])
|
|
428
|
+
info["max_abs_diff"] = float(check.get("max_abs_diff", 0.0))
|
|
429
|
+
info["max_abs_diff_authority"] = "measured"
|
|
430
|
+
value = None if chosen is None else chosen.values.get(name)
|
|
431
|
+
if value is None:
|
|
432
|
+
info["reason"] = self._reason(chosen, layer, port)
|
|
433
|
+
return info
|
|
434
|
+
replica = port == "s"
|
|
435
|
+
info.update(
|
|
436
|
+
state="resolved",
|
|
437
|
+
authority="derived-exact" if replica else "measured",
|
|
438
|
+
kind="replica" if replica else "native",
|
|
439
|
+
shape=list(value.shape),
|
|
440
|
+
dtype=str(value.dtype),
|
|
441
|
+
)
|
|
442
|
+
return info
|
|
443
|
+
|
|
444
|
+
def _reason(self, call: _Call | None, layer: int, port: str) -> str:
|
|
445
|
+
if call is None:
|
|
446
|
+
return "no forward of the model's decoder stack ran inside the trace"
|
|
447
|
+
name = f"L{layer}.{port}"
|
|
448
|
+
if name in call.refused:
|
|
449
|
+
return call.refused[name]
|
|
450
|
+
if layer not in call.layers:
|
|
451
|
+
return f"layer {layer} did not run in call {call.index}"
|
|
452
|
+
if port in EAGER_PORTS and layer not in call.eager:
|
|
453
|
+
if call.attention != "eager":
|
|
454
|
+
return (
|
|
455
|
+
f"attention implementation is {call.attention!r}: qr, kr, s and p exist "
|
|
456
|
+
"only inside eager attention (load with attn_implementation='eager')"
|
|
457
|
+
)
|
|
458
|
+
return f"eager attention did not run in layer {layer} during call {call.index}"
|
|
459
|
+
return (
|
|
460
|
+
f"port {port} did not fire in layer {layer} during call {call.index} (the forward "
|
|
461
|
+
"stopped before it)"
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
def __getitem__(self, key: str | tuple[str, int]) -> torch.Tensor:
|
|
465
|
+
"""``t[address]`` (exactly one call traced) or ``t[address, call]``: the captured copy.
|
|
466
|
+
A refused value raises ``Refused`` with its reason."""
|
|
467
|
+
address, call = key if isinstance(key, tuple) else (key, None)
|
|
468
|
+
info = self.info(address, call)
|
|
469
|
+
if info["state"] != "resolved":
|
|
470
|
+
raise Refused(f"{info['address']}: {info['reason']}")
|
|
471
|
+
return self._calls[info["call"]].values[info["address"]]
|
|
472
|
+
|
|
473
|
+
def record(self, calls: Iterable[int] | None = None) -> dict[str, Any]:
|
|
474
|
+
"""Sealed JSON of what was traced: per call and address the ``info`` fields plus the
|
|
475
|
+
sha256 of each captured value (``mdb.engine.ports.tensor_digest``), and a ``seal``
|
|
476
|
+
(``seal_digest`` of the rest). ``calls`` picks call indices (default: all). At most
|
|
477
|
+
64 KiB and no arrays; a larger record is refused (pick fewer calls)."""
|
|
478
|
+
indices = range(len(self._calls)) if calls is None else [int(c) for c in calls]
|
|
479
|
+
chosen = [self._call(index) for index in indices]
|
|
480
|
+
entries = []
|
|
481
|
+
for item in chosen:
|
|
482
|
+
values = {}
|
|
483
|
+
for address in self.ports:
|
|
484
|
+
entry = self.info(address, item.index)
|
|
485
|
+
del entry["address"], entry["call"]
|
|
486
|
+
if entry["state"] == "resolved":
|
|
487
|
+
entry["sha256"] = tensor_digest(item.values[address])
|
|
488
|
+
values[address] = entry
|
|
489
|
+
entries.append(
|
|
490
|
+
{
|
|
491
|
+
"call": item.index,
|
|
492
|
+
"attention": item.attention,
|
|
493
|
+
"layers_run": sorted(item.layers),
|
|
494
|
+
"values": values,
|
|
495
|
+
}
|
|
496
|
+
)
|
|
497
|
+
parameter = next(self.model.parameters(), None)
|
|
498
|
+
body = {
|
|
499
|
+
"schema": SCHEMA,
|
|
500
|
+
"model": {
|
|
501
|
+
"family": self.program.family,
|
|
502
|
+
"layers": len(self._layers),
|
|
503
|
+
"dtype": None if parameter is None else str(parameter.dtype),
|
|
504
|
+
"device": None if parameter is None else str(parameter.device),
|
|
505
|
+
},
|
|
506
|
+
"ports": list(self.ports),
|
|
507
|
+
"budget": {"max_bytes": self.max_bytes, "held_bytes": self._held},
|
|
508
|
+
"calls_total": len(self._calls),
|
|
509
|
+
"calls": entries,
|
|
510
|
+
}
|
|
511
|
+
try:
|
|
512
|
+
body = check_bounded(body, "trace record")
|
|
513
|
+
return check_bounded({**body, "seal": seal_digest(body)}, "trace record")
|
|
514
|
+
except RecordError as error:
|
|
515
|
+
raise Refused(f"{error}; pick fewer calls with record(calls=...)") from None
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _first(args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
|
|
519
|
+
"""The module's input tensor: its first positional argument or ``hidden_states``."""
|
|
520
|
+
return args[0] if args else kwargs.get("hidden_states")
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def trace(
|
|
524
|
+
model: Any,
|
|
525
|
+
ports: Iterable[str],
|
|
526
|
+
*,
|
|
527
|
+
max_bytes: int = DEFAULT_MAX_BYTES,
|
|
528
|
+
project: Any = None,
|
|
529
|
+
) -> Trace:
|
|
530
|
+
"""Passive capture of ``ports`` during any forward run inside ``with trace(...) as t:``.
|
|
531
|
+
|
|
532
|
+
See the ``mdb.engine.trace`` module docstring. Raises ``BadArgs`` for a malformed or
|
|
533
|
+
unknown address and ``Refused`` for an unsupported model, a non-None ``project`` or a
|
|
534
|
+
second active trace.
|
|
535
|
+
"""
|
|
536
|
+
return Trace(model, ports, max_bytes=max_bytes, project=project)
|
mdb/interop/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""mdb <-> TransformerLens and nnsight.
|
|
2
|
+
|
|
3
|
+
- ``names``: one name table, mdb ports <-> TL hook names <-> nnsight paths, and the layout
|
|
4
|
+
conversions (torch-free).
|
|
5
|
+
- ``tl``: a TransformerBridge around the attached module; TL caches imported as mdb origins;
|
|
6
|
+
``mdb.trace`` captures exported as TL caches.
|
|
7
|
+
- ``nn``: nnsight reads by mdb address and ``batch_whatif`` (mdb edits measured over many
|
|
8
|
+
prompts in batched traces; cell edits in mdb's ``reader`` scope or ``sequence`` scope);
|
|
9
|
+
``grads`` (values and input gradients of a margin, one batched forward + backward).
|
|
10
|
+
- ``verify``: a claimed effect from another tool re-measured by mdb natively, with mdb's
|
|
11
|
+
sealed prediction and P20 verdict beside the claim.
|
|
12
|
+
|
|
13
|
+
Importing ``mdb.interop`` loads neither torch nor the tools; each submodule imports its tool
|
|
14
|
+
when used.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
__all__ = ["names", "tl", "nn", "verify"]
|