model-debugger 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""Hops: how an edit of one cache cell reaches a later reader, exactly, through one layer.
|
|
2
|
+
|
|
3
|
+
``CellTarget`` names a cell consumer (a key/value cell, or a token pair along a direction);
|
|
4
|
+
``cell_value``/``cell_readout`` read it. ``hop_edge`` splits the native change of a reader
|
|
5
|
+
under an edited write into its exact first-order parts (attention, MLP neurons, the rest),
|
|
6
|
+
and ``gate_switch_forecast`` forecasts which MLP gates switch. ``symbols.table`` does not use
|
|
7
|
+
these; ``symbol_finite`` builds on ``hop_edge``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from ..numerics.labels import EXACT, MEASURED, f64, num
|
|
17
|
+
from ..predict.consumers import Margin, Refusal
|
|
18
|
+
from .table import _torch
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _silu_prime(x: Any) -> Any:
|
|
22
|
+
torch = _torch()
|
|
23
|
+
sig = torch.sigmoid(x)
|
|
24
|
+
return sig * (1 + x * (1 - sig))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _rfft_parts(weight_rows: Any, delta: Any, gw: Any = None) -> Any:
|
|
28
|
+
"""Parseval split of ``weight_rows @ delta`` over channel-DFT bins: (rows, bins) float64 whose
|
|
29
|
+
row sums equal ``weight_rows @ delta`` (real rfft, x.y = (1/d) sum_k s_k Re(conj(X_k) Y_k),
|
|
30
|
+
s_k = 1 at DC and Nyquist, else 2). ``gw``: the rows' rfft when already taken."""
|
|
31
|
+
torch = _torch()
|
|
32
|
+
d = int(delta.numel())
|
|
33
|
+
if gw is None:
|
|
34
|
+
gw = torch.fft.rfft(weight_rows, dim=1)
|
|
35
|
+
dn = torch.fft.rfft(delta.reshape(-1))
|
|
36
|
+
scale = torch.full((gw.shape[1],), 2.0, dtype=torch.float64)
|
|
37
|
+
scale[0] = 1.0
|
|
38
|
+
if d % 2 == 0:
|
|
39
|
+
scale[-1] = 1.0
|
|
40
|
+
return (gw.conj() * dn[None, :]).real * (scale / d)[None, :]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class CellTarget:
|
|
45
|
+
"""The content of one value cell (row ``row``, layer ``layer``, KV head ``kv``) as a scalar:
|
|
46
|
+
``C(v) = d . W_g v`` with ``W_g = sum_{h in kappa^-1(g)} W_O,h`` and
|
|
47
|
+
``d = gamma_F * (W_U[a] - W_U[b])`` (the cell's write at unit mass through the final-norm
|
|
48
|
+
readout, per unit final rho; P06/P07, P19)."""
|
|
49
|
+
|
|
50
|
+
row: int
|
|
51
|
+
layer: int
|
|
52
|
+
kv: int
|
|
53
|
+
a: int
|
|
54
|
+
b: int
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def text(self) -> str:
|
|
58
|
+
return f"cell t{self.row}.L{self.layer}.v[kv{self.kv}] M[{self.a},{self.b}]"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _cell_direction(run: Any, target: CellTarget) -> Any:
|
|
62
|
+
"""``W_g^T d`` (head_dim, float64)."""
|
|
63
|
+
from .circuit_map import group_writers
|
|
64
|
+
|
|
65
|
+
adapter = run.adapter
|
|
66
|
+
final = getattr(adapter.backbone, adapter.spec.final_norm)
|
|
67
|
+
w_u = adapter.model.lm_head.weight
|
|
68
|
+
d = f64(final.weight).reshape(-1) * (f64(w_u[target.a]) - f64(w_u[target.b])).cpu()
|
|
69
|
+
from ..measure.readout import layer_module
|
|
70
|
+
o_weight = layer_module(adapter, target.layer).self_attn.o_proj.weight
|
|
71
|
+
w_g = group_writers(o_weight, adapter.num_heads, adapter.num_kv_heads)[target.kv]
|
|
72
|
+
return w_g.T @ d
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def cell_value(run: Any, target: CellTarget, direction: Any = None) -> float:
|
|
76
|
+
"""``C(v)`` of the cell as the run's cache holds it (float64)."""
|
|
77
|
+
direction = _cell_direction(run, target) if direction is None else direction
|
|
78
|
+
v = f64(run.read_cache(target.layer, "v", staged=False))[0, target.kv, target.row]
|
|
79
|
+
return float(direction @ v.reshape(-1))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def cell_readout(run: Any, target: CellTarget) -> Any:
|
|
83
|
+
"""A ``Readout`` (kind ``cell``) of ``C`` as an affine functional of the residual entering
|
|
84
|
+
the cell's layer at its row: with no v norm, ``v_g = W_V^g (rho gamma_l * h) + b_V^g`` with
|
|
85
|
+
``h = t<row>.L<layer>.h`` and ``rho`` its input-norm scale, so
|
|
86
|
+
``C = c . h + bias`` with ``c = rho_0 gamma_l * (W_V^g)^T W_g^T d`` at the native rho_0 and
|
|
87
|
+
``bias = d . W_g b_V^g`` (0 without a V bias, e.g. Qwen3; Qwen2 has one). The bias cancels
|
|
88
|
+
in every difference, so ``hop_edge`` uses ``c`` alone (derived-exact). ``native`` is ``C``
|
|
89
|
+
read from the cache cell."""
|
|
90
|
+
from ..measure.readout import Readout, layer_module
|
|
91
|
+
|
|
92
|
+
module = layer_module(run.adapter, target.layer)
|
|
93
|
+
if getattr(module.self_attn, "v_norm", None) is not None:
|
|
94
|
+
raise Refusal("cell readout: the model normalises V (not an affine functional)")
|
|
95
|
+
dh = run.adapter.head_dim
|
|
96
|
+
direction = _cell_direction(run, target)
|
|
97
|
+
rows = slice(target.kv * dh, (target.kv + 1) * dh)
|
|
98
|
+
w_v = f64(module.self_attn.v_proj.weight)[rows] # (dh, d)
|
|
99
|
+
b_v = getattr(module.self_attn.v_proj, "bias", None)
|
|
100
|
+
bias = 0.0 if b_v is None else float(direction @ f64(b_v)[rows])
|
|
101
|
+
norm = module.input_layernorm
|
|
102
|
+
gamma, eps = f64(norm.weight).reshape(-1), float(norm.variance_epsilon)
|
|
103
|
+
h = f64(run.read(f"t{target.row}.L{target.layer}.h")).reshape(-1)
|
|
104
|
+
rho = float((h.pow(2).mean() + eps) ** -0.5)
|
|
105
|
+
vector = rho * gamma * (w_v.T @ direction)
|
|
106
|
+
return Readout("cell", target.text, target.row, target, layer=target.layer, port="h",
|
|
107
|
+
vector=vector, rho=rho, bias=bias,
|
|
108
|
+
native=cell_value(run, target, direction), native_authority=MEASURED,
|
|
109
|
+
premises=["v = W_V^g n + b_V^g with n = rho gamma h: no v norm (checked); "
|
|
110
|
+
"the V bias enters only as the constant bias",
|
|
111
|
+
"rho of the cell layer's input norm at the native state"])
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def hop_edge(run: Any, edited: Any, reader: Any, *, cell_layer: int, top_neurons: int = 8,
|
|
115
|
+
spectral: bool = False, top_bins: int = 32, seed: int = 0,
|
|
116
|
+
cache: dict | None = None, neurons: bool = True) -> dict[str, Any]:
|
|
117
|
+
"""The exact hop ladder of a finite cell edit at the consumer's row.
|
|
118
|
+
|
|
119
|
+
With a ``cell`` reader (``cell_readout``) the consumer is a value cell's content at an
|
|
120
|
+
intermediate row and layer: the ladder runs over layers ``cell_layer .. reader.layer - 1``
|
|
121
|
+
at that row, the native delta is the change of ``C`` read from the two caches, and the
|
|
122
|
+
norm term uses the cell layer's input norm.
|
|
123
|
+
|
|
124
|
+
``run`` is the native run and ``edited`` the same prompt with the cell edit staged and run
|
|
125
|
+
natively to the consumer's logits; ``reader`` the native scalar ``Readout`` (``c``, native
|
|
126
|
+
rho). ``Delta M_native = c.delta + sum_l c.Delta m_l + sum_{l>cell} c.Delta o_l + Delta_norm
|
|
127
|
+
+ Delta_round``: ``delta`` = the change of the cell layer's attention write at the row,
|
|
128
|
+
``Delta m_l`` / ``Delta o_l`` the captured MLP and attention-write changes (re-reads), the
|
|
129
|
+
norm term ``(rho_1 - rho_0) w . h_out,1`` (exact finite RMS identity) and the rounding the
|
|
130
|
+
measured remainder. Per neuron (finite SwiGLU identity, exact): ``Delta f_i = b0 Delta s +
|
|
131
|
+
s0 Delta b + Delta s Delta b`` on the captured ``sg`` and ``u``; effect ``c . W_down[:, i]
|
|
132
|
+
Delta f_i`` (P15); the top ``top_neurons`` by |effect| per layer are listed and the rest
|
|
133
|
+
summed. ``linear`` is the one-layer Jacobian term on the layer's actual input change (P14,
|
|
134
|
+
derived-local), never the effect; ``nonlinear = exact - linear``. With ``spectral`` the
|
|
135
|
+
``Delta a`` of every neuron is split over channel-DFT bins by Parseval and the top
|
|
136
|
+
``top_bins`` bins' share of the |effect|-weighted credit is reported against the same share
|
|
137
|
+
under a random channel permutation and against the neuron basis at the same unit fraction.
|
|
138
|
+
``cache``: a dict the caller keeps across calls on the same model; it holds, per layer, the
|
|
139
|
+
consumer's ``c . W_down`` (keyed by the bytes of ``c``) and the spectral permutation. The
|
|
140
|
+
float64 gate/up weights (and their channel rfft) are cast for one layer at a time and
|
|
141
|
+
dropped before the next, so the float64 peak is one layer's matrices, not every layer's
|
|
142
|
+
(the same full-matrix float64 operations, so the same values).
|
|
143
|
+
``neurons=False``: the layer terms only (direct, captured MLP writes, re-reads, norm,
|
|
144
|
+
rounding) from the two runs' ports; no MLP weight is read (no float64 weight copies), so the
|
|
145
|
+
per-neuron split, ``exact``/``linear`` per layer and ``spectral`` are omitted.
|
|
146
|
+
"""
|
|
147
|
+
torch = _torch()
|
|
148
|
+
from ..measure.readout import layer_module
|
|
149
|
+
|
|
150
|
+
if reader is None or not (reader.scalar or reader.kind == "cell"):
|
|
151
|
+
raise Refusal("hop_edge needs a scalar consumer (a margin, a logit or a cell)")
|
|
152
|
+
j, layers = reader.row, run.adapter.layers
|
|
153
|
+
top_layer = reader.layer if reader.kind == "cell" else None
|
|
154
|
+
end = layers if top_layer is None else top_layer
|
|
155
|
+
if not 0 <= cell_layer < end:
|
|
156
|
+
raise Refusal(f"cell layer {cell_layer} is not below the consumer's layer {end}")
|
|
157
|
+
c = f64(reader.vector).reshape(-1)
|
|
158
|
+
|
|
159
|
+
def port(r, layer, name):
|
|
160
|
+
return f64(r.read(f"t{j}.L{layer}.{name}")).reshape(-1)
|
|
161
|
+
|
|
162
|
+
def margin(r):
|
|
163
|
+
if top_layer is not None:
|
|
164
|
+
return cell_value(r, reader.target)
|
|
165
|
+
logits = r.read(f"t{j}.logits").reshape(-1)
|
|
166
|
+
t = reader.target
|
|
167
|
+
return float(f64(logits[t.a]) - f64(logits[t.b])) if isinstance(t, Margin) else \
|
|
168
|
+
float(f64(logits[t.i]))
|
|
169
|
+
|
|
170
|
+
native_delta = margin(edited) - margin(run)
|
|
171
|
+
direct = float(c @ (port(edited, cell_layer, "o") - port(run, cell_layer, "o")))
|
|
172
|
+
upstream = float(c @ (port(edited, cell_layer, "h") - port(run, cell_layer, "h")))
|
|
173
|
+
gen = torch.Generator().manual_seed(seed)
|
|
174
|
+
cache = {} if cache is None else cache
|
|
175
|
+
|
|
176
|
+
c_key = hashlib.sha256(c.contiguous().numpy().tobytes()).hexdigest()
|
|
177
|
+
|
|
178
|
+
def consumer_down(layer, module):
|
|
179
|
+
"""``c @ W_down`` (float64, full matrix), the only use of ``W_down`` here."""
|
|
180
|
+
key = ("cd", layer, c_key)
|
|
181
|
+
if key not in cache:
|
|
182
|
+
cache[key] = c @ f64(module.mlp.down_proj.weight) # the cast is dropped here
|
|
183
|
+
return cache[key]
|
|
184
|
+
|
|
185
|
+
def spectra(layer, gate):
|
|
186
|
+
key = ("perm", layer, seed)
|
|
187
|
+
if key not in cache:
|
|
188
|
+
cache[key] = torch.randperm(gate.shape[1], generator=gen)
|
|
189
|
+
perm = cache[key]
|
|
190
|
+
return torch.fft.rfft(gate, dim=1), perm, torch.fft.rfft(gate[:, perm], dim=1)
|
|
191
|
+
mlp, reread, closure_sum = [], [], direct + upstream
|
|
192
|
+
for layer in range(cell_layer, end):
|
|
193
|
+
module = layer_module(run.adapter, layer)
|
|
194
|
+
if layer > cell_layer:
|
|
195
|
+
d_o = float(c @ (port(edited, layer, "o") - port(run, layer, "o")))
|
|
196
|
+
reread.append({"layer": layer, "effect": num(d_o, EXACT, "P07"),
|
|
197
|
+
"meaning": "c . Delta o at the consumer row: later heads re-reading "
|
|
198
|
+
"changed rows, not an MLP path"})
|
|
199
|
+
closure_sum += d_o
|
|
200
|
+
if not neurons:
|
|
201
|
+
captured = float(c @ (port(edited, layer, "m") - port(run, layer, "m")))
|
|
202
|
+
closure_sum += captured
|
|
203
|
+
mlp.append({"layer": layer, "captured": num(captured, MEASURED)})
|
|
204
|
+
continue
|
|
205
|
+
g0, g1 = port(run, layer, "g"), port(edited, layer, "g")
|
|
206
|
+
s0, s1 = port(run, layer, "sg"), port(edited, layer, "sg")
|
|
207
|
+
b0, b1 = port(run, layer, "u"), port(edited, layer, "u")
|
|
208
|
+
ds, db = s1 - s0, b1 - b0
|
|
209
|
+
terms = torch.stack([b0 * ds, s0 * db, ds * db]) # (3, d_ff)
|
|
210
|
+
df = terms.sum(0)
|
|
211
|
+
gate, up = f64(module.mlp.gate_proj.weight), f64(module.mlp.up_proj.weight)
|
|
212
|
+
cd = consumer_down(layer, module) # (d_ff,)
|
|
213
|
+
effect = cd * df
|
|
214
|
+
exact = float(effect.sum())
|
|
215
|
+
captured = float(c @ (port(edited, layer, "m") - port(run, layer, "m")))
|
|
216
|
+
closure_sum += captured
|
|
217
|
+
# one-layer Jacobian on the actual input change (P14)
|
|
218
|
+
r0, r1 = port(run, layer, "r"), port(edited, layer, "r")
|
|
219
|
+
norm = module.post_attention_layernorm
|
|
220
|
+
gamma_l, eps = f64(norm.weight).reshape(-1), float(norm.variance_epsilon)
|
|
221
|
+
rho0 = float((r0.pow(2).mean() + eps) ** -0.5)
|
|
222
|
+
dr = r1 - r0
|
|
223
|
+
dn_lin = gamma_l * (rho0 * dr - (rho0 ** 3 / dr.numel()) * float(r0 @ dr) * r0)
|
|
224
|
+
da_lin, db_lin = gate @ dn_lin, up @ dn_lin
|
|
225
|
+
linear = float((cd * (b0 * _silu_prime(g0) * da_lin + s0 * db_lin)).sum())
|
|
226
|
+
dn_true = port(edited, layer, "n") - port(run, layer, "n")
|
|
227
|
+
den = float(dn_true.norm() * dn_lin.norm())
|
|
228
|
+
da_true = g1 - g0
|
|
229
|
+
da_den = float(da_true.norm() * da_lin.norm())
|
|
230
|
+
order = effect.abs().argsort(descending=True)
|
|
231
|
+
top = order[:top_neurons]
|
|
232
|
+
rest = order[top_neurons:]
|
|
233
|
+
listed = [{"name": f"L{layer}.f{int(i)}", "da": num(float(g1[i] - g0[i]), EXACT),
|
|
234
|
+
"db": num(float(db[i]), EXACT), "df": num(float(df[i]), EXACT),
|
|
235
|
+
"b0_ds": num(float(terms[0, i]), EXACT),
|
|
236
|
+
"s0_db": num(float(terms[1, i]), EXACT),
|
|
237
|
+
"ds_db": num(float(terms[2, i]), EXACT),
|
|
238
|
+
"effect": num(float(effect[i]), EXACT, "P15")} for i in top]
|
|
239
|
+
entry = {"layer": layer,
|
|
240
|
+
"exact": num(exact, EXACT, "P15"),
|
|
241
|
+
"captured": num(captured, MEASURED),
|
|
242
|
+
"down_rounding": num(captured - exact, MEASURED),
|
|
243
|
+
"linear": num(linear, "derived-local", "P14"),
|
|
244
|
+
"nonlinear": num(exact - linear, EXACT),
|
|
245
|
+
"shared_gate": num(float((g1 - g0).mean()), EXACT),
|
|
246
|
+
"input_linearity": {
|
|
247
|
+
"cos_dn": num(float(dn_true @ dn_lin) / den if den else 0.0, EXACT),
|
|
248
|
+
"norm_ratio_dn": num(float(dn_lin.norm() / dn_true.norm())
|
|
249
|
+
if float(dn_true.norm()) else 0.0, EXACT),
|
|
250
|
+
"cos_da": num(float(da_true @ da_lin) / da_den if da_den else 0.0, EXACT),
|
|
251
|
+
"meaning": "the Jacobian input change (J_RMS Delta r, G J_RMS Delta r) "
|
|
252
|
+
"against the captured Delta n and Delta a"},
|
|
253
|
+
"neurons": listed,
|
|
254
|
+
"omitted": {"count": int(rest.numel()),
|
|
255
|
+
"effect": num(float(effect[rest].sum()), EXACT, "P15")},
|
|
256
|
+
"top_share": num(float(effect[top].abs().sum() / effect.abs().sum())
|
|
257
|
+
if float(effect.abs().sum()) else 0.0, EXACT)}
|
|
258
|
+
if spectral:
|
|
259
|
+
dn = dn_true
|
|
260
|
+
wabs = effect.abs()
|
|
261
|
+
gw, perm, pgw = spectra(layer, gate)
|
|
262
|
+
parts = _rfft_parts(gate, dn, gw) # (d_ff, bins)
|
|
263
|
+
credit = (wabs[:, None] * parts.abs()).sum(0)
|
|
264
|
+
pparts = _rfft_parts(None, dn[perm], pgw)
|
|
265
|
+
pcredit = (wabs[:, None] * pparts.abs()).sum(0)
|
|
266
|
+
bins = credit.numel()
|
|
267
|
+
k_neurons = max(1, round(top_bins / bins * effect.numel()))
|
|
268
|
+
spec = torch.fft.rfft(dn).abs().pow(2)
|
|
269
|
+
pspec = torch.fft.rfft(dn[perm]).abs().pow(2)
|
|
270
|
+
|
|
271
|
+
def share(x, k):
|
|
272
|
+
return float(x.sort(descending=True).values[:k].sum() / x.sum()) if float(
|
|
273
|
+
x.sum()) else 0.0
|
|
274
|
+
entry["spectral"] = {
|
|
275
|
+
"bins": bins, "top_bins": top_bins, "neurons_at_same_fraction": k_neurons,
|
|
276
|
+
"parseval_max_error": num(float((parts.sum(1) - (gate @ dn)).abs().max()),
|
|
277
|
+
MEASURED),
|
|
278
|
+
"credit_top_bins_share": num(share(credit, top_bins), EXACT),
|
|
279
|
+
"credit_top_bins_share_permuted": num(share(pcredit, top_bins), EXACT),
|
|
280
|
+
"neuron_top_share_same_fraction": num(share(wabs, k_neurons), EXACT),
|
|
281
|
+
"energy_top_bins_share": num(share(spec, top_bins), EXACT),
|
|
282
|
+
"energy_top_bins_share_permuted": num(share(pspec, top_bins), EXACT),
|
|
283
|
+
"meaning": "Parseval split of each neuron's Delta a over channel-rfft bins of "
|
|
284
|
+
"Delta n, weighted by |effect|; permuted = same with a random channel "
|
|
285
|
+
"order; neuron share = top neurons at the same unit fraction"}
|
|
286
|
+
mlp.append(entry)
|
|
287
|
+
if top_layer is None:
|
|
288
|
+
last = layers - 1
|
|
289
|
+
h1, h0 = port(edited, last, "h_out"), port(run, last, "h_out")
|
|
290
|
+
final = getattr(run.adapter.backbone, run.adapter.spec.final_norm)
|
|
291
|
+
else:
|
|
292
|
+
h1, h0 = port(edited, top_layer, "h"), port(run, top_layer, "h")
|
|
293
|
+
final = layer_module(run.adapter, top_layer).input_layernorm
|
|
294
|
+
eps_f = float(final.variance_epsilon)
|
|
295
|
+
rho_0 = float((h0.pow(2).mean() + eps_f) ** -0.5)
|
|
296
|
+
rho_1 = float((h1.pow(2).mean() + eps_f) ** -0.5)
|
|
297
|
+
norm_term = (rho_1 - rho_0) / rho_0 * float(c @ h1)
|
|
298
|
+
residual_gap = float(c @ (h1 - h0)) - closure_sum
|
|
299
|
+
total = closure_sum + norm_term
|
|
300
|
+
mlp_total = sum(e["captured"]["value"] for e in mlp)
|
|
301
|
+
reread_total = sum(e["effect"]["value"] for e in reread)
|
|
302
|
+
|
|
303
|
+
def share_of(x):
|
|
304
|
+
if not native_delta:
|
|
305
|
+
return {"state": "unresolved", "reason": "native delta 0"}
|
|
306
|
+
return num(x / native_delta, MEASURED)
|
|
307
|
+
return {
|
|
308
|
+
"consumer": {"native_delta": num(native_delta, MEASURED), "kind": reader.kind,
|
|
309
|
+
"text": reader.text},
|
|
310
|
+
"direct": num(direct, EXACT, "P19"),
|
|
311
|
+
"upstream": num(upstream, EXACT, "P07"),
|
|
312
|
+
"mlp": mlp, "reread": reread,
|
|
313
|
+
"norm": num(norm_term, EXACT),
|
|
314
|
+
"residual_add_rounding": num(residual_gap, MEASURED),
|
|
315
|
+
"rounding": num(native_delta - total - residual_gap, MEASURED),
|
|
316
|
+
"closure": {"sum_of_terms": num(total + residual_gap, MEASURED),
|
|
317
|
+
"gap": num(native_delta - total - residual_gap, MEASURED)},
|
|
318
|
+
"shares": {"direct": share_of(direct), "mlp": share_of(mlp_total),
|
|
319
|
+
"reread": share_of(reread_total), "norm": share_of(norm_term),
|
|
320
|
+
"meaning": "each exact term over the native delta; signed"},
|
|
321
|
+
"totals": {"mlp": num(mlp_total, MEASURED), "reread": num(reread_total, EXACT),
|
|
322
|
+
"mlp_exact": num(sum(e["exact"]["value"] for e in mlp), EXACT) if neurons
|
|
323
|
+
else {"state": "not computed", "reason": "neurons=False"},
|
|
324
|
+
"mlp_linear": num(sum(e["linear"]["value"] for e in mlp), "derived-local")
|
|
325
|
+
if neurons else {"state": "not computed", "reason": "neurons=False"}},
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def gate_switch_forecast(run: Any, edited: Any, reader: Any, *, cell_layer: int,
|
|
330
|
+
ks: tuple[int, ...] = (8, 32, 128), switch_layers: Any = None,
|
|
331
|
+
cache: dict | None = None) -> dict[str, Any]:
|
|
332
|
+
"""First-order forecasts of a cell edit's consumer change, with and without exact gate
|
|
333
|
+
switches (the ``hop_edge`` ladder's ``linear``).
|
|
334
|
+
|
|
335
|
+
Same runs as ``hop_edge`` (``run`` native, ``edited`` with the cell edit, both run to the
|
|
336
|
+
consumer's logits; ``reader`` a margin or logit ``Readout``). Per MLP layer ``l >= cell_layer``
|
|
337
|
+
at the consumer row, from the base run's ports ``r0, g0, u0, sg0`` and the weights:
|
|
338
|
+
|
|
339
|
+
* ``F1`` = ``direct + sum_l c . W_down df_lin``: ``df_lin = b0 silu'(g0) da + s0 db`` with
|
|
340
|
+
``(da, db) = (W_gate, W_up) J_RMS(r0) Delta r`` on the layer's ACTUAL input change (P14,
|
|
341
|
+
derived-local): the hop-math first-order total (direct + linear MLP).
|
|
342
|
+
* ``F2[k]`` = F1 with the ``k`` neurons per layer of largest ``|da|`` given the exact finite
|
|
343
|
+
SwiGLU of their Jacobian-predicted input: ``silu(g0 + da)(b0 + db) - s0 b0`` (no residual
|
|
344
|
+
recomputation; the inputs are still the actual ``Delta r``).
|
|
345
|
+
* ``F3[k]`` = the chained, passive version: the residual change at the row starts as the
|
|
346
|
+
cell layer's own attention write ``Delta o`` (exact, the direct term) and each layer's MLP
|
|
347
|
+
forecast (``F2``-style with ``k`` exact gates) is fed forward into the next layer's input;
|
|
348
|
+
later attention re-reads are not forecast (zero), so nothing native downstream of the edit
|
|
349
|
+
is used. ``F3`` = ``c . (Delta o_cell + sum_l Delta m_l^F3)``.
|
|
350
|
+
|
|
351
|
+
``switch_layers`` (default every layer from ``cell_layer``) restricts where the exact gates
|
|
352
|
+
are applied (elsewhere ``k = 0``). Returns the three forecasts, the native delta, the per-layer
|
|
353
|
+
``F1``/``F2`` MLP terms, and the per-layer count of base-run gate sign switches
|
|
354
|
+
(``sign(g1) != sign(g0)``) as measured on the edited run."""
|
|
355
|
+
torch = _torch()
|
|
356
|
+
from ..measure.readout import layer_module
|
|
357
|
+
|
|
358
|
+
if reader is None or not reader.scalar:
|
|
359
|
+
raise Refusal("gate_switch_forecast needs a scalar consumer (a margin or a logit)")
|
|
360
|
+
j, layers = reader.row, run.adapter.layers
|
|
361
|
+
if not 0 <= cell_layer < layers:
|
|
362
|
+
raise Refusal(f"cell layer {cell_layer} outside 0..{layers - 1}")
|
|
363
|
+
c = f64(reader.vector).reshape(-1)
|
|
364
|
+
t = reader.target
|
|
365
|
+
del cache # accepted for compatibility; nothing is cached (float64 weights per layer)
|
|
366
|
+
|
|
367
|
+
def port(r, layer, name):
|
|
368
|
+
return f64(r.read(f"t{j}.L{layer}.{name}")).reshape(-1)
|
|
369
|
+
|
|
370
|
+
def margin(r):
|
|
371
|
+
lg = r.read(f"t{j}.logits").reshape(-1)
|
|
372
|
+
return float(f64(lg[t.a]) - f64(lg[t.b])) if isinstance(t, Margin) else float(f64(lg[t.i]))
|
|
373
|
+
|
|
374
|
+
def weights(layer, module):
|
|
375
|
+
"""This layer's float64 gate/up/down (cast per layer, never kept across layers)."""
|
|
376
|
+
return (f64(module.mlp.gate_proj.weight), f64(module.mlp.up_proj.weight),
|
|
377
|
+
f64(module.mlp.down_proj.weight))
|
|
378
|
+
|
|
379
|
+
allowed = set(range(cell_layer, layers) if switch_layers is None else switch_layers)
|
|
380
|
+
native_delta = margin(edited) - margin(run)
|
|
381
|
+
d_o = port(edited, cell_layer, "o") - port(run, cell_layer, "o")
|
|
382
|
+
direct = float(c @ d_o)
|
|
383
|
+
f1, f2 = direct, {k: direct for k in ks}
|
|
384
|
+
chain = {k: d_o.clone() for k in (0, *ks)} # Delta residual (F3), per k
|
|
385
|
+
rows = []
|
|
386
|
+
for layer in range(cell_layer, layers):
|
|
387
|
+
module = layer_module(run.adapter, layer)
|
|
388
|
+
gate, up, down = weights(layer, module)
|
|
389
|
+
norm = module.post_attention_layernorm
|
|
390
|
+
gamma_l, eps = f64(norm.weight).reshape(-1), float(norm.variance_epsilon)
|
|
391
|
+
r0 = port(run, layer, "r")
|
|
392
|
+
g0, b0, s0 = port(run, layer, "g"), port(run, layer, "u"), port(run, layer, "sg")
|
|
393
|
+
rho0 = float((r0.pow(2).mean() + eps) ** -0.5)
|
|
394
|
+
cd = c @ down
|
|
395
|
+
|
|
396
|
+
def mlp_change(dr, k):
|
|
397
|
+
dn = gamma_l * (rho0 * dr - (rho0 ** 3 / dr.numel()) * float(r0 @ dr) * r0)
|
|
398
|
+
da, db = gate @ dn, up @ dn
|
|
399
|
+
df = b0 * _silu_prime(g0) * da + s0 * db
|
|
400
|
+
if k and layer in allowed:
|
|
401
|
+
top = da.abs().argsort(descending=True)[:k]
|
|
402
|
+
g1 = g0[top] + da[top]
|
|
403
|
+
df[top] = torch.nn.functional.silu(g1) * (b0[top] + db[top]) - s0[top] * b0[top]
|
|
404
|
+
return df
|
|
405
|
+
|
|
406
|
+
dr = port(edited, layer, "r") - r0
|
|
407
|
+
df1 = mlp_change(dr, 0)
|
|
408
|
+
term1 = float(cd @ df1)
|
|
409
|
+
f1 += term1
|
|
410
|
+
entry = {"layer": layer, "F1": num(term1, "derived-local", "P14"), "F2": {}}
|
|
411
|
+
for k in ks:
|
|
412
|
+
term = float(cd @ mlp_change(dr, k))
|
|
413
|
+
f2[k] += term
|
|
414
|
+
entry["F2"][str(k)] = num(term, "derived-local")
|
|
415
|
+
for k, vec in chain.items(): # re-reads of later layers: not forecast
|
|
416
|
+
chain[k] = vec + down @ mlp_change(vec, k)
|
|
417
|
+
g1n = port(edited, layer, "g")
|
|
418
|
+
entry["gate_sign_switches"] = int(((g1n > 0) != (g0 > 0)).sum())
|
|
419
|
+
entry["captured"] = num(float(c @ (port(edited, layer, "m") - port(run, layer, "m"))),
|
|
420
|
+
MEASURED)
|
|
421
|
+
rows.append(entry)
|
|
422
|
+
|
|
423
|
+
def ratio(x):
|
|
424
|
+
return num(x / native_delta, MEASURED) if native_delta else None
|
|
425
|
+
f3 = {k: float(c @ v) for k, v in chain.items()}
|
|
426
|
+
return {"consumer": {"native_delta": num(native_delta, MEASURED), "text": reader.text},
|
|
427
|
+
"direct": num(direct, EXACT, "P19"),
|
|
428
|
+
"F1": num(f1, "derived-local"), "F1_ratio": ratio(f1),
|
|
429
|
+
"F2": {str(k): num(v, "derived-local") for k, v in f2.items()},
|
|
430
|
+
"F2_ratio": {str(k): ratio(v) for k, v in f2.items()},
|
|
431
|
+
"F3": {str(k): num(v, "derived-local") for k, v in f3.items()},
|
|
432
|
+
"F3_ratio": {str(k): ratio(v) for k, v in f3.items()},
|
|
433
|
+
"layers": rows,
|
|
434
|
+
"meaning": "F1 first order on actual layer inputs (direct + linear MLP); F2[k] the k "
|
|
435
|
+
"largest |Jacobian Delta g| gates per layer exact; F3[k] chained from the "
|
|
436
|
+
"direct write, re-reads not forecast"}
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
__all__ = ["gate_switch_forecast", "hop_edge"]
|