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/ports.py
ADDED
|
@@ -0,0 +1,1424 @@
|
|
|
1
|
+
"""Port programs for native pre-norm SwiGLU decoder layers (Qwen2, Qwen3, Llama, Mistral) and
|
|
2
|
+
the controller that drives them.
|
|
3
|
+
|
|
4
|
+
A port is a named value produced inside one native decoder-layer call. The controller
|
|
5
|
+
captures ports with forward hooks plus an intercept of the family's module-level
|
|
6
|
+
``eager_attention_forward``, applies staged edits by returning replacement tensors, and
|
|
7
|
+
raises a private ``PortStop`` at a target port. It never re-implements the layer: every
|
|
8
|
+
value comes from the native modules, except the two ports marked ``replica`` (``s``, and the
|
|
9
|
+
value mix after an ``s``/``p`` edit), which are replicas checked against native output on
|
|
10
|
+
every complete pass.
|
|
11
|
+
|
|
12
|
+
Authority labels used by this package (fixed vocabulary):
|
|
13
|
+
``measured | derived-exact | derived-local | bound | supplied``.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import importlib
|
|
20
|
+
import threading
|
|
21
|
+
from collections.abc import Iterable, Sequence
|
|
22
|
+
from contextlib import contextmanager
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
import torch
|
|
27
|
+
from saturn.core import PortStop, own_hook
|
|
28
|
+
|
|
29
|
+
ATTN = "attn"
|
|
30
|
+
MLP = "mlp"
|
|
31
|
+
EDIT_OPS = ("replace", "add", "scale")
|
|
32
|
+
|
|
33
|
+
_D = ("batch", "row", "d_model")
|
|
34
|
+
_QF = ("batch", "row", "head*head_dim")
|
|
35
|
+
_KF = ("batch", "row", "kv_head*head_dim")
|
|
36
|
+
_FF = ("batch", "row", "d_ff")
|
|
37
|
+
_SCORE = ("batch", "head", "row", "src")
|
|
38
|
+
|
|
39
|
+
CACHE = "cache"
|
|
40
|
+
PREV_LAYER = "prev_layer"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class PortSpec:
|
|
45
|
+
"""One port of a layer program: where it is captured and how an edit there is realised.
|
|
46
|
+
|
|
47
|
+
``inputs`` are the producer edges: names of earlier ports of the same layer, or
|
|
48
|
+
``"cache"`` (the key/value cache rows of earlier tokens) or ``"prev_layer"`` (the previous
|
|
49
|
+
layer's committed output).
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
name: str
|
|
53
|
+
sublayer: str
|
|
54
|
+
site: str
|
|
55
|
+
hook: str
|
|
56
|
+
kind: str
|
|
57
|
+
axes: tuple[str, ...]
|
|
58
|
+
operator: str
|
|
59
|
+
proofs: tuple[str, ...]
|
|
60
|
+
edit: str
|
|
61
|
+
editable: bool = True
|
|
62
|
+
inputs: tuple[str, ...] = ()
|
|
63
|
+
|
|
64
|
+
def to_dict(self) -> dict[str, Any]:
|
|
65
|
+
return {
|
|
66
|
+
"name": self.name,
|
|
67
|
+
"sublayer": self.sublayer,
|
|
68
|
+
"site": self.site,
|
|
69
|
+
"hook": self.hook,
|
|
70
|
+
"kind": self.kind,
|
|
71
|
+
"axes": list(self.axes),
|
|
72
|
+
"operator": self.operator,
|
|
73
|
+
"proofs": list(self.proofs),
|
|
74
|
+
"edit": self.edit,
|
|
75
|
+
"editable": self.editable,
|
|
76
|
+
"inputs": list(self.inputs),
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def model_dims(config: Any) -> dict[str, int]:
|
|
81
|
+
"""Axis sizes of one decoder layer from a Hugging Face config (``src`` is added per call)."""
|
|
82
|
+
heads = int(config.num_attention_heads)
|
|
83
|
+
head_dim = getattr(config, "head_dim", None) or config.hidden_size // heads
|
|
84
|
+
return {
|
|
85
|
+
"batch": 1,
|
|
86
|
+
"row": 1,
|
|
87
|
+
"d_model": int(config.hidden_size),
|
|
88
|
+
"head": heads,
|
|
89
|
+
"kv_head": int(config.num_key_value_heads),
|
|
90
|
+
"head_dim": int(head_dim),
|
|
91
|
+
"d_ff": int(config.intermediate_size),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True)
|
|
96
|
+
class PortProgram:
|
|
97
|
+
"""Ordered ports of one decoder layer, in native execution order."""
|
|
98
|
+
|
|
99
|
+
family: str
|
|
100
|
+
modeling: str
|
|
101
|
+
ports: tuple[PortSpec, ...]
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def names(self) -> tuple[str, ...]:
|
|
105
|
+
return tuple(port.name for port in self.ports)
|
|
106
|
+
|
|
107
|
+
def spec(self, name: str) -> PortSpec:
|
|
108
|
+
for port in self.ports:
|
|
109
|
+
if port.name == name:
|
|
110
|
+
return port
|
|
111
|
+
raise ValueError(f"{self.family} has no port {name!r}; ports: {', '.join(self.names)}")
|
|
112
|
+
|
|
113
|
+
def index(self, name: str) -> int:
|
|
114
|
+
return self.names.index(self.spec(name).name)
|
|
115
|
+
|
|
116
|
+
def shape(self, name: str, config: Any, *, src: int) -> tuple[int, ...]:
|
|
117
|
+
"""Shape of a port for one decoder-step transition, from its axes and the model config.
|
|
118
|
+
|
|
119
|
+
``src`` is the number of source positions attention sees (tokens in the state).
|
|
120
|
+
"""
|
|
121
|
+
dims = {**model_dims(config), "src": int(src)}
|
|
122
|
+
out = []
|
|
123
|
+
for axis in self.spec(name).axes:
|
|
124
|
+
size = 1
|
|
125
|
+
for part in axis.split("*"):
|
|
126
|
+
size *= dims[part]
|
|
127
|
+
out.append(size)
|
|
128
|
+
return tuple(out)
|
|
129
|
+
|
|
130
|
+
def modeling_module(self) -> Any:
|
|
131
|
+
return importlib.import_module(self.modeling)
|
|
132
|
+
|
|
133
|
+
def sites(self) -> tuple[str, ...]:
|
|
134
|
+
return tuple(sorted({p.site for p in self.ports if p.hook in {"pre", "out"} and p.site}))
|
|
135
|
+
|
|
136
|
+
def to_dict(self) -> dict[str, Any]:
|
|
137
|
+
return {
|
|
138
|
+
"schema": "mdb-port-program-v1",
|
|
139
|
+
"family": self.family,
|
|
140
|
+
"modeling": self.modeling,
|
|
141
|
+
"ports": [port.to_dict() for port in self.ports],
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
_H_EDIT = (
|
|
146
|
+
"layer pre-hook replaces the layer input; the native layer binds residual to it, so the "
|
|
147
|
+
"skip path and the attention branch both see the edit (the same computation as writing "
|
|
148
|
+
"the boundary hidden for this one transition)"
|
|
149
|
+
)
|
|
150
|
+
_KR_REFUSAL = (
|
|
151
|
+
"kr holds cached rows and the native layer writes the cache before the eager call, so an "
|
|
152
|
+
"edit here could not reach the stored keys; edit k (or kn on Qwen3) to change the key row "
|
|
153
|
+
"this transition writes"
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _proj(
|
|
158
|
+
name: str,
|
|
159
|
+
site: str,
|
|
160
|
+
axes: tuple[str, ...],
|
|
161
|
+
operator: str,
|
|
162
|
+
inputs: tuple[str, ...],
|
|
163
|
+
extra: str = "",
|
|
164
|
+
) -> PortSpec:
|
|
165
|
+
return PortSpec(
|
|
166
|
+
name,
|
|
167
|
+
ATTN,
|
|
168
|
+
site,
|
|
169
|
+
"out",
|
|
170
|
+
"native",
|
|
171
|
+
axes,
|
|
172
|
+
operator,
|
|
173
|
+
("P04",),
|
|
174
|
+
f"{site} output replaced natively{extra}",
|
|
175
|
+
inputs=inputs,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@dataclass(frozen=True)
|
|
180
|
+
class Family:
|
|
181
|
+
"""One row of the family table. Every registered family runs the same native block shape:
|
|
182
|
+
``h -> input_layernorm (RMSNorm) -> q/k/v_proj [-> q_norm/k_norm] -> RoPE -> eager attention
|
|
183
|
+
-> o_proj -> + h -> post_attention_layernorm (RMSNorm) -> act_fn(gate_proj) * up_proj ->
|
|
184
|
+
down_proj -> + r``, with the same module names, so one port program serves all of them. The
|
|
185
|
+
columns are what differs.
|
|
186
|
+
|
|
187
|
+
``qk_norm``: per-head RMSNorm on q and k before RoPE (ports ``qn``/``kn``). ``qkv_bias``:
|
|
188
|
+
the q/k/v projections always carry a bias (``"always"``), or carry one only under
|
|
189
|
+
``config.attention_bias`` (``"config"``); the analysis reads ``Linear.bias`` of the loaded
|
|
190
|
+
module either way, so an absent bias is an absent (exactly zero) term, never a guess.
|
|
191
|
+
``premises``: ``(config attribute, allowed values, why)``; a loaded config outside them is
|
|
192
|
+
refused at attach (``config_refusal``) instead of being stepped under a wrong operator text.
|
|
193
|
+
"""
|
|
194
|
+
|
|
195
|
+
name: str
|
|
196
|
+
qk_norm: bool = False
|
|
197
|
+
qkv_bias: str = "config"
|
|
198
|
+
premises: tuple[tuple[str, tuple[Any, ...], str], ...] = ()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
_SILU = ("hidden_act", ("silu",), "the MLP port program is sg = silu(g)")
|
|
202
|
+
_NO_MLP_BIAS = ("mlp_bias", (False, None),
|
|
203
|
+
"the MLP port program (g = W_gate n, u = W_up n, m = W_down f) is bias-free")
|
|
204
|
+
|
|
205
|
+
FAMILIES: dict[str, Family] = {
|
|
206
|
+
row.name: row
|
|
207
|
+
for row in (
|
|
208
|
+
Family("qwen2", qkv_bias="always", premises=(_SILU,)),
|
|
209
|
+
Family("qwen3", qk_norm=True, premises=(_SILU,)),
|
|
210
|
+
Family("llama", premises=(_SILU, _NO_MLP_BIAS)),
|
|
211
|
+
Family("mistral", premises=(_SILU,)),
|
|
212
|
+
)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def config_refusal(family: str, config: Any) -> str | None:
|
|
217
|
+
"""Why a loaded ``config`` falls outside its family row's premises (None when it does not)."""
|
|
218
|
+
row = FAMILIES.get(family)
|
|
219
|
+
if row is None:
|
|
220
|
+
return f"no port program for model_type {family!r}; supported: {', '.join(FAMILIES)}"
|
|
221
|
+
for name, allowed, why in row.premises:
|
|
222
|
+
value = getattr(config, name, allowed[0])
|
|
223
|
+
if value not in allowed:
|
|
224
|
+
return (f"{family} config.{name} = {value!r} is outside the port table "
|
|
225
|
+
f"({name} must be one of {list(allowed)}: {why})")
|
|
226
|
+
return None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _decoder_program(row: Family) -> PortProgram:
|
|
230
|
+
family, qk_norm = row.name, row.qk_norm
|
|
231
|
+
bias = {"always": " + b_{}", "config": " (+ b_{} when attention_bias)"}[row.qkv_bias]
|
|
232
|
+
head = ("batch", "row", "head", "head_dim")
|
|
233
|
+
kv_head = ("batch", "row", "kv_head", "head_dim")
|
|
234
|
+
q_src, k_src = ("qn", "kn") if qk_norm else ("q", "k")
|
|
235
|
+
attention: list[PortSpec] = [
|
|
236
|
+
PortSpec(
|
|
237
|
+
"h",
|
|
238
|
+
ATTN,
|
|
239
|
+
"",
|
|
240
|
+
"pre",
|
|
241
|
+
"native",
|
|
242
|
+
_D,
|
|
243
|
+
"h = layer input (residual stream)",
|
|
244
|
+
("P01",),
|
|
245
|
+
_H_EDIT,
|
|
246
|
+
inputs=(PREV_LAYER,),
|
|
247
|
+
),
|
|
248
|
+
PortSpec(
|
|
249
|
+
"a",
|
|
250
|
+
ATTN,
|
|
251
|
+
"input_layernorm",
|
|
252
|
+
"out",
|
|
253
|
+
"native",
|
|
254
|
+
_D,
|
|
255
|
+
"a = RMSNorm(h) * w_in",
|
|
256
|
+
("P02", "P03"),
|
|
257
|
+
"input_layernorm output replaced; reaches q/k/v only, the skip path keeps h",
|
|
258
|
+
inputs=("h",),
|
|
259
|
+
),
|
|
260
|
+
_proj(
|
|
261
|
+
"q", "self_attn.q_proj", _QF, f"q = W_q a{bias.format('q')} (pre-RoPE, flat)", ("a",)
|
|
262
|
+
),
|
|
263
|
+
]
|
|
264
|
+
if qk_norm:
|
|
265
|
+
attention.append(
|
|
266
|
+
PortSpec(
|
|
267
|
+
"qn",
|
|
268
|
+
ATTN,
|
|
269
|
+
"self_attn.q_norm",
|
|
270
|
+
"out",
|
|
271
|
+
"native",
|
|
272
|
+
head,
|
|
273
|
+
"qn = RMSNorm_head(q) * w_q (per head, pre-RoPE)",
|
|
274
|
+
("P02", "P04"),
|
|
275
|
+
"q_norm output replaced natively",
|
|
276
|
+
inputs=("q",),
|
|
277
|
+
)
|
|
278
|
+
)
|
|
279
|
+
attention.append(
|
|
280
|
+
_proj(
|
|
281
|
+
"k",
|
|
282
|
+
"self_attn.k_proj",
|
|
283
|
+
_KF,
|
|
284
|
+
f"k = W_k a{bias.format('k')} (pre-RoPE, flat)",
|
|
285
|
+
("a",),
|
|
286
|
+
"; flows through RoPE into the cache row this transition writes",
|
|
287
|
+
)
|
|
288
|
+
)
|
|
289
|
+
if qk_norm:
|
|
290
|
+
attention.append(
|
|
291
|
+
PortSpec(
|
|
292
|
+
"kn",
|
|
293
|
+
ATTN,
|
|
294
|
+
"self_attn.k_norm",
|
|
295
|
+
"out",
|
|
296
|
+
"native",
|
|
297
|
+
kv_head,
|
|
298
|
+
"kn = RMSNorm_head(k) * w_k (per kv head, pre-RoPE)",
|
|
299
|
+
("P02", "P04"),
|
|
300
|
+
"k_norm output replaced natively; enters the cache via RoPE",
|
|
301
|
+
inputs=("k",),
|
|
302
|
+
)
|
|
303
|
+
)
|
|
304
|
+
attention += [
|
|
305
|
+
_proj(
|
|
306
|
+
"v",
|
|
307
|
+
"self_attn.v_proj",
|
|
308
|
+
_KF,
|
|
309
|
+
f"v = W_v a{bias.format('v')} (flat)",
|
|
310
|
+
("a",),
|
|
311
|
+
"; enters the cache row this transition writes",
|
|
312
|
+
),
|
|
313
|
+
PortSpec(
|
|
314
|
+
"qr",
|
|
315
|
+
ATTN,
|
|
316
|
+
"eager",
|
|
317
|
+
"eager-arg",
|
|
318
|
+
"native",
|
|
319
|
+
("batch", "head", "row", "head_dim"),
|
|
320
|
+
f"qr = RoPE({q_src}) (query argument of eager attention)",
|
|
321
|
+
("P04",),
|
|
322
|
+
"query argument of the eager call replaced; native eager attention recomputes "
|
|
323
|
+
"s, p and the value mix",
|
|
324
|
+
inputs=(q_src,),
|
|
325
|
+
),
|
|
326
|
+
PortSpec(
|
|
327
|
+
"kr",
|
|
328
|
+
ATTN,
|
|
329
|
+
"eager",
|
|
330
|
+
"eager-arg",
|
|
331
|
+
"native",
|
|
332
|
+
("batch", "kv_head", "src", "head_dim"),
|
|
333
|
+
f"kr = [{CACHE}; RoPE({k_src})] (key argument of eager attention, cached rows "
|
|
334
|
+
"included)",
|
|
335
|
+
("P04",),
|
|
336
|
+
_KR_REFUSAL,
|
|
337
|
+
editable=False,
|
|
338
|
+
inputs=(k_src, CACHE),
|
|
339
|
+
),
|
|
340
|
+
PortSpec(
|
|
341
|
+
"s",
|
|
342
|
+
ATTN,
|
|
343
|
+
"eager",
|
|
344
|
+
"eager-replica",
|
|
345
|
+
"replica",
|
|
346
|
+
_SCORE,
|
|
347
|
+
"s = scaling * qr repeat_kv(kr)^T + mask (replica of the native expression)",
|
|
348
|
+
("P05", "P07", "P08", "P09"),
|
|
349
|
+
"replica: p' = softmax(s', float32).to(dtype) and the value mix "
|
|
350
|
+
"matmul(p', repeat_kv(v)) are recomputed by replica",
|
|
351
|
+
inputs=("qr", "kr"),
|
|
352
|
+
),
|
|
353
|
+
PortSpec(
|
|
354
|
+
"p",
|
|
355
|
+
ATTN,
|
|
356
|
+
"eager",
|
|
357
|
+
"eager-out",
|
|
358
|
+
"native",
|
|
359
|
+
_SCORE,
|
|
360
|
+
"p = softmax(s, float32).to(dtype) (native attention weights)",
|
|
361
|
+
("P05", "P06", "P07", "P08", "P09"),
|
|
362
|
+
"native weights replaced after the eager call; the value mix "
|
|
363
|
+
"matmul(p', repeat_kv(v)) is recomputed by replica",
|
|
364
|
+
inputs=("s",),
|
|
365
|
+
),
|
|
366
|
+
PortSpec(
|
|
367
|
+
"A",
|
|
368
|
+
ATTN,
|
|
369
|
+
"self_attn.o_proj",
|
|
370
|
+
"pre",
|
|
371
|
+
"native",
|
|
372
|
+
_QF,
|
|
373
|
+
f"A = concat_heads(p repeat_kv([{CACHE}; v])) (o_proj input)",
|
|
374
|
+
("P06", "P07"),
|
|
375
|
+
"o_proj input replaced natively",
|
|
376
|
+
inputs=("p", "v", CACHE),
|
|
377
|
+
),
|
|
378
|
+
PortSpec(
|
|
379
|
+
"o",
|
|
380
|
+
ATTN,
|
|
381
|
+
"self_attn.o_proj",
|
|
382
|
+
"out",
|
|
383
|
+
"native",
|
|
384
|
+
_D,
|
|
385
|
+
"o = W_o A",
|
|
386
|
+
("P06", "P07"),
|
|
387
|
+
"o_proj output replaced natively; reaches r, hence both the skip path and the MLP",
|
|
388
|
+
inputs=("A",),
|
|
389
|
+
),
|
|
390
|
+
PortSpec(
|
|
391
|
+
"r",
|
|
392
|
+
ATTN,
|
|
393
|
+
"post_attention_layernorm",
|
|
394
|
+
"pre",
|
|
395
|
+
"native",
|
|
396
|
+
_D,
|
|
397
|
+
"r = h + o",
|
|
398
|
+
("P06", "P07", "P14"),
|
|
399
|
+
"realised as an o edit: o' = op(h + o) - h, so the native sum h + o' feeds both "
|
|
400
|
+
"the skip path and the MLP; the realised r is compared with the request and the "
|
|
401
|
+
"max abs error is recorded (floating-point sums need not hit it exactly)",
|
|
402
|
+
inputs=("h", "o"),
|
|
403
|
+
),
|
|
404
|
+
]
|
|
405
|
+
mlp = [
|
|
406
|
+
PortSpec(
|
|
407
|
+
"n",
|
|
408
|
+
MLP,
|
|
409
|
+
"mlp",
|
|
410
|
+
"pre",
|
|
411
|
+
"native",
|
|
412
|
+
_D,
|
|
413
|
+
"n = RMSNorm(r) * w_post (mlp input)",
|
|
414
|
+
("P02", "P03"),
|
|
415
|
+
"mlp input replaced; reaches the MLP only, the skip path keeps r",
|
|
416
|
+
inputs=("r",),
|
|
417
|
+
),
|
|
418
|
+
PortSpec(
|
|
419
|
+
"g",
|
|
420
|
+
MLP,
|
|
421
|
+
"mlp.gate_proj",
|
|
422
|
+
"out",
|
|
423
|
+
"native",
|
|
424
|
+
_FF,
|
|
425
|
+
"g = W_gate n",
|
|
426
|
+
("P10", "P15"),
|
|
427
|
+
"gate_proj output replaced natively",
|
|
428
|
+
inputs=("n",),
|
|
429
|
+
),
|
|
430
|
+
PortSpec(
|
|
431
|
+
"sg",
|
|
432
|
+
MLP,
|
|
433
|
+
"mlp.act_fn",
|
|
434
|
+
"out",
|
|
435
|
+
"native",
|
|
436
|
+
_FF,
|
|
437
|
+
"sg = silu(g)",
|
|
438
|
+
("P10", "P15"),
|
|
439
|
+
"act_fn output replaced natively",
|
|
440
|
+
inputs=("g",),
|
|
441
|
+
),
|
|
442
|
+
PortSpec(
|
|
443
|
+
"u",
|
|
444
|
+
MLP,
|
|
445
|
+
"mlp.up_proj",
|
|
446
|
+
"out",
|
|
447
|
+
"native",
|
|
448
|
+
_FF,
|
|
449
|
+
"u = W_up n",
|
|
450
|
+
("P10", "P15"),
|
|
451
|
+
"up_proj output replaced natively",
|
|
452
|
+
inputs=("n",),
|
|
453
|
+
),
|
|
454
|
+
PortSpec(
|
|
455
|
+
"f",
|
|
456
|
+
MLP,
|
|
457
|
+
"mlp.down_proj",
|
|
458
|
+
"pre",
|
|
459
|
+
"native",
|
|
460
|
+
_FF,
|
|
461
|
+
"f = sg * u (down_proj input)",
|
|
462
|
+
("P10", "P15"),
|
|
463
|
+
"down_proj input replaced natively",
|
|
464
|
+
inputs=("sg", "u"),
|
|
465
|
+
),
|
|
466
|
+
PortSpec(
|
|
467
|
+
"m",
|
|
468
|
+
MLP,
|
|
469
|
+
"mlp.down_proj",
|
|
470
|
+
"out",
|
|
471
|
+
"native",
|
|
472
|
+
_D,
|
|
473
|
+
"m = W_down f",
|
|
474
|
+
("P14",),
|
|
475
|
+
"down_proj output replaced natively; the skip path keeps r",
|
|
476
|
+
inputs=("f",),
|
|
477
|
+
),
|
|
478
|
+
PortSpec(
|
|
479
|
+
"h_out",
|
|
480
|
+
MLP,
|
|
481
|
+
"",
|
|
482
|
+
"out",
|
|
483
|
+
"native",
|
|
484
|
+
_D,
|
|
485
|
+
"h_out = r + m (layer output)",
|
|
486
|
+
("P14",),
|
|
487
|
+
"layer output replaced; it becomes the committed hidden",
|
|
488
|
+
inputs=("r", "m"),
|
|
489
|
+
),
|
|
490
|
+
]
|
|
491
|
+
return PortProgram(
|
|
492
|
+
family, f"transformers.models.{family}.modeling_{family}", tuple(attention + mlp)
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
PROGRAMS: dict[str, PortProgram] = {name: _decoder_program(row) for name, row in FAMILIES.items()}
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def program_for(adapter_or_family: Any) -> PortProgram:
|
|
500
|
+
"""The port program of a family name, or of an adapter (whose loaded config must then lie
|
|
501
|
+
inside the family row's premises)."""
|
|
502
|
+
family = adapter_or_family
|
|
503
|
+
if not isinstance(family, str):
|
|
504
|
+
family = adapter_or_family.spec.model_type
|
|
505
|
+
try:
|
|
506
|
+
program = PROGRAMS[family]
|
|
507
|
+
except KeyError:
|
|
508
|
+
raise ValueError(
|
|
509
|
+
f"no port program for {family!r}; registered: {', '.join(sorted(PROGRAMS))}"
|
|
510
|
+
) from None
|
|
511
|
+
config = getattr(getattr(adapter_or_family, "model", None), "config", None)
|
|
512
|
+
refusal = None if config is None else config_refusal(family, config)
|
|
513
|
+
if refusal is not None:
|
|
514
|
+
raise ValueError(refusal)
|
|
515
|
+
return program
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def check_deterministic(module: Any) -> None:
|
|
519
|
+
"""Refuse a model or layer that would run in training mode (dropout applies there).
|
|
520
|
+
|
|
521
|
+
The one implementation of the eval-mode rule: ``PortController`` installs call it on the
|
|
522
|
+
pending layer, ``Run`` on the whole model before construction, every commit and every probe.
|
|
523
|
+
"""
|
|
524
|
+
training = [name or type(module).__name__ for name, m in module.named_modules() if m.training]
|
|
525
|
+
if not training:
|
|
526
|
+
return
|
|
527
|
+
dropout = sorted(
|
|
528
|
+
{
|
|
529
|
+
float(p)
|
|
530
|
+
for m in module.modules()
|
|
531
|
+
if m.training
|
|
532
|
+
for p in (getattr(m, "attention_dropout", 0.0), getattr(m, "p", 0.0))
|
|
533
|
+
if type(p) in (int, float) and p
|
|
534
|
+
}
|
|
535
|
+
)
|
|
536
|
+
raise ValueError(
|
|
537
|
+
f"port stepping requires an eval-mode model (no dropout): {len(training)} module(s) are "
|
|
538
|
+
f"in training mode (e.g. {training[0]!r}); non-zero dropout probabilities seen: "
|
|
539
|
+
f"{dropout or 'none'}; call model.eval()"
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def tensor_digest(value: torch.Tensor) -> str:
|
|
544
|
+
raw = value.detach().cpu().contiguous().reshape(-1).view(torch.uint8)
|
|
545
|
+
return hashlib.sha256(raw.numpy()).hexdigest() # hashes the buffer, not a bytes copy
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def changed_fraction(before: torch.Tensor, after: torch.Tensor) -> float:
|
|
549
|
+
"""Fraction of elements whose bit pattern differs (same shape and dtype)."""
|
|
550
|
+
if before.numel() == 0:
|
|
551
|
+
return 0.0
|
|
552
|
+
width = before.element_size()
|
|
553
|
+
left = before.detach().cpu().contiguous().reshape(-1).view(torch.uint8).reshape(-1, width)
|
|
554
|
+
right = after.detach().cpu().contiguous().reshape(-1).view(torch.uint8).reshape(-1, width)
|
|
555
|
+
return float((left != right).any(dim=1).double().mean())
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
MEASURED_FIELDS = (
|
|
559
|
+
"cast_max_abs_error",
|
|
560
|
+
"realised_max_abs_error",
|
|
561
|
+
"realisation_max_abs_error",
|
|
562
|
+
"changed_fraction",
|
|
563
|
+
"row_sum_min",
|
|
564
|
+
"row_sum_max",
|
|
565
|
+
"min",
|
|
566
|
+
)
|
|
567
|
+
SUPPLIED_FIELDS = ("row_sum_tolerance",)
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def with_labels(entry: dict[str, Any]) -> dict[str, Any]:
|
|
571
|
+
"""Attach ``labels`` ``{field: authority}`` for the numeric quantities of a manifest entry
|
|
572
|
+
(measurements are ``measured``, the row-sum tolerance is ``supplied``). Counts and shapes
|
|
573
|
+
(``mask_count``, ``mask_shape``) are structure and stay unlabelled."""
|
|
574
|
+
labels = {key: "measured" for key in MEASURED_FIELDS if key in entry}
|
|
575
|
+
labels.update({key: "supplied" for key in SUPPLIED_FIELDS if key in entry})
|
|
576
|
+
entry["labels"] = labels
|
|
577
|
+
return entry
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def max_abs(value: torch.Tensor) -> float:
|
|
581
|
+
return float(value.max()) if value.numel() else 0.0
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def wide(value: torch.Tensor) -> torch.Tensor:
|
|
585
|
+
"""``value`` in float64 on its own device (on the host for a device without float64)."""
|
|
586
|
+
if value.device.type == "mps":
|
|
587
|
+
return value.detach().to("cpu", torch.float64)
|
|
588
|
+
return value.detach().to(torch.float64)
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
@dataclass(frozen=True)
|
|
592
|
+
class PortEdit:
|
|
593
|
+
"""A staged edit: ``replace``, ``add`` or ``scale`` the value at one port.
|
|
594
|
+
|
|
595
|
+
``mask`` (bool, broadcastable to the port) limits the op to the elements where it is true;
|
|
596
|
+
the other elements stay bit-identical. ``selection`` is an opaque description of what the
|
|
597
|
+
mask selects, recorded verbatim. ``origin`` is the pointer of a value taken from another run
|
|
598
|
+
(``{origin, via, address, sha256, ...}``, names and digests), recorded verbatim.
|
|
599
|
+
"""
|
|
600
|
+
|
|
601
|
+
port: str
|
|
602
|
+
value: Any
|
|
603
|
+
op: str = "replace"
|
|
604
|
+
mask: Any = None
|
|
605
|
+
selection: str | None = None
|
|
606
|
+
origin: dict[str, Any] | None = None
|
|
607
|
+
|
|
608
|
+
def __post_init__(self) -> None:
|
|
609
|
+
if self.op not in EDIT_OPS:
|
|
610
|
+
raise ValueError(f"edit op must be one of {', '.join(EDIT_OPS)}")
|
|
611
|
+
value = self.value
|
|
612
|
+
if isinstance(value, torch.Tensor):
|
|
613
|
+
if not value.is_floating_point():
|
|
614
|
+
raise ValueError("edit tensors must be floating point")
|
|
615
|
+
object.__setattr__(self, "value", value.detach().clone())
|
|
616
|
+
elif type(value) in (int, float):
|
|
617
|
+
if value != value or value in (float("inf"), float("-inf")):
|
|
618
|
+
raise ValueError("edit scalars must be finite")
|
|
619
|
+
object.__setattr__(self, "value", float(value))
|
|
620
|
+
else:
|
|
621
|
+
raise ValueError("edit value must be a tensor or a finite number")
|
|
622
|
+
if self.mask is not None:
|
|
623
|
+
if not isinstance(self.mask, torch.Tensor) or self.mask.dtype != torch.bool:
|
|
624
|
+
raise ValueError("edit mask must be a bool tensor")
|
|
625
|
+
object.__setattr__(self, "mask", self.mask.detach().to("cpu", copy=True))
|
|
626
|
+
if self.selection is not None and not isinstance(self.selection, str):
|
|
627
|
+
raise ValueError("edit selection must be a string")
|
|
628
|
+
|
|
629
|
+
def validate(self, shape: Sequence[int]) -> None:
|
|
630
|
+
"""Shape-only validation against a port shape; executes nothing."""
|
|
631
|
+
shape = tuple(shape)
|
|
632
|
+
value = self.value
|
|
633
|
+
if isinstance(value, torch.Tensor):
|
|
634
|
+
if self.op == "replace":
|
|
635
|
+
if tuple(value.shape) != shape:
|
|
636
|
+
raise ValueError(
|
|
637
|
+
f"replace at port {self.port} needs shape {shape}, "
|
|
638
|
+
f"got {tuple(value.shape)}"
|
|
639
|
+
)
|
|
640
|
+
else:
|
|
641
|
+
try:
|
|
642
|
+
joint = tuple(torch.broadcast_shapes(tuple(value.shape), shape))
|
|
643
|
+
except RuntimeError:
|
|
644
|
+
joint = None
|
|
645
|
+
if joint != shape:
|
|
646
|
+
raise ValueError(
|
|
647
|
+
f"{self.op} value at port {self.port} does not broadcast to the port: "
|
|
648
|
+
f"port shape {shape}, value shape {tuple(value.shape)}"
|
|
649
|
+
)
|
|
650
|
+
if self.mask is not None:
|
|
651
|
+
try:
|
|
652
|
+
joint = tuple(torch.broadcast_shapes(tuple(self.mask.shape), shape))
|
|
653
|
+
except RuntimeError:
|
|
654
|
+
joint = None
|
|
655
|
+
if joint != shape:
|
|
656
|
+
raise ValueError(
|
|
657
|
+
f"mask at port {self.port} does not broadcast to the port: "
|
|
658
|
+
f"port shape {shape}, mask shape {tuple(self.mask.shape)}"
|
|
659
|
+
)
|
|
660
|
+
|
|
661
|
+
def selected(self, shape: Sequence[int], device: Any = "cpu") -> torch.Tensor | None:
|
|
662
|
+
"""The mask broadcast to the port shape (None for a whole-port edit)."""
|
|
663
|
+
if self.mask is None:
|
|
664
|
+
return None
|
|
665
|
+
return self.mask.to(device).broadcast_to(tuple(shape))
|
|
666
|
+
|
|
667
|
+
def apply(self, x: torch.Tensor) -> torch.Tensor:
|
|
668
|
+
"""The edited value alone (``realise`` without the record)."""
|
|
669
|
+
self.validate(x.shape)
|
|
670
|
+
return self._result(x, self._operands(x.dtype)[0])
|
|
671
|
+
|
|
672
|
+
def _operands(self, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]:
|
|
673
|
+
"""``(written, requested)`` on the host: the request cast once to the port dtype (the
|
|
674
|
+
operand the arithmetic uses) and the request in float64. The value crosses to the host
|
|
675
|
+
at most once (a scalar or a host tensor not at all)."""
|
|
676
|
+
value = self.value
|
|
677
|
+
if isinstance(value, torch.Tensor):
|
|
678
|
+
host = value.detach().to("cpu")
|
|
679
|
+
return host.to(dtype), host.to(torch.float64)
|
|
680
|
+
return torch.tensor(value, dtype=dtype), torch.tensor(value, dtype=torch.float64)
|
|
681
|
+
|
|
682
|
+
def _result(self, x: torch.Tensor, written: torch.Tensor) -> torch.Tensor:
|
|
683
|
+
"""``x op written`` on the selected elements, on ``x``'s device (``written`` moved there
|
|
684
|
+
once)."""
|
|
685
|
+
written = written.to(x.device)
|
|
686
|
+
if self.op == "replace":
|
|
687
|
+
full = torch.empty_like(x)
|
|
688
|
+
full.copy_(written)
|
|
689
|
+
elif self.op == "add":
|
|
690
|
+
full = x + written
|
|
691
|
+
else:
|
|
692
|
+
full = x * written
|
|
693
|
+
sel = self.selected(x.shape, x.device)
|
|
694
|
+
return full if sel is None else torch.where(sel, full, x)
|
|
695
|
+
|
|
696
|
+
def realise(self, x: torch.Tensor) -> tuple[torch.Tensor, dict[str, Any]]:
|
|
697
|
+
"""The edited value and the record of what entered the model.
|
|
698
|
+
|
|
699
|
+
The arithmetic uses the recorded cast operand (``written``, the request cast to the
|
|
700
|
+
port dtype): ``x op written``. ``cast_*`` compare the requested operand with ``written``
|
|
701
|
+
(float64, over the selected elements); ``realised_*`` compare the result with the ideal
|
|
702
|
+
``x_f64 op requested_f64`` (the effect error; for ``replace`` it equals the cast error);
|
|
703
|
+
``changed_fraction`` is the fraction of elements whose bits changed.
|
|
704
|
+
"""
|
|
705
|
+
self.validate(x.shape)
|
|
706
|
+
written, requested = self._operands(x.dtype)
|
|
707
|
+
result = self._result(x, written)
|
|
708
|
+
return result, self._record(x, result, written, requested)
|
|
709
|
+
|
|
710
|
+
def measure(self, x: torch.Tensor, actual: torch.Tensor) -> dict[str, Any]:
|
|
711
|
+
"""The record of this edit applied to ``x`` when the value that actually entered the
|
|
712
|
+
model is ``actual``: ``realised_*`` is ``actual`` against the exact float64 result of
|
|
713
|
+
``x op requested`` (selected elements; the others must equal ``x``)."""
|
|
714
|
+
return self._record(x, actual, *self._operands(x.dtype))
|
|
715
|
+
|
|
716
|
+
def _record(
|
|
717
|
+
self, x: torch.Tensor, actual: torch.Tensor, written: torch.Tensor, requested: torch.Tensor
|
|
718
|
+
) -> dict[str, Any]:
|
|
719
|
+
"""``measure`` given the host operands; ``x`` and ``actual`` cross to the host once each,
|
|
720
|
+
and the mask is the stored host mask."""
|
|
721
|
+
shape = tuple(x.shape)
|
|
722
|
+
before, after = x.detach().to("cpu"), actual.detach().to("cpu")
|
|
723
|
+
base = before.to(torch.float64)
|
|
724
|
+
wanted = requested.expand(shape)
|
|
725
|
+
ideal = (
|
|
726
|
+
wanted
|
|
727
|
+
if self.op == "replace"
|
|
728
|
+
else (base + wanted if self.op == "add" else base * wanted)
|
|
729
|
+
)
|
|
730
|
+
sel = self.selected(shape)
|
|
731
|
+
if sel is not None:
|
|
732
|
+
ideal = torch.where(sel, ideal, base)
|
|
733
|
+
effect = max_abs((after.to(torch.float64) - ideal).abs())
|
|
734
|
+
gap = (written.to(torch.float64).expand(shape) - wanted).abs()
|
|
735
|
+
if sel is not None:
|
|
736
|
+
gap = gap[sel]
|
|
737
|
+
cast_error = max_abs(gap)
|
|
738
|
+
record: dict[str, Any] = {
|
|
739
|
+
"realised_dtype": str(written.dtype),
|
|
740
|
+
"realised_sha256": tensor_digest(written),
|
|
741
|
+
"cast_exact": cast_error == 0.0,
|
|
742
|
+
"cast_max_abs_error": cast_error,
|
|
743
|
+
"realised_exact": effect == 0.0,
|
|
744
|
+
"realised_max_abs_error": effect,
|
|
745
|
+
"changed_fraction": changed_fraction(before, after),
|
|
746
|
+
}
|
|
747
|
+
if sel is not None:
|
|
748
|
+
record["mask_count"] = int(sel.sum())
|
|
749
|
+
return record
|
|
750
|
+
|
|
751
|
+
def manifest(self) -> dict[str, Any]:
|
|
752
|
+
value = self.value
|
|
753
|
+
if isinstance(value, torch.Tensor):
|
|
754
|
+
described = {
|
|
755
|
+
"kind": "tensor",
|
|
756
|
+
"sha256": tensor_digest(value),
|
|
757
|
+
"shape": list(value.shape),
|
|
758
|
+
"dtype": str(value.dtype),
|
|
759
|
+
}
|
|
760
|
+
else:
|
|
761
|
+
described = {"kind": "scalar", "value": value}
|
|
762
|
+
entry: dict[str, Any] = {"port": self.port, "op": self.op, "value": described}
|
|
763
|
+
if self.selection is not None:
|
|
764
|
+
entry["selection"] = self.selection
|
|
765
|
+
if self.mask is not None:
|
|
766
|
+
entry["mask_sha256"] = tensor_digest(self.mask)
|
|
767
|
+
entry["mask_count"] = int(self.mask.sum())
|
|
768
|
+
entry["mask_shape"] = list(self.mask.shape)
|
|
769
|
+
if self.origin is not None:
|
|
770
|
+
entry["origin"] = dict(self.origin)
|
|
771
|
+
return entry
|
|
772
|
+
|
|
773
|
+
@property
|
|
774
|
+
def key(self) -> str:
|
|
775
|
+
"""Content key under which a process-local registry can hold the value."""
|
|
776
|
+
manifest = self.manifest()["value"]
|
|
777
|
+
return manifest["sha256"] if manifest["kind"] == "tensor" else f"scalar:{manifest['value']}"
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
def _module(layer: Any, path: str) -> Any:
|
|
781
|
+
module = layer
|
|
782
|
+
for part in path.split(".") if path else ():
|
|
783
|
+
module = getattr(module, part, None)
|
|
784
|
+
if module is None:
|
|
785
|
+
raise ValueError(f"native layer has no module {path!r}")
|
|
786
|
+
if not isinstance(module, torch.nn.Module):
|
|
787
|
+
raise ValueError(f"native layer attribute {path!r} is not a module")
|
|
788
|
+
return module
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def rewritten_forward(module: Any) -> bool:
|
|
792
|
+
"""An instance-level forward whose body is not the class's forward (duck-typed on
|
|
793
|
+
nnsight's ``Controller``: ``forward.state.body``; plain pass-through wrappers are fine)."""
|
|
794
|
+
forward = vars(module).get("forward")
|
|
795
|
+
body = getattr(getattr(forward, "state", None), "body", None)
|
|
796
|
+
if body is None:
|
|
797
|
+
return False
|
|
798
|
+
return getattr(body, "__func__", body) is not type(module).forward
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
# --- the one process-wide eager-attention interceptor ------------------------------------
|
|
802
|
+
#
|
|
803
|
+
# The family's modeling module has one module-level ``eager_attention_forward``. It is patched
|
|
804
|
+
# once, by the first controller to install, with a single interceptor that dispatches through a
|
|
805
|
+
# lock-protected registry keyed by attention-module identity, and restored when the registry
|
|
806
|
+
# empties. The interceptor is a pass-through unless the calling thread is inside the
|
|
807
|
+
# controller-driven transition (``installed()``) of the controller registered for that module,
|
|
808
|
+
# so a plain forward of the same model from user code or another thread is never staged or
|
|
809
|
+
# captured. Hooks on the shared native modules carry the same guard.
|
|
810
|
+
|
|
811
|
+
_LOCK = threading.RLock()
|
|
812
|
+
_LOCAL = threading.local()
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
class _Patch:
|
|
816
|
+
def __init__(self, modeling: Any):
|
|
817
|
+
self.modeling = modeling
|
|
818
|
+
self.original = modeling.eager_attention_forward
|
|
819
|
+
self.repeat_kv = modeling.repeat_kv
|
|
820
|
+
self.owners: dict[int, PortController] = {}
|
|
821
|
+
patch = self
|
|
822
|
+
|
|
823
|
+
def eager(module, query, key, value, attention_mask, *args, **kwargs):
|
|
824
|
+
owner = patch.owners.get(id(module))
|
|
825
|
+
if owner is None or not owner._engaged():
|
|
826
|
+
return patch.original(module, query, key, value, attention_mask, *args, **kwargs)
|
|
827
|
+
return owner._eager(
|
|
828
|
+
patch, module, query, key, value, attention_mask, *args, **kwargs
|
|
829
|
+
)
|
|
830
|
+
|
|
831
|
+
eager._mdb_attention_observer = True
|
|
832
|
+
self.interceptor = eager
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
_PATCHES: dict[str, _Patch] = {}
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def _acquire(controller: PortController, modeling: Any, attention: Any) -> _Patch:
|
|
839
|
+
with _LOCK:
|
|
840
|
+
patch = _PATCHES.get(modeling.__name__)
|
|
841
|
+
created = patch is None
|
|
842
|
+
if patch is None:
|
|
843
|
+
patch = _Patch(modeling)
|
|
844
|
+
if id(attention) in patch.owners:
|
|
845
|
+
raise ValueError(
|
|
846
|
+
"an eager-attention interceptor is already installed on this attention module "
|
|
847
|
+
"(nested installs on one layer are unsupported)"
|
|
848
|
+
)
|
|
849
|
+
patch.owners[id(attention)] = controller
|
|
850
|
+
if created:
|
|
851
|
+
_PATCHES[modeling.__name__] = patch
|
|
852
|
+
modeling.eager_attention_forward = patch.interceptor
|
|
853
|
+
return patch
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _release(patch: _Patch, attention: Any) -> None:
|
|
857
|
+
with _LOCK:
|
|
858
|
+
patch.owners.pop(id(attention), None)
|
|
859
|
+
if patch.owners:
|
|
860
|
+
return
|
|
861
|
+
if patch.modeling.eager_attention_forward is patch.interceptor:
|
|
862
|
+
patch.modeling.eager_attention_forward = patch.original
|
|
863
|
+
_PATCHES.pop(patch.modeling.__name__, None)
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
class _Stop(PortStop):
|
|
867
|
+
def __init__(self, port: str):
|
|
868
|
+
super().__init__(f"stopped at port {port}")
|
|
869
|
+
self.port = port
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
class PortController:
|
|
873
|
+
"""Hooks for one native decoder-layer call.
|
|
874
|
+
|
|
875
|
+
``layer=None`` observes every layer (captures are replaced per layer) and may not carry
|
|
876
|
+
edits. ``capture`` selects which ports are cloned (``True`` = all, ``False`` = none, or an
|
|
877
|
+
iterable of names); the stop port is always captured. ``layers`` (optional) is the model's
|
|
878
|
+
layer count: a layer at or beyond it is refused at construction (and always at install).
|
|
879
|
+
|
|
880
|
+
Per-transition lifecycle used by ``saturn.Session``: ``begin()`` clears what the previous
|
|
881
|
+
transition recorded, ``manifest()`` then lists exactly the edits whose hooks fired during the
|
|
882
|
+
transition's native call (a probe or a transition that did not install the controller
|
|
883
|
+
contributes nothing), and raises if an edit staged for the layer that ran did not fire.
|
|
884
|
+
|
|
885
|
+
Stopping at ``p`` with the native eager attention function: the function cannot be split,
|
|
886
|
+
so the value mix ``A`` is computed natively as a by-product of producing ``p``; it is not
|
|
887
|
+
held, checked or captured (``computed_past_cursor`` on ``Run.status`` discloses it).
|
|
888
|
+
|
|
889
|
+
Thread safety: the interceptor and hooks only act inside this controller's own
|
|
890
|
+
``installed()`` window in the calling thread; a forward of the same model from another
|
|
891
|
+
thread, or outside a transition, passes through untouched. Two controllers on different
|
|
892
|
+
attention modules (different models, or different layers) coexist; two on one module are
|
|
893
|
+
refused.
|
|
894
|
+
"""
|
|
895
|
+
|
|
896
|
+
def __init__(
|
|
897
|
+
self,
|
|
898
|
+
program: PortProgram,
|
|
899
|
+
layer: int | None,
|
|
900
|
+
*,
|
|
901
|
+
stop: str | None = None,
|
|
902
|
+
edits: Sequence[PortEdit] = (),
|
|
903
|
+
capture: bool | Iterable[str] = True,
|
|
904
|
+
layers: int | None = None,
|
|
905
|
+
cells: Sequence[Any] = (),
|
|
906
|
+
):
|
|
907
|
+
self.program = program
|
|
908
|
+
self.layer = layer
|
|
909
|
+
if layer is not None and (type(layer) is not int or layer < 0):
|
|
910
|
+
raise ValueError("layer must be a nonnegative integer")
|
|
911
|
+
if layer is not None and layers is not None and layer >= layers:
|
|
912
|
+
raise ValueError(f"layer {layer} does not exist in a {layers}-layer model")
|
|
913
|
+
self.stop = None if stop is None else program.spec(stop).name
|
|
914
|
+
if stop == "h_out":
|
|
915
|
+
raise ValueError("h_out is the layer output; commit the layer instead of stopping")
|
|
916
|
+
self.edits = tuple(edits)
|
|
917
|
+
if self.edits and layer is None:
|
|
918
|
+
raise ValueError("edits need an explicit layer")
|
|
919
|
+
self.cells = tuple(cells) # engine.edits.CellEdit, realised in this layer's call
|
|
920
|
+
if self.cells and layer is None:
|
|
921
|
+
raise ValueError("cell edits need an explicit layer")
|
|
922
|
+
self.cell_records: dict[int, dict[str, Any]] = {}
|
|
923
|
+
self._adapter: Any = None
|
|
924
|
+
self._edits_at: dict[str, list[PortEdit]] = {}
|
|
925
|
+
for edit in self.edits:
|
|
926
|
+
spec = program.spec(edit.port)
|
|
927
|
+
if not spec.editable:
|
|
928
|
+
raise ValueError(f"port {spec.name} is not editable: {spec.edit}")
|
|
929
|
+
self._edits_at.setdefault(spec.name, []).append(edit)
|
|
930
|
+
names = program.names
|
|
931
|
+
if capture is True:
|
|
932
|
+
self._capture = set(names)
|
|
933
|
+
elif capture is False:
|
|
934
|
+
self._capture = set()
|
|
935
|
+
else:
|
|
936
|
+
self._capture = {program.spec(name).name for name in capture}
|
|
937
|
+
if self.stop is not None:
|
|
938
|
+
self._capture.add(self.stop)
|
|
939
|
+
self.captures: dict[str, torch.Tensor] = {}
|
|
940
|
+
self.originals: dict[str, torch.Tensor] = {}
|
|
941
|
+
self.order: list[str] = []
|
|
942
|
+
self.checks: dict[str, Any] = {}
|
|
943
|
+
self.installs = 0
|
|
944
|
+
self.edited_captures: dict[str, dict[str, str]] = {}
|
|
945
|
+
self.capture_notes: dict[str, dict[str, Any]] = {}
|
|
946
|
+
self.replica_verified: bool | None = None
|
|
947
|
+
self.replica_max_abs_diff: float | None = None
|
|
948
|
+
self.realisation: dict[str, Any] | None = None
|
|
949
|
+
self.fired: dict[int, dict[str, Any]] = {}
|
|
950
|
+
self._realised: list[dict[str, Any]] = []
|
|
951
|
+
self._live: dict[str, Any] = {}
|
|
952
|
+
self._active = False
|
|
953
|
+
self._seen_layer: int | None = None
|
|
954
|
+
self._installed_now = False
|
|
955
|
+
self._layer_index = layer
|
|
956
|
+
self._local = threading.local() # per-thread depth of entries into the pending layer
|
|
957
|
+
|
|
958
|
+
# --- protocol used by saturn ----------------------------------------------------
|
|
959
|
+
|
|
960
|
+
def begin(self) -> None:
|
|
961
|
+
"""Start of one transition (probe or commit): forget what an earlier one recorded."""
|
|
962
|
+
self._realised, self._seen_layer, self._installed_now = [], None, False
|
|
963
|
+
self.fired, self.cell_records = {}, {}
|
|
964
|
+
|
|
965
|
+
def _carries(self) -> bool:
|
|
966
|
+
return self.layer is not None and bool(self._edits_at or self.stop or self.cells)
|
|
967
|
+
|
|
968
|
+
def check_ahead(self, ahead: Sequence[Any]) -> None:
|
|
969
|
+
"""Before a multi-step ``continue_``: refuse when the controller carries edits (or a
|
|
970
|
+
stop) for a layer that none of the coming transitions runs (``ahead`` is the adapter's
|
|
971
|
+
``ports_ahead``), so nothing is silently dropped."""
|
|
972
|
+
if self._carries() and self.layer not in ahead:
|
|
973
|
+
what = "edits" if self._edits_at or self.cells else "a stop"
|
|
974
|
+
raise ValueError(
|
|
975
|
+
f"port controller carries {what} for layer {self.layer} but the coming "
|
|
976
|
+
f"transition(s) run {self._ahead_text(ahead)}; nothing was run"
|
|
977
|
+
)
|
|
978
|
+
|
|
979
|
+
@staticmethod
|
|
980
|
+
def _ahead_text(ahead: Sequence[Any]) -> str:
|
|
981
|
+
layers = sorted({a for a in ahead if a is not None})
|
|
982
|
+
return ("layer " + ", ".join(map(str, layers))) if layers else "no decoder layer"
|
|
983
|
+
|
|
984
|
+
def begin_call(self) -> None:
|
|
985
|
+
"""Start of one ``continue_`` call."""
|
|
986
|
+
self._call_installs = self.installs
|
|
987
|
+
|
|
988
|
+
def end_call(self) -> None:
|
|
989
|
+
"""End of one ``continue_`` call: a controller with edits must have been installed."""
|
|
990
|
+
if self._carries() and self.installs == getattr(self, "_call_installs", self.installs):
|
|
991
|
+
raise ValueError(
|
|
992
|
+
f"port controller carries edits for layer {self.layer} but the call never ran "
|
|
993
|
+
"that layer; the edits were not applied"
|
|
994
|
+
)
|
|
995
|
+
|
|
996
|
+
def _missing(self) -> list[str]:
|
|
997
|
+
if self._seen_layer is None or self._seen_layer != self.layer:
|
|
998
|
+
return []
|
|
999
|
+
cells = [cell.text for i, cell in enumerate(self.cells) if i not in self.cell_records]
|
|
1000
|
+
return sorted(set(self._edits_at) - {r["port"] for r in self._realised}) + cells
|
|
1001
|
+
|
|
1002
|
+
def unfired_before_stop(self) -> list[str]:
|
|
1003
|
+
"""Edited ports at or before the stop port whose edit did not fire (stop probes only)."""
|
|
1004
|
+
if self.stop is None:
|
|
1005
|
+
return []
|
|
1006
|
+
limit = self.program.index(self.stop)
|
|
1007
|
+
done = {r["port"] for r in self._realised}
|
|
1008
|
+
cells = [cell.text for i, cell in enumerate(self.cells)
|
|
1009
|
+
if cell.timing == "before" and i not in self.cell_records]
|
|
1010
|
+
return sorted(
|
|
1011
|
+
port
|
|
1012
|
+
for port in self._edits_at
|
|
1013
|
+
if self.program.index(port) <= limit and port not in done
|
|
1014
|
+
) + cells
|
|
1015
|
+
|
|
1016
|
+
def manifest(self) -> list[dict[str, Any]] | None:
|
|
1017
|
+
"""Edits whose hooks fired in the transition that just ran; consumed once.
|
|
1018
|
+
|
|
1019
|
+
Raises if the transition ran the layer this controller addresses and a staged edit did
|
|
1020
|
+
not fire, so a receipt can never omit an edit that was meant to apply.
|
|
1021
|
+
"""
|
|
1022
|
+
missing = self._missing()
|
|
1023
|
+
if missing:
|
|
1024
|
+
raise ValueError(f"staged edits were not realised: {', '.join(missing)}")
|
|
1025
|
+
failed = [
|
|
1026
|
+
entry["port"]
|
|
1027
|
+
for entry in self._realised
|
|
1028
|
+
if entry["port"] in ("s", "p") and entry.get("replica_verified") is False
|
|
1029
|
+
]
|
|
1030
|
+
if failed:
|
|
1031
|
+
raise ValueError(
|
|
1032
|
+
f"layer {self._layer_index}: replica check failed (max |replica - native| = "
|
|
1033
|
+
f"{self.replica_max_abs_diff}); refusing to commit the {', '.join(failed)} edit "
|
|
1034
|
+
"(its value mix is a replica that does not match the native computation)"
|
|
1035
|
+
)
|
|
1036
|
+
realised, self._realised, self._seen_layer = self._realised, [], None
|
|
1037
|
+
# State-cell edits realised in this call ride in the same list (entries carry a
|
|
1038
|
+
# ``cell`` key and the cell's ``port`` ``cache.L<l>.<k|v>``): address, op, operand
|
|
1039
|
+
# digest, origin and the realisation record. ``cell_records`` stays for the run.
|
|
1040
|
+
cells = [
|
|
1041
|
+
{**self.cells[i].manifest(), **self.cell_records[i]}
|
|
1042
|
+
for i in sorted(self.cell_records)
|
|
1043
|
+
]
|
|
1044
|
+
realised = [*realised, *cells]
|
|
1045
|
+
return realised or None
|
|
1046
|
+
|
|
1047
|
+
def probe_check(self) -> None:
|
|
1048
|
+
"""After a probe: the controller must have met the layer it addresses."""
|
|
1049
|
+
if self.layer is not None and not self._installed_now:
|
|
1050
|
+
ran = "no decoder layer" if self._seen_layer is None else f"layer {self._seen_layer}"
|
|
1051
|
+
raise ValueError(
|
|
1052
|
+
f"port controller addresses layer {self.layer} but the probed transition ran "
|
|
1053
|
+
f"{ran}; nothing was captured"
|
|
1054
|
+
)
|
|
1055
|
+
|
|
1056
|
+
@contextmanager
|
|
1057
|
+
def installed(self, adapter: Any, layer_index: int, layer_module: Any):
|
|
1058
|
+
if self.layer is not None and self.layer >= adapter.layers:
|
|
1059
|
+
raise ValueError(
|
|
1060
|
+
f"port controller addresses layer {self.layer} but the model has "
|
|
1061
|
+
f"{adapter.layers} layers"
|
|
1062
|
+
)
|
|
1063
|
+
self._seen_layer = layer_index
|
|
1064
|
+
if self.layer is not None and layer_index != self.layer:
|
|
1065
|
+
yield self
|
|
1066
|
+
return
|
|
1067
|
+
if self._active:
|
|
1068
|
+
raise ValueError("port controller is already installed")
|
|
1069
|
+
self._check(adapter, layer_module)
|
|
1070
|
+
self.captures, self.originals, self.order, self.checks = {}, {}, [], {}
|
|
1071
|
+
self.edited_captures, self.capture_notes, self.replica_verified = {}, {}, None
|
|
1072
|
+
self.replica_max_abs_diff = None
|
|
1073
|
+
self.realisation, self.fired, self.cell_records = None, {}, {}
|
|
1074
|
+
self._realised, self._live = [], {}
|
|
1075
|
+
self._layer_index = layer_index
|
|
1076
|
+
self._adapter = adapter
|
|
1077
|
+
self._local.depth = 0
|
|
1078
|
+
attention = layer_module.self_attn
|
|
1079
|
+
handles = self._register(layer_module)
|
|
1080
|
+
try:
|
|
1081
|
+
patch = _acquire(self, self.program.modeling_module(), attention)
|
|
1082
|
+
except Exception:
|
|
1083
|
+
for handle in handles:
|
|
1084
|
+
handle.remove()
|
|
1085
|
+
raise
|
|
1086
|
+
previous = getattr(_LOCAL, "active", None)
|
|
1087
|
+
self._active = True
|
|
1088
|
+
self._installed_now = True
|
|
1089
|
+
self.installs += 1
|
|
1090
|
+
completed = False
|
|
1091
|
+
_LOCAL.active = self
|
|
1092
|
+
try:
|
|
1093
|
+
yield self
|
|
1094
|
+
completed = True
|
|
1095
|
+
finally:
|
|
1096
|
+
_LOCAL.active = previous
|
|
1097
|
+
self._local.depth = 0
|
|
1098
|
+
self._live = {} # call-scoped references (h, r operands, the native mix): not kept
|
|
1099
|
+
_release(patch, attention)
|
|
1100
|
+
for handle in handles:
|
|
1101
|
+
handle.remove()
|
|
1102
|
+
self._active = False
|
|
1103
|
+
if completed:
|
|
1104
|
+
missing = self._missing()
|
|
1105
|
+
if missing:
|
|
1106
|
+
raise ValueError(f"staged edits were not realised: {', '.join(missing)}")
|
|
1107
|
+
|
|
1108
|
+
# --- installation ------------------------------------------------------------------
|
|
1109
|
+
|
|
1110
|
+
def _check(self, adapter: Any, layer_module: Any) -> None:
|
|
1111
|
+
if adapter.spec.model_type != self.program.family:
|
|
1112
|
+
raise ValueError(
|
|
1113
|
+
f"{self.program.family} port program cannot drive {adapter.spec.model_type}"
|
|
1114
|
+
)
|
|
1115
|
+
if adapter.execution.get("attention") != "eager":
|
|
1116
|
+
raise ValueError("port stepping requires eager attention")
|
|
1117
|
+
if adapter.execution.get("residency", "resident") != "resident":
|
|
1118
|
+
raise ValueError("port stepping supports resident execution only")
|
|
1119
|
+
check_deterministic(layer_module)
|
|
1120
|
+
patched = [name or "<layer>" for name, module in layer_module.named_modules()
|
|
1121
|
+
if rewritten_forward(module)]
|
|
1122
|
+
if patched:
|
|
1123
|
+
# a tool (nnsight .source) rewrote a forward AFTER attach; the eager
|
|
1124
|
+
# interceptor would not fire there, so qr/kr/s/p reads would crash and edits at
|
|
1125
|
+
# them would silently not apply. Refuse with the reason instead.
|
|
1126
|
+
raise ValueError(
|
|
1127
|
+
f"{len(patched)} module(s) of this layer run a rewritten forward (e.g. "
|
|
1128
|
+
f"{patched[0]!r}), as nnsight's .source leaves behind after attach; mdb's "
|
|
1129
|
+
"attention interceptor would not run there. Instrument "
|
|
1130
|
+
"mdb.interop.clone.shared_clone(model) (same weights) instead")
|
|
1131
|
+
for site in self.program.sites():
|
|
1132
|
+
_module(layer_module, site)
|
|
1133
|
+
|
|
1134
|
+
def _register(self, layer: Any) -> list[Any]:
|
|
1135
|
+
handles = []
|
|
1136
|
+
try:
|
|
1137
|
+
# entry counter first, exit counter (always called) last: hooks and the eager
|
|
1138
|
+
# interceptor act only on the outermost entry of the layer.
|
|
1139
|
+
handles.append(layer.register_forward_pre_hook(self._enter))
|
|
1140
|
+
if self.cells:
|
|
1141
|
+
handles.append(
|
|
1142
|
+
layer.register_forward_pre_hook(self._cells_before, with_kwargs=True)
|
|
1143
|
+
)
|
|
1144
|
+
for port in self.program.ports:
|
|
1145
|
+
if port.hook not in {"pre", "out"}:
|
|
1146
|
+
continue
|
|
1147
|
+
module = _module(layer, port.site)
|
|
1148
|
+
if port.name == "r":
|
|
1149
|
+
hook = module.register_forward_pre_hook(self._r_hook)
|
|
1150
|
+
elif port.hook == "pre":
|
|
1151
|
+
hook = module.register_forward_pre_hook(self._pre(port.name))
|
|
1152
|
+
else:
|
|
1153
|
+
hook = module.register_forward_hook(self._out(port.name))
|
|
1154
|
+
handles.append(hook)
|
|
1155
|
+
if self.cells: # not always_call: an interrupted call realises no "after" cell
|
|
1156
|
+
handles.append(layer.register_forward_hook(self._cells_after, with_kwargs=True))
|
|
1157
|
+
handles.append(layer.register_forward_hook(self._exit, always_call=True))
|
|
1158
|
+
except Exception:
|
|
1159
|
+
for handle in handles:
|
|
1160
|
+
handle.remove()
|
|
1161
|
+
raise
|
|
1162
|
+
return handles
|
|
1163
|
+
|
|
1164
|
+
@own_hook
|
|
1165
|
+
def _enter(self, module: Any, args: tuple[Any, ...]) -> None:
|
|
1166
|
+
self._local.depth = getattr(self._local, "depth", 0) + 1
|
|
1167
|
+
|
|
1168
|
+
@own_hook
|
|
1169
|
+
def _exit(self, module: Any, args: tuple[Any, ...], output: Any) -> None:
|
|
1170
|
+
self._local.depth = max(getattr(self._local, "depth", 0) - 1, 0)
|
|
1171
|
+
|
|
1172
|
+
def _write_cells(self, kwargs: dict[str, Any], timing: str) -> None:
|
|
1173
|
+
"""Realise the ``timing`` cell edits into the cache object the native layer was handed
|
|
1174
|
+
(copy-on-write: each written layer tensor is replaced by an edited copy)."""
|
|
1175
|
+
if not self._engaged():
|
|
1176
|
+
return
|
|
1177
|
+
cache = kwargs.get(self._adapter.spec.cache_kwarg)
|
|
1178
|
+
if cache is None:
|
|
1179
|
+
raise ValueError("the layer call carries no key/value cache to edit")
|
|
1180
|
+
for index, cell in enumerate(self.cells):
|
|
1181
|
+
if cell.timing != timing or index in self.cell_records:
|
|
1182
|
+
continue
|
|
1183
|
+
if cell.layer >= len(cache.layers):
|
|
1184
|
+
raise ValueError(f"{cell.port}: the cache holds no layer {cell.layer}")
|
|
1185
|
+
slot = cache.layers[cell.layer]
|
|
1186
|
+
name = "keys" if cell.tensor == "k" else "values"
|
|
1187
|
+
current = getattr(slot, name, None)
|
|
1188
|
+
if current is None:
|
|
1189
|
+
raise ValueError(f"{cell.port} holds no rows yet")
|
|
1190
|
+
written, record = cell.realise(current)
|
|
1191
|
+
setattr(slot, name, written)
|
|
1192
|
+
self.cell_records[index] = {**record, "realised_timing": timing,
|
|
1193
|
+
"realised_in_layer": self._layer_index}
|
|
1194
|
+
|
|
1195
|
+
@own_hook
|
|
1196
|
+
def _cells_before(self, module: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
|
|
1197
|
+
self._write_cells(kwargs, "before")
|
|
1198
|
+
|
|
1199
|
+
@own_hook
|
|
1200
|
+
def _cells_after(
|
|
1201
|
+
self, module: Any, args: tuple[Any, ...], kwargs: dict[str, Any], output: Any
|
|
1202
|
+
) -> None:
|
|
1203
|
+
self._write_cells(kwargs, "after")
|
|
1204
|
+
|
|
1205
|
+
def _engaged(self) -> bool:
|
|
1206
|
+
"""True only inside this controller's own transition, in the calling thread, at the
|
|
1207
|
+
outermost entry of the addressed layer (a nested forward of the same model from a user
|
|
1208
|
+
hook runs natively)."""
|
|
1209
|
+
return getattr(_LOCAL, "active", None) is self and getattr(self._local, "depth", 0) == 1
|
|
1210
|
+
|
|
1211
|
+
def _keep(self, name: str, value: torch.Tensor) -> None:
|
|
1212
|
+
self.order.append(name)
|
|
1213
|
+
if name in self._capture:
|
|
1214
|
+
self.captures[name] = value.detach().clone()
|
|
1215
|
+
if name == self.stop:
|
|
1216
|
+
raise _Stop(name)
|
|
1217
|
+
|
|
1218
|
+
def _mark_edited(self, port: str, by: str, kind: str) -> None:
|
|
1219
|
+
seen = self.edited_captures.get(port)
|
|
1220
|
+
if seen is not None and by not in seen["by"].split(","):
|
|
1221
|
+
by = f"{seen['by']},{by}"
|
|
1222
|
+
self.edited_captures[port] = {"by": by, "kind": kind}
|
|
1223
|
+
|
|
1224
|
+
def _value(self, name: str, x: torch.Tensor) -> torch.Tensor:
|
|
1225
|
+
edits = self._edits_at.get(name)
|
|
1226
|
+
native_mix = self._live.pop("A_native", None) if name == "A" else None
|
|
1227
|
+
if native_mix is not None:
|
|
1228
|
+
self.originals["A"] = native_mix # the native value mix, before the replica's
|
|
1229
|
+
if edits:
|
|
1230
|
+
self.originals.setdefault(name, x.detach().clone())
|
|
1231
|
+
for edit in edits:
|
|
1232
|
+
x, record = edit.realise(x)
|
|
1233
|
+
entry = {**edit.manifest(), "layer": self._layer_index, **record}
|
|
1234
|
+
if name in ("s", "p"):
|
|
1235
|
+
entry["mix"] = "replica"
|
|
1236
|
+
entry["replica_verified"] = None
|
|
1237
|
+
if name == "p":
|
|
1238
|
+
entry.update(_row_statistics(x))
|
|
1239
|
+
with_labels(entry)
|
|
1240
|
+
self._realised.append(entry)
|
|
1241
|
+
self.fired[id(edit)] = entry
|
|
1242
|
+
self._mark_edited(name, name, "edit")
|
|
1243
|
+
if name == "h":
|
|
1244
|
+
self._live["h"] = x
|
|
1245
|
+
if name == "o" and "r" in self._edits_at:
|
|
1246
|
+
self.originals.setdefault("o", x.detach().clone())
|
|
1247
|
+
x = self._realise_r(x)
|
|
1248
|
+
self._mark_edited("o", "r", "realisation")
|
|
1249
|
+
self._keep(name, x)
|
|
1250
|
+
return x
|
|
1251
|
+
|
|
1252
|
+
def _realise_r(self, o: torch.Tensor) -> torch.Tensor:
|
|
1253
|
+
h = self._live["h"]
|
|
1254
|
+
native = h + o # a new tensor nothing writes: the original of r, held once uncopied
|
|
1255
|
+
target = native
|
|
1256
|
+
inputs, outputs = [], []
|
|
1257
|
+
for edit in self._edits_at["r"]:
|
|
1258
|
+
inputs.append(target)
|
|
1259
|
+
target = edit.apply(target) # the records are made in _r_hook, once r is known
|
|
1260
|
+
outputs.append(target)
|
|
1261
|
+
self.originals["r"] = native
|
|
1262
|
+
self._live["r_target"] = target
|
|
1263
|
+
self._live["r_inputs"] = inputs
|
|
1264
|
+
self._live["r_outputs"] = outputs
|
|
1265
|
+
self._live["r_native"] = native
|
|
1266
|
+
edits = self._edits_at["r"]
|
|
1267
|
+
if any(edit.mask is None for edit in edits):
|
|
1268
|
+
new_o = target - h
|
|
1269
|
+
else:
|
|
1270
|
+
union = torch.zeros(o.shape, dtype=torch.bool, device=o.device)
|
|
1271
|
+
for edit in edits:
|
|
1272
|
+
union |= edit.selected(o.shape, o.device)
|
|
1273
|
+
new_o = torch.where(union, target - h, o)
|
|
1274
|
+
predicted = h + new_o
|
|
1275
|
+
self.realisation = {
|
|
1276
|
+
"exact": bool(torch.equal(predicted, target)),
|
|
1277
|
+
"max_abs_error": max_abs((wide(predicted) - wide(target)).abs()),
|
|
1278
|
+
}
|
|
1279
|
+
return new_o
|
|
1280
|
+
|
|
1281
|
+
@own_hook
|
|
1282
|
+
def _r_hook(self, module: Any, args: tuple[Any, ...]) -> None:
|
|
1283
|
+
if not self._engaged():
|
|
1284
|
+
return None
|
|
1285
|
+
r = args[0]
|
|
1286
|
+
target = self._live.get("r_target")
|
|
1287
|
+
if target is not None:
|
|
1288
|
+
error = max_abs((wide(r) - wide(target)).abs())
|
|
1289
|
+
native = self._live["r_native"]
|
|
1290
|
+
self.realisation = {"exact": bool(torch.equal(r, target)), "max_abs_error": error}
|
|
1291
|
+
edits = self._edits_at["r"]
|
|
1292
|
+
outputs = self._live["r_outputs"]
|
|
1293
|
+
for position, edit in enumerate(edits):
|
|
1294
|
+
# the last edit's effect is what actually entered the model at r (r = h + o')
|
|
1295
|
+
actual = r if position == len(edits) - 1 else outputs[position]
|
|
1296
|
+
record = edit.measure(self._live["r_inputs"][position], actual)
|
|
1297
|
+
# realised_* are measured against the exact float64 result of x op requested,
|
|
1298
|
+
# as at every port; the cost of realising r through o is recorded separately.
|
|
1299
|
+
entry = {
|
|
1300
|
+
**edit.manifest(),
|
|
1301
|
+
"layer": self._layer_index,
|
|
1302
|
+
**{k: v for k, v in record.items() if k != "changed_fraction"},
|
|
1303
|
+
"realised_at": "o",
|
|
1304
|
+
"realisation_exact": self.realisation["exact"],
|
|
1305
|
+
"realisation_max_abs_error": error,
|
|
1306
|
+
"changed_fraction": changed_fraction(native, r),
|
|
1307
|
+
}
|
|
1308
|
+
with_labels(entry)
|
|
1309
|
+
self._realised.append(entry)
|
|
1310
|
+
self.fired[id(edit)] = entry
|
|
1311
|
+
self._mark_edited("r", "r", "edit")
|
|
1312
|
+
self._keep("r", r)
|
|
1313
|
+
|
|
1314
|
+
def _pre(self, name: str):
|
|
1315
|
+
@own_hook
|
|
1316
|
+
def hook(module: Any, args: tuple[Any, ...]):
|
|
1317
|
+
if not self._engaged():
|
|
1318
|
+
return None
|
|
1319
|
+
value = self._value(name, args[0])
|
|
1320
|
+
return None if value is args[0] else (value, *args[1:])
|
|
1321
|
+
|
|
1322
|
+
return hook
|
|
1323
|
+
|
|
1324
|
+
def _out(self, name: str):
|
|
1325
|
+
@own_hook
|
|
1326
|
+
def hook(module: Any, args: tuple[Any, ...], output: Any):
|
|
1327
|
+
if not self._engaged():
|
|
1328
|
+
return None
|
|
1329
|
+
first = output[0] if isinstance(output, tuple) else output
|
|
1330
|
+
value = self._value(name, first)
|
|
1331
|
+
if value is first:
|
|
1332
|
+
return None
|
|
1333
|
+
return (value, *output[1:]) if isinstance(output, tuple) else value
|
|
1334
|
+
|
|
1335
|
+
return hook
|
|
1336
|
+
|
|
1337
|
+
def _eager(self, patch: _Patch, module, query, key, value, attention_mask, *args, **kwargs):
|
|
1338
|
+
original, repeat_kv = patch.original, patch.repeat_kv
|
|
1339
|
+
dropout = kwargs.get("dropout", args[0] if args else 0.0)
|
|
1340
|
+
if module.training or dropout:
|
|
1341
|
+
raise ValueError("port stepping requires dropout-free eval attention")
|
|
1342
|
+
query = self._value("qr", query)
|
|
1343
|
+
self._value("kr", key)
|
|
1344
|
+
scaling = kwargs.get("scaling", getattr(module, "scaling", None))
|
|
1345
|
+
groups = module.num_key_value_groups
|
|
1346
|
+
scores = torch.matmul(query, repeat_kv(key, groups).transpose(2, 3)) * scaling
|
|
1347
|
+
if attention_mask is not None:
|
|
1348
|
+
scores = scores + attention_mask
|
|
1349
|
+
used = self._value("s", scores)
|
|
1350
|
+
output, weights = original(module, query, key, value, attention_mask, *args, **kwargs)
|
|
1351
|
+
reference = torch.nn.functional.softmax(scores, dim=-1, dtype=torch.float32).to(
|
|
1352
|
+
query.dtype
|
|
1353
|
+
)
|
|
1354
|
+
s_check = _equality(reference, weights)
|
|
1355
|
+
self.checks["s"] = s_check
|
|
1356
|
+
self.capture_notes["s"] = {
|
|
1357
|
+
"replica_equal": s_check["equal"],
|
|
1358
|
+
"max_abs_diff": s_check.get("max_abs_diff", 0.0),
|
|
1359
|
+
}
|
|
1360
|
+
probs = weights
|
|
1361
|
+
if used is not scores:
|
|
1362
|
+
self.originals["p"] = weights.detach().clone()
|
|
1363
|
+
probs = torch.nn.functional.softmax(used, dim=-1, dtype=torch.float32).to(query.dtype)
|
|
1364
|
+
self._mark_edited("p", "s", "replica")
|
|
1365
|
+
edited = self._value("p", probs) # a stop at p ends here; the mix is checked at A
|
|
1366
|
+
native_mix = torch.matmul(weights, repeat_kv(value, groups)).transpose(1, 2).contiguous()
|
|
1367
|
+
mix_check = _equality(native_mix, output)
|
|
1368
|
+
self.checks["mix_replica"] = mix_check
|
|
1369
|
+
self.replica_verified = bool(s_check["equal"] and mix_check["equal"])
|
|
1370
|
+
self.replica_max_abs_diff = max(
|
|
1371
|
+
s_check.get("max_abs_diff", 0.0), mix_check.get("max_abs_diff", 0.0)
|
|
1372
|
+
)
|
|
1373
|
+
mix = torch.matmul(edited, repeat_kv(value, groups)).transpose(1, 2).contiguous()
|
|
1374
|
+
for entry in self._realised:
|
|
1375
|
+
if entry["port"] in ("s", "p"):
|
|
1376
|
+
entry["replica_verified"] = self.replica_verified
|
|
1377
|
+
if edited is weights:
|
|
1378
|
+
self.checks["mix"] = mix_check
|
|
1379
|
+
return output, weights
|
|
1380
|
+
self.checks["mix"] = {"replica": True, "native_unedited": False}
|
|
1381
|
+
self._live["A_native"] = output.detach().reshape(*output.shape[:-2], -1).clone()
|
|
1382
|
+
return mix, edited
|
|
1383
|
+
|
|
1384
|
+
|
|
1385
|
+
def _row_statistics(probs: torch.Tensor) -> dict[str, Any]:
|
|
1386
|
+
"""Row sums and minimum of an edited ``p``. The row-sum tolerance is a supplied constant by
|
|
1387
|
+
dtype: the dtype's machine epsilon for bf16/f16, 1e-5 for fp32, 1e-12 for fp64."""
|
|
1388
|
+
if probs.dtype in (torch.bfloat16, torch.float16):
|
|
1389
|
+
tolerance = float(torch.finfo(probs.dtype).eps)
|
|
1390
|
+
elif probs.dtype == torch.float64:
|
|
1391
|
+
tolerance = 1e-12
|
|
1392
|
+
else:
|
|
1393
|
+
tolerance = 1e-5
|
|
1394
|
+
wide = probs.detach().to("cpu", torch.float64)
|
|
1395
|
+
sums = wide.sum(dim=-1)
|
|
1396
|
+
low, high, smallest = float(sums.min()), float(sums.max()), float(wide.min())
|
|
1397
|
+
return {
|
|
1398
|
+
"row_sum_min": low,
|
|
1399
|
+
"row_sum_max": high,
|
|
1400
|
+
"min": smallest,
|
|
1401
|
+
"row_sum_tolerance": tolerance,
|
|
1402
|
+
"is_distribution": bool(smallest >= 0.0 and max(abs(low - 1), abs(high - 1)) <= tolerance),
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
|
|
1406
|
+
def _equality(replica: torch.Tensor, native: torch.Tensor) -> dict[str, Any]:
|
|
1407
|
+
# bit-for-bit, with NaN positions counted as equal (an overflowing edit makes both NaN)
|
|
1408
|
+
equal = bool(torch.equal(replica, native)) or bool(
|
|
1409
|
+
torch.allclose(wide(replica), wide(native), rtol=0.0, atol=0.0, equal_nan=True)
|
|
1410
|
+
)
|
|
1411
|
+
result: dict[str, Any] = {"equal": equal}
|
|
1412
|
+
if not equal: # measured: the float64 difference of the two native-dtype values (exact)
|
|
1413
|
+
result["max_abs_diff"] = float((wide(replica) - wide(native)).abs().max())
|
|
1414
|
+
return result
|
|
1415
|
+
|
|
1416
|
+
|
|
1417
|
+
def observe_all(program: PortProgram) -> PortController:
|
|
1418
|
+
"""An edit-free controller that captures every port of whichever layer runs."""
|
|
1419
|
+
return PortController(program, None)
|
|
1420
|
+
|
|
1421
|
+
|
|
1422
|
+
# Old private names, kept for one commit: engine/edits.py imported them.
|
|
1423
|
+
_with_labels = with_labels
|
|
1424
|
+
_max_abs = max_abs
|