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,776 @@
|
|
|
1
|
+
"""Per-layer explanation of a logit margin (P19) and per-port reconstruction from producers.
|
|
2
|
+
|
|
3
|
+
Operands come from one native pending-token row: every port of every layer (``engine.ports``),
|
|
4
|
+
the key/value cache after the row, the native final-norm output (``fn``) and logits. Weights are
|
|
5
|
+
read from the adapter that produced the capture. Every number carries exactly one authority label
|
|
6
|
+
(``measured | derived-exact | derived-local | bound | supplied``) and a proof ID; first-order
|
|
7
|
+
numbers are ``derived-local`` and never presented as a decomposition. Every result has a state
|
|
8
|
+
(``resolved | unresolved | refused``) with a reason when it is not resolved.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
from collections.abc import Mapping, Sequence
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from mdb.core.bounded import keep_indices, load_json, put_json
|
|
18
|
+
|
|
19
|
+
from ..numerics import finite
|
|
20
|
+
from ..numerics.labels import BOUND, EXACT, LOCAL, MEASURED, SUPPLIED, f64, f64_at, num
|
|
21
|
+
from .capture import _BOUNDARY_EDIT_PORTS, RowCapture, _as_capture, _info, _program
|
|
22
|
+
from .rounding import _head_bound, _stream_rounding_bound, _ulp
|
|
23
|
+
from .rowmodel import _llama3_rope, _readout_refusal, _rope_refusal
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _vec(x: Any) -> Any:
|
|
27
|
+
return f64(x).reshape(-1)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _final_norm(adapter: Any) -> tuple[Any, float]:
|
|
31
|
+
norm = getattr(adapter.backbone, adapter.spec.final_norm)
|
|
32
|
+
return norm.weight, float(norm.variance_epsilon)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# Rounding bounds of ``within_rounding``. residual_rounding and head are TRUE bounds with ``k = 1``
|
|
36
|
+
# (see ``_stream_rounding_bound`` and ``_head_bound``: round-to-nearest, stated premises).
|
|
37
|
+
# final_norm is still the a-priori ``k = 2`` multiple of ``||W_a - W_b||_1 ulp(max|fn|)`` (the
|
|
38
|
+
# native norm rounds twice: the normalised value, then the gain product) and is flagged
|
|
39
|
+
# ``heuristic: True``; its measured worst ratio |remainder| / (k scale) is 0.07 on the test models.
|
|
40
|
+
_K_FINAL_NORM = 2
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# Engine edit-record numbers: measurements of the realised edit; the row-sum tolerance and a scalar
|
|
44
|
+
# edit operand are supplied constants. Counts, shapes, rows and layers stay structural integers.
|
|
45
|
+
_MEASURED_RECORD_KEYS = ("cast_max_abs_error", "realised_max_abs_error", "changed_fraction",
|
|
46
|
+
"row_sum_min", "row_sum_max", "min")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _is_number(x: Any) -> bool:
|
|
50
|
+
return isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _label_record(record: Mapping[str, Any]) -> dict[str, Any]:
|
|
54
|
+
"""Copy of an engine edit record with its measured/supplied numbers as labelled numbers."""
|
|
55
|
+
out: dict[str, Any] = {}
|
|
56
|
+
for key, value in record.items():
|
|
57
|
+
if key in _MEASURED_RECORD_KEYS and _is_number(value):
|
|
58
|
+
out[key] = num(value, MEASURED, "P19")
|
|
59
|
+
elif key == "row_sum_tolerance" and _is_number(value):
|
|
60
|
+
out[key] = num(value, SUPPLIED, "P19")
|
|
61
|
+
elif key == "value" and isinstance(value, Mapping):
|
|
62
|
+
out[key] = {k: (num(v, SUPPLIED, "P19") if k == "value" and _is_number(v) else v)
|
|
63
|
+
for k, v in value.items()}
|
|
64
|
+
else:
|
|
65
|
+
out[key] = value
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _label_edits(edits: Mapping[Any, Sequence[Mapping[str, Any]]]) -> dict[Any, list[dict]]:
|
|
70
|
+
return {key: [_label_record(r) for r in records] for key, records in edits.items()}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def explain_margin(source: Any, a: int, b: int, *, first_order: bool = False,
|
|
74
|
+
units: int = 0) -> dict[str, Any]:
|
|
75
|
+
"""Per-layer signed contributions to ``M_ab = logit_a - logit_b`` at the pending token (P19).
|
|
76
|
+
|
|
77
|
+
The final residual is ``h_L = h_0 + sum_l (o_l + m_l) + edits + e``, where ``e`` collects the
|
|
78
|
+
measured rounding of every native residual add (``r - (h + o)``, ``h_out - (r + m)``) and any
|
|
79
|
+
boundary mismatch that is not an edit. With ``c = Gamma^F (W_a - W_b)^T`` and the final-norm
|
|
80
|
+
scale ``rho^F(h_L)`` evaluated once at the full measured final state (chapter 02: shared, not
|
|
81
|
+
attributed), the listed terms are ``rho^F c^T h_0`` and ``rho^F c^T o_l``, ``rho^F c^T m_l``
|
|
82
|
+
(``derived-exact``; each row also carries its scale-free ``projection`` ``c^T xi``).
|
|
83
|
+
|
|
84
|
+
A user edit at ``h`` or ``h_out`` of the explained row is a listed term
|
|
85
|
+
``L{l}.edit_{port} = rho^F c^T (edited - original)`` (the pre-edit value is the engine's
|
|
86
|
+
``controller.originals``), never part of ``residual_rounding``; with an ``h`` edit at layer 0
|
|
87
|
+
the ``embedding`` term uses the pre-edit ``h_0``. If the head has a bias, ``head_bias =
|
|
88
|
+
b_a - b_b`` is a listed term (``derived-exact``). A config logit softcap/scale that is not
|
|
89
|
+
modelled makes the result ``refused``.
|
|
90
|
+
|
|
91
|
+
Labels of the listed terms come from ``read_info`` of the port each term reads (``o`` for
|
|
92
|
+
``L{l}.attn``, ``m`` for ``L{l}.mlp``; an ``r`` edit shows up as ``o`` with ``kind:
|
|
93
|
+
realisation``; edit_h / edit_h_out from their own op): a value that is exactly a supplied
|
|
94
|
+
tensor (a pure ``replace``) is ``supplied``; add / scale / mixed ops or a realisation are
|
|
95
|
+
``derived-exact`` (``op``, ``ops``), an inexact ``r`` realisation is ``measured``; a native
|
|
96
|
+
value is ``derived-exact`` (the identity over the captured value). Every term written by an
|
|
97
|
+
edit carries ``edit`` (the edit address(es), ``t{row}.L{l}.{port}``) and ``kind``.
|
|
98
|
+
``listed_sum`` is ``derived-exact`` (exact arithmetic over its terms) with ``includes_edits``
|
|
99
|
+
(term names written by edits) and, when any term is ``supplied``, ``includes_supplied``.
|
|
100
|
+
|
|
101
|
+
Remainders: ``residual_rounding`` ``rho^F c^T e`` (measured), float64 ``unlisted`` roundoff,
|
|
102
|
+
``final_norm`` and ``head`` (measured), so listed + remainders equals the native margin to
|
|
103
|
+
float64 roundoff. They are gaps by construction, so each of the first, third and fourth also
|
|
104
|
+
carries a ``scale`` (the bound), ``k`` and ``within_rounding = |remainder| <= k * scale``:
|
|
105
|
+
|
|
106
|
+
* residual_rounding: ``scale = rho^F sum_i |c_i| sum_adds 1/2 ulp(|z_i|)`` (``bound``, ``k =
|
|
107
|
+
1``): every native add rounds once to nearest, error <= 1/2 ulp of its result per
|
|
108
|
+
coordinate, ``rho^F`` is the final-norm scale ``rho_F`` and the ulp is that of the dtype of
|
|
109
|
+
the residual ports ``h, r, h_out`` (not the logits dtype); see ``_stream_rounding_bound``;
|
|
110
|
+
* head: ``scale = gamma_d sum_{j in a,b} sum_i |W_ji fn_i|`` plus ``1/2 ulp`` of each logit per
|
|
111
|
+
output rounding (``bound``, ``k = 1``; ``gamma_d = d u / (1 - d u)``); see ``_head_bound``;
|
|
112
|
+
* final_norm: ``scale = ||W_a - W_b||_1 u(max|fn|)``, ``k = 2``, ``heuristic: True`` (an
|
|
113
|
+
a-priori multiple, not a derived bound).
|
|
114
|
+
|
|
115
|
+
``units=K`` adds ``mlp_units`` (``analysis.numerics.units.swiglu_units``): the K units of
|
|
116
|
+
largest
|
|
117
|
+
direct contribution over all layers and the K *selected but zero-valued* units (gate
|
|
118
|
+
``sg`` active, contribution through ``u`` ~0), which contribution ranking cannot list.
|
|
119
|
+
|
|
120
|
+
``first_order=True`` adds a ``derived-local`` column ``lambda_r^T o_l``,
|
|
121
|
+
``lambda_{h_{l+1}}^T m_l``, ``lambda_{h_0}^T h_0`` from ``circuit_native.consumer_gradient``
|
|
122
|
+
(model-dtype autograd adjoints at each layer input) and the P14 pullback
|
|
123
|
+
``lambda_r = (I + J_M)^T lambda_{h_{l+1}}``; those numbers do not sum to the margin. On a row
|
|
124
|
+
with edits in this row or in the run's history the column is ``{state: "refused", reason}``
|
|
125
|
+
(no numbers). Edits of earlier rows reach this row only through the cache: they are reported
|
|
126
|
+
as ``edits_history`` (with a count) and not as terms.
|
|
127
|
+
"""
|
|
128
|
+
import torch
|
|
129
|
+
|
|
130
|
+
caps = _as_capture(source)
|
|
131
|
+
adapter = caps.adapter
|
|
132
|
+
config = adapter.model.config
|
|
133
|
+
base: dict[str, Any] = {
|
|
134
|
+
"schema": "mdb-explain-margin-v1", "proof": "P19", "tokens": {"a": int(a), "b": int(b)},
|
|
135
|
+
"position": caps.position, "family": caps.family,
|
|
136
|
+
}
|
|
137
|
+
refusal = _readout_refusal(config)
|
|
138
|
+
layers = len(caps.ports)
|
|
139
|
+
originals = list(caps.originals) + [{}] * (layers - len(caps.originals))
|
|
140
|
+
if refusal is not None:
|
|
141
|
+
return {**base, "state": "refused", "reason": refusal, "edits": _label_edits(caps.edits)}
|
|
142
|
+
missing = set(caps.originals_missing)
|
|
143
|
+
program = _program(adapter)
|
|
144
|
+
ops: dict[tuple[int, str], list[str]] = {}
|
|
145
|
+
last_write: dict[tuple[int, str], Mapping[str, Any]] = {}
|
|
146
|
+
for layer, records in caps.edits.items():
|
|
147
|
+
for record in records:
|
|
148
|
+
port = program.spec(record["port"]).name
|
|
149
|
+
if port in _BOUNDARY_EDIT_PORTS:
|
|
150
|
+
ops.setdefault((layer, port), []).append(record["op"])
|
|
151
|
+
last_write[(layer, port)] = record
|
|
152
|
+
head = adapter.model.lm_head
|
|
153
|
+
weight, head_bias = head.weight, getattr(head, "bias", None)
|
|
154
|
+
gamma, eps = _final_norm(adapter)
|
|
155
|
+
delta_h: dict[int, Any] = {}
|
|
156
|
+
delta_out: dict[int, Any] = {}
|
|
157
|
+
for layer in range(layers):
|
|
158
|
+
if "h" in originals[layer]:
|
|
159
|
+
delta_h[layer] = _vec(caps.ports[layer]["h"]) - _vec(originals[layer]["h"])
|
|
160
|
+
if "h_out" in originals[layer]:
|
|
161
|
+
delta_out[layer] = _vec(caps.ports[layer]["h_out"]) - _vec(originals[layer]["h_out"])
|
|
162
|
+
embedding = _vec(caps.ports[0]["h"])
|
|
163
|
+
if 0 in delta_h:
|
|
164
|
+
embedding = embedding - delta_h[0]
|
|
165
|
+
components: dict[str, Any] = {"embedding": embedding}
|
|
166
|
+
rounding = []
|
|
167
|
+
edit_names: dict[str, tuple[int, str]] = {}
|
|
168
|
+
for layer, ports in enumerate(caps.ports):
|
|
169
|
+
h, o, r = _vec(ports["h"]), _vec(ports["o"]), _vec(ports["r"])
|
|
170
|
+
m, out = _vec(ports["m"]), _vec(ports["h_out"])
|
|
171
|
+
if layer in delta_h:
|
|
172
|
+
components[f"L{layer}.edit_h"] = delta_h[layer]
|
|
173
|
+
edit_names[f"L{layer}.edit_h"] = (layer, "h")
|
|
174
|
+
components[f"L{layer}.attn"] = o
|
|
175
|
+
components[f"L{layer}.mlp"] = m
|
|
176
|
+
if layer in delta_out:
|
|
177
|
+
components[f"L{layer}.edit_h_out"] = delta_out[layer]
|
|
178
|
+
edit_names[f"L{layer}.edit_h_out"] = (layer, "h_out")
|
|
179
|
+
boundary = 0 * h if layer + 1 == layers else _vec(caps.ports[layer + 1]["h"]) - out
|
|
180
|
+
rounding.append({"attn_add": r - (h + o), "mlp_add": out - (r + m), "boundary": boundary})
|
|
181
|
+
# The raw gaps contain the supplied edits: ``mlp_add_l`` holds the h_out edit of layer l,
|
|
182
|
+
# ``boundary_{l-1}`` holds the h edit of layer l >= 1 (the layer-0 h edit sits in no gap: the
|
|
183
|
+
# embedding term uses the pre-edit h_0). They are removed here and listed as edit terms.
|
|
184
|
+
removed = sum((-d for layer, d in delta_h.items() if layer >= 1), 0 * embedding)
|
|
185
|
+
removed = removed - sum(delta_out.values(), 0 * embedding)
|
|
186
|
+
e_total = sum(sum(item.values()) for item in rounding) + removed
|
|
187
|
+
components["residual_rounding"] = e_total
|
|
188
|
+
h_last = _vec(caps.ports[-1]["h_out"])
|
|
189
|
+
logits = caps.logits.reshape(-1)
|
|
190
|
+
native_margin = f64(logits[a]) - f64(logits[b])
|
|
191
|
+
result = finite.readout_margin(h_last, weight, gamma, eps, a, b, components=components,
|
|
192
|
+
native_margin=native_margin,
|
|
193
|
+
native_normed=_vec(caps.normed), out_bias=head_bias)
|
|
194
|
+
rho = result.extras["rho"]
|
|
195
|
+
c = result.extras["c"]
|
|
196
|
+
|
|
197
|
+
reason_missing = "pre-edit value not retained; pass recompute_originals=True"
|
|
198
|
+
|
|
199
|
+
infos = {(layer, port): _info(caps, layer, port) for layer in range(layers)
|
|
200
|
+
for port in ("o", "m")}
|
|
201
|
+
refused_ports = {key: info for key, info in infos.items() if info["state"] == "refused"}
|
|
202
|
+
|
|
203
|
+
def claim(value, authority, proof):
|
|
204
|
+
"""A labelled number, or an inspection-only record when the result is refused."""
|
|
205
|
+
if refused_ports:
|
|
206
|
+
return {"value": float(value), "authority": None, "inspection_only": True,
|
|
207
|
+
"proof": proof}
|
|
208
|
+
return num(value, authority, proof)
|
|
209
|
+
|
|
210
|
+
def term(name, layer, port):
|
|
211
|
+
entry = {"name": name, "layer": layer, "port": port}
|
|
212
|
+
authority = EXACT
|
|
213
|
+
if name in edit_names:
|
|
214
|
+
# The edit's own ops decide the label (the engine's rule): the value is ``supplied``
|
|
215
|
+
# only when the last write is an unmasked replace; an add/scale operand, a masked
|
|
216
|
+
# replace or a mix is derived-exact.
|
|
217
|
+
kinds = ops[edit_names[name]]
|
|
218
|
+
last = last_write[edit_names[name]]
|
|
219
|
+
full = "mask_count" not in last or int(last["mask_count"]) == caps.ports[
|
|
220
|
+
edit_names[name][0]][edit_names[name][1]].numel()
|
|
221
|
+
authority = SUPPLIED if last["op"] == "replace" and full else EXACT
|
|
222
|
+
entry.update(op="+".join(sorted(set(kinds))), ops=list(kinds),
|
|
223
|
+
edit=[f"t{caps.position}.L{layer}.{edit_names[name][1]}"])
|
|
224
|
+
elif layer is not None and port.split(".")[-1] in ("o", "m"):
|
|
225
|
+
# the label comes from Run.read_info of the port the term reads
|
|
226
|
+
info = infos[(layer, port.split(".")[-1])]
|
|
227
|
+
if info["state"] == "refused":
|
|
228
|
+
entry.update(state="refused", reason=info["reason"])
|
|
229
|
+
elif info["kind"] != "native":
|
|
230
|
+
authority = info["authority"]
|
|
231
|
+
entry.update(kind=info["kind"], op="+".join(sorted(set(info["ops"]))),
|
|
232
|
+
ops=list(info["ops"]),
|
|
233
|
+
edit=[f"t{caps.position}.L{layer}.{p}"
|
|
234
|
+
for p in (info["by"] or "").split(",") if p])
|
|
235
|
+
entry["value"] = claim(result.terms[name], authority, "P19")
|
|
236
|
+
entry["projection"] = claim(float(c @ components[name]), authority, "P19")
|
|
237
|
+
return entry
|
|
238
|
+
|
|
239
|
+
def shell(name, layer, port):
|
|
240
|
+
entry = {"name": name, "layer": layer, "port": port, "state": "unresolved",
|
|
241
|
+
"reason": reason_missing}
|
|
242
|
+
if (layer, port.split(".")[-1]) in ops:
|
|
243
|
+
entry["op"] = "+".join(sorted(set(ops[(layer, port.split(".")[-1])])))
|
|
244
|
+
return entry
|
|
245
|
+
|
|
246
|
+
terms = [shell("embedding", None, "L0.h") if (0, "h") in missing
|
|
247
|
+
else term("embedding", None, "L0.h")]
|
|
248
|
+
for layer in range(layers):
|
|
249
|
+
if (layer, "h") in missing:
|
|
250
|
+
terms.append(shell(f"L{layer}.edit_h", layer, f"L{layer}.h"))
|
|
251
|
+
elif f"L{layer}.edit_h" in components:
|
|
252
|
+
terms.append(term(f"L{layer}.edit_h", layer, f"L{layer}.h"))
|
|
253
|
+
terms.append(term(f"L{layer}.attn", layer, f"L{layer}.o"))
|
|
254
|
+
terms.append(term(f"L{layer}.mlp", layer, f"L{layer}.m"))
|
|
255
|
+
if (layer, "h_out") in missing:
|
|
256
|
+
terms.append(shell(f"L{layer}.edit_h_out", layer, f"L{layer}.h_out"))
|
|
257
|
+
elif f"L{layer}.edit_h_out" in components:
|
|
258
|
+
terms.append(term(f"L{layer}.edit_h_out", layer, f"L{layer}.h_out"))
|
|
259
|
+
if head_bias is not None:
|
|
260
|
+
terms.append({"name": "head_bias", "layer": None, "port": "lm_head.bias",
|
|
261
|
+
"value": claim(result.terms["head_bias"], EXACT, "P19")})
|
|
262
|
+
per_layer_rounding = [
|
|
263
|
+
{key: claim(float(rho * (c @ vec)), MEASURED, "P01") for key, vec in item.items()}
|
|
264
|
+
for item in rounding
|
|
265
|
+
]
|
|
266
|
+
# rounding bounds (see the docstring)
|
|
267
|
+
diff = f64_at(weight, a) - f64_at(weight, b)
|
|
268
|
+
stream_dtype = caps.ports[0]["h"].dtype
|
|
269
|
+
bound_rr = float(rho) * _stream_rounding_bound(caps, originals, c)
|
|
270
|
+
from ..numerics.accumulation import accumulation
|
|
271
|
+
|
|
272
|
+
head_bound, head_premises = _head_bound(caps, weight, head_bias, a, b,
|
|
273
|
+
accumulation(caps.adapter, caps.logits.dtype))
|
|
274
|
+
scale_fn = float(diff.abs().sum()) * _ulp(
|
|
275
|
+
float(_vec(caps.normed).abs().max()), float(torch.finfo(caps.normed.dtype).eps))
|
|
276
|
+
stream_premises = ["round-to-nearest", "one rounding per residual add",
|
|
277
|
+
f"residual stream dtype {stream_dtype} (dtype of h, r, h_out)"]
|
|
278
|
+
|
|
279
|
+
def bounded(entry, scale, k, formula, authority, premises=(), heuristic=False):
|
|
280
|
+
value = abs(entry["value"]["value"])
|
|
281
|
+
entry.update(scale=claim(scale, authority, "P19"), k=int(k), scale_formula=formula,
|
|
282
|
+
within_rounding=bool(value <= k * scale), heuristic=heuristic,
|
|
283
|
+
premises=list(premises))
|
|
284
|
+
return entry
|
|
285
|
+
|
|
286
|
+
remainders = [
|
|
287
|
+
bounded({"name": "residual_rounding",
|
|
288
|
+
"value": claim(result.terms["residual_rounding"], MEASURED, "P01"),
|
|
289
|
+
"per_layer": per_layer_rounding,
|
|
290
|
+
"edits_removed": claim(float(rho * (c @ removed)),
|
|
291
|
+
SUPPLIED if any("replace" in v for v in ops.values())
|
|
292
|
+
else EXACT, "P19"),
|
|
293
|
+
"meaning": "rho^F c^T (native residual-add rounding and boundary mismatch); "
|
|
294
|
+
"per_layer entries are the raw gaps (they contain supplied h/h_out "
|
|
295
|
+
"edits) and edits_removed takes those edits out, listed as edit_* "
|
|
296
|
+
"terms"},
|
|
297
|
+
bound_rr, 1, "rho^F sum_i |c_i| sum_adds 1/2 ulp(|z_i|); k = 1", BOUND,
|
|
298
|
+
stream_premises),
|
|
299
|
+
{"name": "unlisted", "value": claim(result.terms["unlisted"], EXACT, "P19"),
|
|
300
|
+
"meaning": "float64 roundoff of h_L minus the listed components"},
|
|
301
|
+
bounded({"name": "final_norm", "value": claim(result.extras["eta_final_norm"], MEASURED,
|
|
302
|
+
"P19"),
|
|
303
|
+
"meaning": "(W_a - W_b).(native fn output - rho Gamma h_L)"},
|
|
304
|
+
scale_fn, _K_FINAL_NORM, "||W_a - W_b||_1 ulp(max |fn|); k = 2", EXACT,
|
|
305
|
+
heuristic=True),
|
|
306
|
+
bounded({"name": "head", "value": claim(result.extras["eta_head"], MEASURED, "P19"),
|
|
307
|
+
"meaning": "native margin - (W_a - W_b).(native fn output) - head bias, float64"},
|
|
308
|
+
head_bound, 1, "gamma_d (sum_i |W_ai x_i| + sum_i |W_bi x_i|) + output roundings; "
|
|
309
|
+
"k = 1", BOUND, head_premises) if head_bound is not None else
|
|
310
|
+
{"name": "head", "value": claim(result.extras["eta_head"], MEASURED, "P19"),
|
|
311
|
+
"meaning": "native margin - (W_a - W_b).(native fn output) - head bias, float64",
|
|
312
|
+
"bound": {"state": "refused", "reason": head_premises[-1]}},
|
|
313
|
+
]
|
|
314
|
+
unresolved = bool(missing)
|
|
315
|
+
if unresolved:
|
|
316
|
+
# the edit sits inside the raw gaps (and, for an h edit at layer 0, in the embedding):
|
|
317
|
+
# the rounding remainder cannot be separated, so it is not reported as a number
|
|
318
|
+
remainders[0] = {"name": "residual_rounding", "state": "unresolved",
|
|
319
|
+
"reason": reason_missing}
|
|
320
|
+
listed = sum(t["value"]["value"] for t in terms if "value" in t)
|
|
321
|
+
rem = sum(r["value"]["value"] for r in remainders if "value" in r)
|
|
322
|
+
native = float(native_margin)
|
|
323
|
+
refused = bool(refused_ports)
|
|
324
|
+
reason_refused = "; ".join(f"L{layer}.{port}: {info['reason']}"
|
|
325
|
+
for (layer, port), info in sorted(refused_ports.items()))
|
|
326
|
+
edited_terms = [t["name"] for t in terms if "edit" in t]
|
|
327
|
+
supplied_terms = [t["name"] for t in terms
|
|
328
|
+
if t.get("value", {}).get("authority") == SUPPLIED]
|
|
329
|
+
listed_sum = {"state": "unresolved", "reason": reason_missing} if unresolved else claim(
|
|
330
|
+
listed, EXACT, "P19")
|
|
331
|
+
if not unresolved:
|
|
332
|
+
listed_sum["includes_edits"] = edited_terms
|
|
333
|
+
if supplied_terms:
|
|
334
|
+
listed_sum["includes_supplied"] = supplied_terms
|
|
335
|
+
out: dict[str, Any] = {
|
|
336
|
+
**base,
|
|
337
|
+
"state": "refused" if refused else "unresolved" if unresolved else "resolved",
|
|
338
|
+
"reason": reason_refused if refused else reason_missing if unresolved else None,
|
|
339
|
+
"edits": _label_edits(caps.edits),
|
|
340
|
+
"native_margin": claim(native, MEASURED, "P19"),
|
|
341
|
+
"native_dtype": str(caps.logits.dtype),
|
|
342
|
+
"float64_margin": claim(float(result.reference), EXACT, "P19"),
|
|
343
|
+
"eta": claim(native - float(result.reference), MEASURED, "P19"),
|
|
344
|
+
"rho_F": claim(float(rho), EXACT, "P19"),
|
|
345
|
+
"rho_F_note": "final-norm scale evaluated once at the full measured h_L; not attributed",
|
|
346
|
+
"terms": terms,
|
|
347
|
+
"remainders": remainders,
|
|
348
|
+
"all_within_rounding": None if unresolved or refused or any(
|
|
349
|
+
"bound" in r for r in remainders) else all(
|
|
350
|
+
r["within_rounding"] for r in remainders if "k" in r),
|
|
351
|
+
"listed_sum": listed_sum,
|
|
352
|
+
"closure": {"state": "unresolved", "reason": reason_missing} if unresolved else claim(
|
|
353
|
+
listed + rem - native, EXACT, "P19"),
|
|
354
|
+
"closure_rel": {"state": "unresolved", "reason": reason_missing} if unresolved else claim(
|
|
355
|
+
abs(listed + rem - native) / max(abs(native), 1e-300), EXACT, "P19"),
|
|
356
|
+
}
|
|
357
|
+
if caps.edits_history:
|
|
358
|
+
out["edits_history"] = {
|
|
359
|
+
"count": sum(len(v) for v in caps.edits_history.values()),
|
|
360
|
+
"entries": [{"row": row, "layer": layer, "edits": [_label_record(r) for r in v]}
|
|
361
|
+
for (row, layer), v in sorted(caps.edits_history.items())],
|
|
362
|
+
"note": "edits of earlier rows reach this row through the cache; not listed as terms",
|
|
363
|
+
}
|
|
364
|
+
if first_order:
|
|
365
|
+
out["first_order"] = _first_order(caps, a, b, result, components)
|
|
366
|
+
if units:
|
|
367
|
+
from ..numerics.units import swiglu_units
|
|
368
|
+
|
|
369
|
+
out["mlp_units"] = swiglu_units(caps, rho, c, top=units)
|
|
370
|
+
return out
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
MAX_TERMS = 64 # listed terms in a result (the record's sequence bound)
|
|
374
|
+
|
|
375
|
+
def _per_layer(result: dict[str, Any]) -> list[dict[str, Any]]:
|
|
376
|
+
for rem in result["remainders"]:
|
|
377
|
+
if rem["name"] == "residual_rounding" and "per_layer" in rem:
|
|
378
|
+
return rem["per_layer"]
|
|
379
|
+
return []
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def bound_terms(result: dict[str, Any], *, store: Any = None, run: Any = None,
|
|
383
|
+
cap: int = MAX_TERMS) -> dict[str, Any]:
|
|
384
|
+
"""Bound the lists of ``result`` that grow with the layers to ``cap`` items (in place;
|
|
385
|
+
returns ``result``): ``terms`` (two per layer plus the embedding) and the residual-rounding
|
|
386
|
+
remainder's ``per_layer`` entries.
|
|
387
|
+
|
|
388
|
+
Over the cap ``terms`` keeps the terms with the largest ``|value|`` (unresolved terms first:
|
|
389
|
+
they carry a state the reader must see), in their original order, and ``terms_summary``
|
|
390
|
+
gives ``count``, ``listed``, ``rest`` (``count`` and ``sum``, ``derived-exact``, so listed +
|
|
391
|
+
rest still adds to ``listed_sum``) and ``pointer`` to the full lists. ``per_layer`` keeps the
|
|
392
|
+
entries with the largest magnitude, each tagged with its ``layer``, and the remainder gets
|
|
393
|
+
``per_layer_count``. The full lists are JSON bytes put in ``store`` (a project
|
|
394
|
+
``LocalStore``, a tensor pointer to uint8 bytes, checked by ``sha256``) or, with no store,
|
|
395
|
+
held in memory per ``run`` (``load_terms`` / ``load_full`` resolve both). Within the cap
|
|
396
|
+
nothing changes and no summary is added.
|
|
397
|
+
"""
|
|
398
|
+
terms, per_layer = result["terms"], _per_layer(result)
|
|
399
|
+
if len(terms) <= cap and len(per_layer) <= cap:
|
|
400
|
+
return result
|
|
401
|
+
full = {"terms": terms, "per_layer": per_layer}
|
|
402
|
+
pointer = put_json(full, store=store, run=run,
|
|
403
|
+
absent_reason="no project store: the full lists are held in memory on "
|
|
404
|
+
"the run (explain.load_full), not stored")
|
|
405
|
+
|
|
406
|
+
def top(items: list[dict[str, Any]], size: float) -> list[tuple[int, dict[str, Any]]]:
|
|
407
|
+
def rank(item: dict[str, Any]) -> tuple[int, float]:
|
|
408
|
+
return (0, 0.0) if "value" not in item else (1, -abs(item["value"]["value"]))
|
|
409
|
+
|
|
410
|
+
return [(i, items[i]) for i in keep_indices(items, int(size), rank)]
|
|
411
|
+
|
|
412
|
+
keep = top(terms, cap)
|
|
413
|
+
kept = {index for index, _ in keep}
|
|
414
|
+
rest = [t for i, t in enumerate(terms) if i not in kept]
|
|
415
|
+
result["terms"] = [t for _, t in keep]
|
|
416
|
+
result["terms_summary"] = {
|
|
417
|
+
"count": len(terms), "listed": len(keep),
|
|
418
|
+
"rest": {"count": len(rest),
|
|
419
|
+
"sum": claim_sum(sum(t["value"]["value"] for t in rest if "value" in t)),
|
|
420
|
+
"unresolved": sum(1 for t in rest if "value" not in t)},
|
|
421
|
+
"pointer": pointer}
|
|
422
|
+
if len(per_layer) > cap:
|
|
423
|
+
magnitude = [{"value": {"value": max((abs(c["value"]) for c in entry.values()
|
|
424
|
+
if isinstance(c, dict) and "value" in c),
|
|
425
|
+
default=0.0)}} for entry in per_layer]
|
|
426
|
+
chosen = top(magnitude, cap)
|
|
427
|
+
for rem in result["remainders"]:
|
|
428
|
+
if rem["name"] == "residual_rounding" and "per_layer" in rem:
|
|
429
|
+
rem["per_layer"] = [{"layer": i, **per_layer[i]} for i, _ in chosen]
|
|
430
|
+
rem["per_layer_count"] = len(per_layer)
|
|
431
|
+
return result
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def claim_sum(value: float) -> dict[str, Any]:
|
|
435
|
+
return num(float(value), EXACT, "P19")
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def load_full(summary: Mapping[str, Any], *, store: Any = None, run: Any = None
|
|
439
|
+
) -> dict[str, Any]:
|
|
440
|
+
"""The full ``{"terms", "per_layer"}`` lists ``terms_summary`` points at: from ``store``
|
|
441
|
+
(stored blob, checked against the summary's ``sha256``) or from the run's in-memory copy;
|
|
442
|
+
``ValueError`` if absent or changed."""
|
|
443
|
+
return load_json(summary["pointer"], store=store, run=run)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def load_terms(summary: Mapping[str, Any], *, store: Any = None, run: Any = None
|
|
447
|
+
) -> list[dict[str, Any]]:
|
|
448
|
+
"""The full term list ``terms_summary`` points at (see ``load_full``)."""
|
|
449
|
+
return load_full(summary, store=store, run=run)["terms"]
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _layer_module(adapter: Any, layer: int) -> Any:
|
|
453
|
+
"""Decoder layer ``layer`` of a saturn ``DecoderAdapter`` (its public backbone/spec)."""
|
|
454
|
+
return getattr(adapter.backbone, adapter.spec.layers)[layer]
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def consumer_gradient(session: Any, token: int, contrast: int) -> tuple[float, Any]:
|
|
458
|
+
"""``(value, d value / d hidden)`` for ``value = logits[token] - logits[contrast]`` of the
|
|
459
|
+
pending row, from the hidden state entering the session's pending decoder layer.
|
|
460
|
+
|
|
461
|
+
The same computation as the lane function ``circuit_native.consumer_gradient`` restricted to
|
|
462
|
+
what ``_first_order`` reads (the primal and the hidden adjoint): the adapter's own layer
|
|
463
|
+
executor under autograd, the past KV fixed (detached clones of the captured cache), final norm,
|
|
464
|
+
LM head and logit softcap; no argmax/rounding derivative. Resident ``DecoderAdapter`` of a
|
|
465
|
+
family with a port program (``engine.ports.FAMILIES``), one pending token, batch one, only.
|
|
466
|
+
"""
|
|
467
|
+
import torch
|
|
468
|
+
from saturn.adapters.decoder import DecoderAdapter
|
|
469
|
+
|
|
470
|
+
from mdb.engine.ports import PROGRAMS
|
|
471
|
+
|
|
472
|
+
adapter = session.adapter
|
|
473
|
+
if (not isinstance(adapter, DecoderAdapter)
|
|
474
|
+
or adapter.spec.model_type not in PROGRAMS
|
|
475
|
+
or adapter.execution.get("residency", "resident") != "resident"):
|
|
476
|
+
raise ValueError("native circuit expansion supports a resident public DecoderAdapter "
|
|
477
|
+
f"of a port-program family ({', '.join(PROGRAMS)})")
|
|
478
|
+
adapter.validate_execution()
|
|
479
|
+
state = session.capture(retain=False).payload
|
|
480
|
+
index = state["layer"]
|
|
481
|
+
if state["phase"] != "layer" or not 0 <= index < adapter.layers:
|
|
482
|
+
raise ValueError("select hidden at a pending decoder layer before expanding native "
|
|
483
|
+
"attention/MLP")
|
|
484
|
+
hidden = session.read("hidden")
|
|
485
|
+
if hidden is None or hidden.shape[:2] != (1, 1):
|
|
486
|
+
raise ValueError("native circuit expansion requires one pending token and batch one")
|
|
487
|
+
if max(token, contrast) >= adapter.model.config.vocab_size:
|
|
488
|
+
raise ValueError("consumer token is outside native vocabulary")
|
|
489
|
+
with torch.inference_mode(False), torch.enable_grad():
|
|
490
|
+
hidden = hidden.detach().clone().requires_grad_(True)
|
|
491
|
+
keys = [x.detach().clone() for x in state["keys"]]
|
|
492
|
+
values = [x.detach().clone() for x in state["values"]]
|
|
493
|
+
cache = adapter.native_cache(keys, values, index) # private clones: by reference is safe
|
|
494
|
+
position = session.read("tokens").shape[-1] - 1
|
|
495
|
+
out = hidden
|
|
496
|
+
for layer in range(index, adapter.layers):
|
|
497
|
+
out = adapter.run_layer(layer, out, cache, position)
|
|
498
|
+
logits = adapter.apply_logit_softcap(
|
|
499
|
+
adapter.model.lm_head(getattr(adapter.backbone, adapter.spec.final_norm)(out))
|
|
500
|
+
)[:, -1]
|
|
501
|
+
target = logits[0, token] - logits[0, contrast]
|
|
502
|
+
(gradient,) = torch.autograd.grad(target, [hidden])
|
|
503
|
+
value = float(target.detach())
|
|
504
|
+
gradient = gradient.detach().clone()
|
|
505
|
+
adapter.validate_execution()
|
|
506
|
+
return value, gradient
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _first_order(caps: RowCapture, a: int, b: int, result: Any,
|
|
510
|
+
components: Mapping[str, Any]) -> dict[str, Any]:
|
|
511
|
+
if caps.edits or caps.edits_history:
|
|
512
|
+
where = []
|
|
513
|
+
if caps.edits:
|
|
514
|
+
where.append(f"edits in this row at layers {sorted(caps.edits)}")
|
|
515
|
+
if caps.edits_history:
|
|
516
|
+
where.append("edits in earlier rows (history) at (row, layer) "
|
|
517
|
+
f"{sorted(caps.edits_history)}")
|
|
518
|
+
return {"state": "refused", "authority": None,
|
|
519
|
+
"reason": "first-order column needs an unedited row: consumer_gradient replays "
|
|
520
|
+
"the native suffix without port edits; " + "; ".join(where)}
|
|
521
|
+
adapter = caps.adapter
|
|
522
|
+
layers = len(caps.ports)
|
|
523
|
+
adjoints, primals = [], []
|
|
524
|
+
# One prefill, one layer transition per layer: consumer_gradient only reads the session
|
|
525
|
+
# (a capture it does not retain and cloned reads), so it stays at the same state.
|
|
526
|
+
session = adapter.session(list(caps.tokens))
|
|
527
|
+
session.continue_()
|
|
528
|
+
for layer in range(layers):
|
|
529
|
+
if layer:
|
|
530
|
+
session.continue_()
|
|
531
|
+
value, grad = consumer_gradient(session, int(a), int(b))
|
|
532
|
+
adjoints.append(_vec(grad))
|
|
533
|
+
primals.append(value)
|
|
534
|
+
adjoints.append(result.extras["gradient"])
|
|
535
|
+
rows = [{"name": "embedding", "value": num(float(adjoints[0] @ components["embedding"]),
|
|
536
|
+
LOCAL, "P19")}]
|
|
537
|
+
for layer, ports in enumerate(caps.ports):
|
|
538
|
+
mlp = _layer_module(adapter, layer).mlp
|
|
539
|
+
norm = _layer_module(adapter, layer).post_attention_layernorm
|
|
540
|
+
lam_out = adjoints[layer + 1]
|
|
541
|
+
lam_r = finite.mlp_pullback(lam_out, _vec(ports["r"]), mlp.gate_proj.weight,
|
|
542
|
+
mlp.up_proj.weight, mlp.down_proj.weight, norm.weight,
|
|
543
|
+
float(norm.variance_epsilon)).total
|
|
544
|
+
rows.append({"name": f"L{layer}.attn", "value": num(
|
|
545
|
+
float(lam_r @ components[f"L{layer}.attn"]), LOCAL, "P14")})
|
|
546
|
+
rows.append({"name": f"L{layer}.mlp", "value": num(
|
|
547
|
+
float(lam_out @ components[f"L{layer}.mlp"]), LOCAL, "P14")})
|
|
548
|
+
logits = caps.logits.reshape(-1)
|
|
549
|
+
native = float(f64(logits[a]) - f64(logits[b]))
|
|
550
|
+
return {
|
|
551
|
+
"state": "resolved",
|
|
552
|
+
"reason": None,
|
|
553
|
+
"authority": LOCAL,
|
|
554
|
+
"rows": rows,
|
|
555
|
+
"adjoint_source": "consumer_gradient (model dtype autograd, fixed past "
|
|
556
|
+
"KV) at each layer input; P14 float64 pullback through each MLP; P19 "
|
|
557
|
+
"float64 readout gradient for the last layer",
|
|
558
|
+
"consumer_primal_minus_native": [num(p - native, MEASURED, "P19") for p in primals],
|
|
559
|
+
"note": "first-order products lambda^T xi; they are not a decomposition of the margin",
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
_PRODUCERS: dict[str, tuple[str, ...]] = {
|
|
564
|
+
"a": ("h",), "q": ("a",), "k": ("a",), "v": ("a",), "qn": ("q",), "kn": ("k",),
|
|
565
|
+
"s": ("qr", "kr"), "p": ("s",), "A": ("p", "values"), "o": ("A",), "r": ("h", "o"),
|
|
566
|
+
"n": ("r",), "g": ("n",), "u": ("n",), "sg": ("g",), "f": ("sg", "u"), "m": ("f",),
|
|
567
|
+
"h_out": ("r", "m"),
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def _theta(config: Any) -> float:
|
|
572
|
+
rope = getattr(config, "rope_parameters", None)
|
|
573
|
+
if isinstance(rope, Mapping) and "rope_theta" in rope:
|
|
574
|
+
return float(rope["rope_theta"])
|
|
575
|
+
return float(config.rope_theta)
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def explain_port(source: Any, layer: int, port: str) -> dict[str, Any]:
|
|
579
|
+
"""Reconstruct one captured port from its producers by the identity that defines it.
|
|
580
|
+
|
|
581
|
+
Returns the port program's operator and declared proofs, the producers used, the identity
|
|
582
|
+
(proof ID, function, kind), the float64 reconstruction, the native capture and the measured
|
|
583
|
+
remainder ``eta = native - reconstruction``. ``kr`` is reconstructed for the pending row only
|
|
584
|
+
(cached pre-RoPE keys are not captured); ``h`` at layer 0 is the embedding lookup.
|
|
585
|
+
|
|
586
|
+
``eta`` is the native output minus the float64 identity on the captured operands, so it exists
|
|
587
|
+
only for a value the native code produced. A native value carries ``eta_max_abs`` /
|
|
588
|
+
``eta_rel`` (``measured`` against the native capture, ``against: "native"``). The engine's ``s``
|
|
589
|
+
capture is a replica (not a native tensor): ``kind`` of its ``read_info`` is ``replica`` and its
|
|
590
|
+
``eta`` is ``derived-exact`` with ``against: "replica"`` in BOTH ``eta_max_abs`` and
|
|
591
|
+
``result.summary()``; the same holds for ``p``/``A`` under an ``s``/``p`` edit. A replica whose
|
|
592
|
+
check failed is ``state: "refused"``; one whose check has not run stays resolved with
|
|
593
|
+
``replica_equal: None`` and a note. A value written by an edit or a realisation
|
|
594
|
+
(``value_kind in {edit, realisation}``) has NO ``eta``: it returns ``authority`` (from
|
|
595
|
+
``read_info``), ``edit`` (``by``, ``ops``, ``kind``), ``edit_delta_max_abs`` (``measured``: the
|
|
596
|
+
edit's displacement from the identity, never a remainder) and, when the pre-edit original is
|
|
597
|
+
held, ``original.eta_max_abs`` (the native remainder of the original). ``under_edits`` lists the
|
|
598
|
+
edits that fired before the value in program order. ``qr``/``kr`` under llama3 RoPE use its
|
|
599
|
+
scaled frequencies; under a RoPE the identity does not model (a type other than default and
|
|
600
|
+
llama3, partial rotary width) they return ``state: "refused"`` with the reason instead of a
|
|
601
|
+
large ``eta``. ``schema``, ``state``, ``reason``, ``against``, ``value_kind``,
|
|
602
|
+
``under_edits`` are always present.
|
|
603
|
+
"""
|
|
604
|
+
from mdb.engine.ports import program_for
|
|
605
|
+
|
|
606
|
+
caps = _as_capture(source)
|
|
607
|
+
adapter = caps.adapter
|
|
608
|
+
spec_program = program_for(adapter)
|
|
609
|
+
spec = spec_program.spec(port)
|
|
610
|
+
module = _layer_module(adapter, layer)
|
|
611
|
+
attn = module.self_attn
|
|
612
|
+
ports = caps.ports[layer]
|
|
613
|
+
heads, kv_heads, d_h = adapter.num_heads, adapter.num_kv_heads, adapter.head_dim
|
|
614
|
+
t = caps.position
|
|
615
|
+
kappa = finite.gqa_kappa(heads, kv_heads)
|
|
616
|
+
q_src, k_src = spec_program.spec("qr").inputs[0], spec_program.spec("kr").inputs[0]
|
|
617
|
+
notes: list[str] = []
|
|
618
|
+
producers = _PRODUCERS.get(port, ())
|
|
619
|
+
native = ports[port]
|
|
620
|
+
if spec.name in ("qr", "kr"):
|
|
621
|
+
refusal = _rope_refusal(adapter.model.config)
|
|
622
|
+
if refusal is not None:
|
|
623
|
+
return {"schema": "mdb-explain-port-v1", "layer": layer, "port": spec.name,
|
|
624
|
+
"operator": spec.operator, "proofs_declared": list(spec.proofs),
|
|
625
|
+
"proof": "P04", "function": "rope_rotate", "state": "refused",
|
|
626
|
+
"reason": refusal, "against": "native"}
|
|
627
|
+
|
|
628
|
+
def norm(x, mod, nat, width=None):
|
|
629
|
+
x = f64(x) if width is None else f64(x).reshape(-1, width)
|
|
630
|
+
nat = nat if width is None else nat.reshape(-1, width)
|
|
631
|
+
return finite.rms_norm(x.reshape(-1, x.shape[-1]), mod.weight, float(mod.variance_epsilon),
|
|
632
|
+
native=nat.reshape(-1, nat.shape[-1]))
|
|
633
|
+
|
|
634
|
+
def lin(x, mod, nat, proof="P04"):
|
|
635
|
+
return finite.affine(_vec(x), mod.weight, mod.bias, native=nat.reshape(-1), proof=proof)
|
|
636
|
+
|
|
637
|
+
if port == "h":
|
|
638
|
+
if layer == 0:
|
|
639
|
+
producers = ("embedding", "token")
|
|
640
|
+
res = finite.embedding_lookup(getattr(adapter.backbone, adapter.spec.embed).weight,
|
|
641
|
+
caps.tokens[-1], native=native.reshape(-1))
|
|
642
|
+
else:
|
|
643
|
+
producers = (f"L{layer - 1}.h_out",)
|
|
644
|
+
prev = caps.ports[layer - 1]["h_out"]
|
|
645
|
+
res = finite.residual_add(_vec(prev), 0 * _vec(prev), native=native.reshape(-1))
|
|
646
|
+
notes.append("layer boundary: h_l equals the previous layer output")
|
|
647
|
+
elif port == "a":
|
|
648
|
+
res = norm(ports["h"], module.input_layernorm, native)
|
|
649
|
+
elif port in ("q", "k", "v"):
|
|
650
|
+
res = lin(ports["a"], getattr(attn, f"{port}_proj"), native)
|
|
651
|
+
elif port in ("qn", "kn"):
|
|
652
|
+
source_port = port[0]
|
|
653
|
+
res = norm(ports[source_port], getattr(attn, f"{source_port}_norm"), native, width=d_h)
|
|
654
|
+
elif port == "qr":
|
|
655
|
+
producers = (q_src,)
|
|
656
|
+
qbar = f64(ports[producers[0]]).reshape(heads, d_h)
|
|
657
|
+
res = finite.rope_rotate(qbar, t, _theta(adapter.model.config), native=native[0, :, 0, :],
|
|
658
|
+
llama3=_llama3_rope(adapter.model.config))
|
|
659
|
+
elif port == "kr":
|
|
660
|
+
producers = (k_src,)
|
|
661
|
+
kbar = f64(ports[producers[0]]).reshape(kv_heads, d_h)
|
|
662
|
+
res = finite.rope_rotate(kbar, t, _theta(adapter.model.config), native=native[0, :, t, :],
|
|
663
|
+
llama3=_llama3_rope(adapter.model.config))
|
|
664
|
+
notes.append("pending row only; cached rows' pre-RoPE keys are not captured")
|
|
665
|
+
elif port == "s":
|
|
666
|
+
keys = ports["kr"][0][kappa]
|
|
667
|
+
res = finite.scores(f64(ports["qr"][0, :, 0, :]), keys, scaling=float(attn.scaling),
|
|
668
|
+
native=native[0, :, 0, :])
|
|
669
|
+
notes.append("single pending row: no attention mask, every cached source visible")
|
|
670
|
+
elif port == "p":
|
|
671
|
+
res = finite.softmax(ports["s"][0, :, 0, :], native=native[0, :, 0, :])
|
|
672
|
+
elif port == "A":
|
|
673
|
+
values = caps.values[layer][0][kappa]
|
|
674
|
+
res = finite.transport(ports["p"][0, :, 0, :], values, native=native.reshape(heads, d_h))
|
|
675
|
+
pending = f64(caps.values[layer][0, :, t, :]).reshape(-1)
|
|
676
|
+
notes.append(f"value cache row t vs captured v max abs diff "
|
|
677
|
+
f"{float((pending - _vec(ports['v'])).abs().max()):.3g}")
|
|
678
|
+
elif port == "o":
|
|
679
|
+
res = finite.head_write(_vec(ports["A"]), attn.o_proj.weight, attn.o_proj.bias,
|
|
680
|
+
native=native.reshape(-1))
|
|
681
|
+
elif port == "r":
|
|
682
|
+
res = finite.residual_add(_vec(ports["h"]), _vec(ports["o"]), native=native.reshape(-1))
|
|
683
|
+
elif port == "n":
|
|
684
|
+
res = norm(ports["r"], module.post_attention_layernorm, native)
|
|
685
|
+
elif port in ("g", "u"):
|
|
686
|
+
mod = module.mlp.gate_proj if port == "g" else module.mlp.up_proj
|
|
687
|
+
res = lin(ports["n"], mod, native, proof="P10")
|
|
688
|
+
elif port == "sg":
|
|
689
|
+
res = finite.swiglu_gate(_vec(ports["g"]), native=native.reshape(-1))
|
|
690
|
+
elif port == "f":
|
|
691
|
+
res = finite.swiglu_product(_vec(ports["sg"]), _vec(ports["u"]),
|
|
692
|
+
native=native.reshape(-1))
|
|
693
|
+
elif port == "m":
|
|
694
|
+
res = lin(ports["f"], module.mlp.down_proj, native, proof="P10")
|
|
695
|
+
elif port == "h_out":
|
|
696
|
+
res = finite.residual_add(_vec(ports["r"]), _vec(ports["m"]), native=native.reshape(-1))
|
|
697
|
+
else:
|
|
698
|
+
raise ValueError(f"no identity registered for port {port!r}")
|
|
699
|
+
entry = finite.IDENTITIES.get(res.proof, {}).get("functions", {}).get(res.name, {})
|
|
700
|
+
info = _info(caps, layer, spec.name)
|
|
701
|
+
out: dict[str, Any] = {
|
|
702
|
+
"schema": "mdb-explain-port-v1",
|
|
703
|
+
"layer": layer,
|
|
704
|
+
"port": spec.name,
|
|
705
|
+
"operator": spec.operator,
|
|
706
|
+
"proofs_declared": list(spec.proofs),
|
|
707
|
+
"proof": res.proof,
|
|
708
|
+
"function": res.name,
|
|
709
|
+
"kind": res.kind,
|
|
710
|
+
"section": entry.get("section"),
|
|
711
|
+
"producers": list(producers),
|
|
712
|
+
"reconstruction": res.total,
|
|
713
|
+
"native": native,
|
|
714
|
+
"native_dtype": str(native.dtype),
|
|
715
|
+
"value_kind": info["kind"],
|
|
716
|
+
"under_edits": [dict(e) for e in info["upstream_edits"]],
|
|
717
|
+
"state": "resolved",
|
|
718
|
+
"reason": None,
|
|
719
|
+
"against": "native",
|
|
720
|
+
"notes": notes,
|
|
721
|
+
"result": res,
|
|
722
|
+
}
|
|
723
|
+
if info["state"] == "refused":
|
|
724
|
+
# the value rests on a replica whose check failed: no claim about it
|
|
725
|
+
res.native = None
|
|
726
|
+
out.update(state="refused", reason=info["reason"], against="replica",
|
|
727
|
+
replica_equal=info["replica_equal"], replica_checked=info["replica_checked"])
|
|
728
|
+
return out
|
|
729
|
+
target = res.reference if res.reference is not None else res.total
|
|
730
|
+
|
|
731
|
+
def gap(value, against=None):
|
|
732
|
+
against = f64(target) if against is None else against
|
|
733
|
+
return float((f64(value).reshape(f64(res.native).shape) - against).abs().max())
|
|
734
|
+
|
|
735
|
+
if info["kind"] in ("edit", "realisation"):
|
|
736
|
+
# An edit or a realisation wrote this value: it is not a native output, so ``eta`` (native
|
|
737
|
+
# minus the identity on the captured operands) does not exist for it. The displacement of
|
|
738
|
+
# the written value from the identity is the edit's, not a rounding remainder.
|
|
739
|
+
delta = gap(native)
|
|
740
|
+
original = caps.originals[layer].get(spec.name) if layer < len(caps.originals) else None
|
|
741
|
+
out.update(
|
|
742
|
+
authority=info["authority"],
|
|
743
|
+
edit={"by": info["by"], "ops": list(info["ops"]), "kind": info["kind"]},
|
|
744
|
+
edit_delta_max_abs=num(delta, MEASURED, res.proof),
|
|
745
|
+
edit_delta_meaning="max |written value - identity on the captured operands|: the "
|
|
746
|
+
"displacement the edit or realisation produced, not a remainder",
|
|
747
|
+
)
|
|
748
|
+
against = None
|
|
749
|
+
if spec.name == "r" and original is not None:
|
|
750
|
+
# r's operand o is itself the realisation of the r edit: the original r is compared
|
|
751
|
+
# with the add of the ORIGINAL operands (h + pre-edit o), or not at all
|
|
752
|
+
held = caps.originals[layer].get("o")
|
|
753
|
+
against = None if held is None else f64(ports["h"]).reshape(-1) + _vec(held)
|
|
754
|
+
original = None if held is None else original
|
|
755
|
+
if original is not None:
|
|
756
|
+
out["original"] = {"eta_max_abs": num(gap(original, against), MEASURED, res.proof),
|
|
757
|
+
"meaning": "native output of the pre-edit value minus the identity "
|
|
758
|
+
"on the captured operands (the remainder eta)"}
|
|
759
|
+
else:
|
|
760
|
+
notes.append("pre-edit original not retained: no native eta for this value "
|
|
761
|
+
"(captures_from_run(recompute_originals=True) rebuilds it)")
|
|
762
|
+
res.native = None # the native-remainder fields of summary() are not defined here
|
|
763
|
+
notes.append("value written by an edit/realisation: no eta; see edit_delta_max_abs")
|
|
764
|
+
return out
|
|
765
|
+
eta_authority = EXACT if info["kind"] == "replica" else MEASURED
|
|
766
|
+
if info["kind"] == "replica":
|
|
767
|
+
out.update(against="replica", replica_equal=info["replica_equal"],
|
|
768
|
+
replica_checked=info["replica_checked"])
|
|
769
|
+
notes.append(f"{spec.name} is a replica computed from captured operands (for s: qr, kr), "
|
|
770
|
+
"not a native tensor: its comparison against native is derived-exact")
|
|
771
|
+
if info["replica_equal"] is None:
|
|
772
|
+
notes.append("replica check not run at this cursor: the comparison is unchecked")
|
|
773
|
+
res.eta_authority = eta_authority
|
|
774
|
+
out["eta_max_abs"] = num(res.eta_max_abs, eta_authority, res.proof)
|
|
775
|
+
out["eta_rel"] = num(res.eta_rel, eta_authority, res.proof)
|
|
776
|
+
return out
|