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,806 @@
|
|
|
1
|
+
"""Branches: named native branches from one checkpoint, all measured at one consumer against one
|
|
2
|
+
floor.
|
|
3
|
+
|
|
4
|
+
Eight experiment drivers wrote the same loop by hand: checkpoint, edit, run to the logits, read
|
|
5
|
+
the margin, restore, keyed by an arm label, with a matched-norm null drawn differently in four of
|
|
6
|
+
them and the floor attached by hand in every one. ``Branches`` is that loop as a debugger object:
|
|
7
|
+
|
|
8
|
+
br = Branches(run, Margin(last, a, b), at=f"t{last}.L20.h")
|
|
9
|
+
br.add("R1", [edit(f"t{last}.L20.v[kv6]", donor.ref(f"t{last}.L20.v[kv6]"))])
|
|
10
|
+
br.add("R1-held", br.arm("R1").edits, holds=[f"t@last.L>20.p"])
|
|
11
|
+
br.add_null("random", like="R1", seed=0) # matched-norm random change, same address
|
|
12
|
+
br.add_null("self", like="R1") # self-patch: the native value back (dM = 0)
|
|
13
|
+
br.add_null("answer", like="R1") # matched norm along the answer direction
|
|
14
|
+
br.run() # stepped (mdb-stepped kernel path)
|
|
15
|
+
br.table(); br.compare("R1", "R1-held"); br.seal(); br.restore()
|
|
16
|
+
|
|
17
|
+
Semantics (a debugger's): ``branch`` (the checkpoint taken at ``at``), ``add``/``add_null``
|
|
18
|
+
(named arms), ``run`` (each arm: restore, holds on, edits staged at their layers, run to the
|
|
19
|
+
consumer's logits, read, holds released, restore), ``compare`` (two arms' difference, in floors),
|
|
20
|
+
``restore`` (the run back at the branch point). Every arm records: its edits' manifests (origins
|
|
21
|
+
included: a ``ValueRef`` from another run or a ``Pool`` keeps its pointer), its holds, ``M``,
|
|
22
|
+
``dM = M - M0``, the argmax, ``|dM|`` in floors with the stability band (``stability.stability``:
|
|
23
|
+
stable above ``k`` floors, else kernel-sensitive; ``k`` from a calibration, the caller, or 4) and
|
|
24
|
+
the kernel path it was measured on.
|
|
25
|
+
|
|
26
|
+
The floor is ONE number for every arm: ``floor_spacings`` (2) x the dtype
|
|
27
|
+
spacing at the base margin's larger ``|logit|`` (``verdict.margin_floor``) plus ``extra_floor``
|
|
28
|
+
(a measured kernel-path delta), or the caller's ``floor``. A callable consumer gives no
|
|
29
|
+
magnitude: pass ``floor`` or the arms carry no floor columns.
|
|
30
|
+
|
|
31
|
+
Built-in nulls (each derived from an arm ``like`` and recorded with its rule):
|
|
32
|
+
|
|
33
|
+
* ``random``: at every address the ``like`` arm edits, an ``add`` of a seeded Gaussian over the
|
|
34
|
+
edited elements, rescaled to the norm of the change the arm makes there (``|requested -
|
|
35
|
+
native|``, float64 on the reference run's native value), cast once to the model dtype.
|
|
36
|
+
* ``self``: every edited element replaced by its own native value (the self-patch): ``dM`` must
|
|
37
|
+
be 0 on the stepped path; a nonzero ``dM`` measures the kernel path, not the model.
|
|
38
|
+
* ``answer``: residual-stream ports only (``h``, ``o``, ``r``, ``m``, ``h_out``): the change's norm
|
|
39
|
+
written along the consumer's readout direction (``reads.readout(...).vector``, the
|
|
40
|
+
answer-minus-foil unembedding through the final norm), signed like the change's own projection:
|
|
41
|
+
the direct-effect ceiling of a write of that size (the answer-token null).
|
|
42
|
+
|
|
43
|
+
``batched`` measures arms in one batched forward per chunk (``sweep.cell_sweep``; kernel path
|
|
44
|
+
``batched``, with its measured null-vs-stepped delta added to the floor of those arms; twice the
|
|
45
|
+
delta: a margin is a difference of two logits): state-cell arms (``replace`` of whole cells) and
|
|
46
|
+
port arms at the pending row's native-module ports (``a q k v n g sg u f A o m``; any op, selector
|
|
47
|
+
or mask, applied per arm by a forward hook with the stepped run's own arithmetic). A batched
|
|
48
|
+
forward is a different kernel path from the stepped one, and it was measured that
|
|
49
|
+
this only changes verdicts for effects within about 4 floors (0/214 above), so the default
|
|
50
|
+
``recheck="band"`` re-measures stepped only the arms that could flip: ``1/k <= |dM| / floor <= k``
|
|
51
|
+
(``k`` = the stability margin, 4 unless calibrated); arms above ``k`` floors (stable) or below
|
|
52
|
+
``1/k`` (clearly null) keep their batched row, which says why (``recheck.why``). ``recheck=0``
|
|
53
|
+
none, ``"all"`` every arm, an ``int`` the ``k`` arms of largest ``|dM|``.
|
|
54
|
+
|
|
55
|
+
``probes``: named callables ``probe(run) -> number | list`` read
|
|
56
|
+
on every stepped arm (and the base) after the consumer's logits are computed and before the
|
|
57
|
+
restore, so an arm can report a value OTHER than the consumer (a cache cell's projection, a
|
|
58
|
+
port's norm) from the branch it ran; stored per row as ``probes`` (measured). Batched arms carry
|
|
59
|
+
no probes (their forward is not a ``Run``).
|
|
60
|
+
|
|
61
|
+
``interchange`` (subspace.py) builds on this object.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
from __future__ import annotations
|
|
65
|
+
|
|
66
|
+
import time
|
|
67
|
+
from dataclasses import dataclass, field
|
|
68
|
+
from typing import Any, Sequence
|
|
69
|
+
|
|
70
|
+
from mdb.core.kinds import BRANCHES, procedure # noqa: F401 (declares the kind)
|
|
71
|
+
from mdb.core.records import seal_record
|
|
72
|
+
|
|
73
|
+
from ..numerics.labels import EXACT, MEASURED, SUPPLIED, f64, num
|
|
74
|
+
from ..numerics.stability import MDB_STEPPED, stability
|
|
75
|
+
from ..numerics.verdict import magnitude, margin_floor, spacing
|
|
76
|
+
from ..predict.consumers import Logit, Margin, Refusal, run_session_id
|
|
77
|
+
|
|
78
|
+
SCHEMA = "mdb-branches-v1"
|
|
79
|
+
NULL_KINDS = ("random", "self", "answer")
|
|
80
|
+
RESIDUAL_PORTS = ("h", "o", "r", "m", "h_out")
|
|
81
|
+
_CAP = 64
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _torch():
|
|
85
|
+
import torch
|
|
86
|
+
|
|
87
|
+
return torch
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class Edit:
|
|
92
|
+
"""One edit of an arm: ``target`` (an address, selector allowed; ``cache.L<l>.k|v[...]`` for
|
|
93
|
+
a state cell), ``value`` (number, tensor or ``engine.refs.ValueRef``), ``op``, an optional
|
|
94
|
+
bool ``mask`` (ports only), ``dose`` (cell ``mix``) and ``origin`` (overrides a ref's)."""
|
|
95
|
+
|
|
96
|
+
target: str
|
|
97
|
+
value: Any
|
|
98
|
+
op: str = "replace"
|
|
99
|
+
mask: Any = None
|
|
100
|
+
dose: float | None = None
|
|
101
|
+
origin: dict[str, Any] | None = None
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def cell(self) -> bool:
|
|
105
|
+
return self.target.strip().startswith("cache.")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def edit(target: str, value: Any, op: str = "replace", **options: Any) -> Edit:
|
|
109
|
+
return Edit(target, value, op, **options)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@dataclass
|
|
113
|
+
class Arm:
|
|
114
|
+
name: str
|
|
115
|
+
kind: str = "edit"
|
|
116
|
+
edits: list[Edit] = field(default_factory=list)
|
|
117
|
+
holds: list[Any] = field(default_factory=list) # "ADDR" (source: reference) or (ADDR, run)
|
|
118
|
+
final_scale: str = "native" # "held": final RMSNorm scale held too
|
|
119
|
+
like: str | None = None
|
|
120
|
+
seed: int | None = None
|
|
121
|
+
rule: str | None = None
|
|
122
|
+
result: dict[str, Any] | None = None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# the verdict fields of an arm row: a batched arm re-measured stepped takes the stepped ones and
|
|
126
|
+
# keeps the batched ones under ``batched``
|
|
127
|
+
_VERDICT = ("M", "dM", "argmax", "magnitude", "floor", "effect_floors", "above_floor", "stability",
|
|
128
|
+
"k", "k_source", "kernel_path", "seconds")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _safe(value: Any, authority: str) -> Any:
|
|
132
|
+
"""A manifest made record-safe: floats (and negative ints) labelled, long lists capped."""
|
|
133
|
+
import numbers
|
|
134
|
+
|
|
135
|
+
if isinstance(value, bool) or value is None or isinstance(value, str):
|
|
136
|
+
return value
|
|
137
|
+
if isinstance(value, numbers.Integral):
|
|
138
|
+
return int(value) if value >= 0 else num(float(value), authority)
|
|
139
|
+
if isinstance(value, numbers.Real):
|
|
140
|
+
return num(float(value), authority)
|
|
141
|
+
if isinstance(value, dict):
|
|
142
|
+
if set(value) >= {"value", "authority"} and isinstance(value.get("authority"), str):
|
|
143
|
+
return value
|
|
144
|
+
return {str(k): _safe(v, authority) for k, v in value.items()}
|
|
145
|
+
if isinstance(value, (list, tuple)):
|
|
146
|
+
return [_safe(v, authority) for v in list(value)[:_CAP]]
|
|
147
|
+
return str(value)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
_KEEP = ("port", "op", "value", "selection", "mask_count", "origin", "row", "layer",
|
|
151
|
+
"realised_exact", "realised_max_abs_error", "cell")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _keep(entry: dict[str, Any]) -> dict[str, Any]:
|
|
155
|
+
"""The fields of a committed edit/cell record a branches record keeps."""
|
|
156
|
+
entry = {k: v for k, v in entry.items() if k in _KEEP}
|
|
157
|
+
if isinstance(entry.get("realised_max_abs_error"), float):
|
|
158
|
+
entry["realised_max_abs_error"] = num(entry["realised_max_abs_error"], MEASURED)
|
|
159
|
+
return entry
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class Branches:
|
|
163
|
+
"""Named native branches of ``run`` from one checkpoint (module docstring)."""
|
|
164
|
+
|
|
165
|
+
def __init__(self, run: Any, consumer: Any, *, at: str | None = None,
|
|
166
|
+
name: str = "branches", row: int | None = None, floor: float | None = None,
|
|
167
|
+
floor_spacings: float = 2.0, extra_floor: float = 0.0,
|
|
168
|
+
calibration: Any = None, stable_floors: float | None = None,
|
|
169
|
+
kernel_path: str = MDB_STEPPED, reference: Any = None,
|
|
170
|
+
probes: dict[str, Any] | None = None):
|
|
171
|
+
self.debuggee, self.consumer, self.name = run, consumer, name
|
|
172
|
+
self.probes = dict(probes or {})
|
|
173
|
+
self.row = consumer.row if hasattr(consumer, "row") else row
|
|
174
|
+
if self.row is None:
|
|
175
|
+
raise Refusal("a callable consumer needs row= (the logits row it reads)")
|
|
176
|
+
if at is not None:
|
|
177
|
+
here, there = run.parse(run.where), run.parse(at)
|
|
178
|
+
if there > here:
|
|
179
|
+
run.until(at)
|
|
180
|
+
elif there < here:
|
|
181
|
+
run.rewind(at)
|
|
182
|
+
self.at = run.where
|
|
183
|
+
self.checkpoint = run.checkpoint(f"{name}:at")
|
|
184
|
+
# edits and cells committed on the path BEFORE the branch point (an arm's own edits are
|
|
185
|
+
# those fired from here on): recorded once under ``at``, never in an arm row
|
|
186
|
+
self.path = {"edits": [_keep(e) for e in run.committed_edits()],
|
|
187
|
+
"cells": [_keep(c) for c in run.committed_cells()]}
|
|
188
|
+
self.calibration, self.stable_floors = calibration, stable_floors
|
|
189
|
+
self.kernel_path = kernel_path
|
|
190
|
+
self.arms: dict[str, Arm] = {}
|
|
191
|
+
self._reference = reference
|
|
192
|
+
started = time.monotonic()
|
|
193
|
+
logits = self._to_consumer()
|
|
194
|
+
self.base_logits = logits.detach().clone()
|
|
195
|
+
self.M0 = self._value(logits)
|
|
196
|
+
self.base_argmax = int(logits.reshape(-1).argmax())
|
|
197
|
+
self.base_probes = self._probe()
|
|
198
|
+
self.base_seconds = time.monotonic() - started
|
|
199
|
+
run.restore(self.checkpoint)
|
|
200
|
+
self.extra_floor = abs(float(extra_floor))
|
|
201
|
+
self.floor_spacings = float(floor_spacings)
|
|
202
|
+
if floor is not None:
|
|
203
|
+
self.floor, self.floor_rule = float(floor), "caller"
|
|
204
|
+
elif isinstance(consumer, Margin):
|
|
205
|
+
self.floor = margin_floor(logits, consumer.a, consumer.b, spacings=floor_spacings,
|
|
206
|
+
extra=extra_floor)
|
|
207
|
+
self.floor_rule = (f"{floor_spacings:g} x {str(logits.dtype).removeprefix('torch.')} "
|
|
208
|
+
"spacing at the larger |logit| of the base margin + extra")
|
|
209
|
+
elif isinstance(consumer, Logit):
|
|
210
|
+
size = abs(float(logits.reshape(-1)[consumer.i]))
|
|
211
|
+
self.floor = floor_spacings * spacing(size, logits.dtype) + self.extra_floor
|
|
212
|
+
self.floor_rule = f"{floor_spacings:g} x spacing at the base logit + extra"
|
|
213
|
+
else:
|
|
214
|
+
self.floor, self.floor_rule = None, "none (callable consumer, no floor given)"
|
|
215
|
+
|
|
216
|
+
# --- the consumer ---------------------------------------------------------------------
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
def text(self) -> str:
|
|
220
|
+
return getattr(self.consumer, "text", f"t{self.row}.<callable>")
|
|
221
|
+
|
|
222
|
+
def _value(self, logits: Any) -> float:
|
|
223
|
+
lg = f64(logits).reshape(-1)
|
|
224
|
+
if isinstance(self.consumer, Margin):
|
|
225
|
+
return float(lg[self.consumer.a] - lg[self.consumer.b])
|
|
226
|
+
if isinstance(self.consumer, Logit):
|
|
227
|
+
return float(lg[self.consumer.i])
|
|
228
|
+
return float(self.consumer(lg))
|
|
229
|
+
|
|
230
|
+
def _probe(self) -> dict[str, Any]:
|
|
231
|
+
"""Every probe evaluated on the debuggee where it stands (after the consumer)."""
|
|
232
|
+
out = {}
|
|
233
|
+
for key, probe in self.probes.items():
|
|
234
|
+
value = probe(self.debuggee)
|
|
235
|
+
if isinstance(value, (list, tuple)):
|
|
236
|
+
out[key] = [num(float(v), MEASURED) for v in value]
|
|
237
|
+
else:
|
|
238
|
+
out[key] = num(float(value), MEASURED)
|
|
239
|
+
return out
|
|
240
|
+
|
|
241
|
+
def _to_consumer(self, final_scale: str = "native") -> Any:
|
|
242
|
+
stop = f"t{self.row}.logits"
|
|
243
|
+
self.debuggee.until(stop)
|
|
244
|
+
if final_scale == "held":
|
|
245
|
+
from mdb.engine.holds import final_held_logits
|
|
246
|
+
|
|
247
|
+
return final_held_logits(self.debuggee, self.row, self.reference)
|
|
248
|
+
return self.debuggee.read(stop)
|
|
249
|
+
|
|
250
|
+
@property
|
|
251
|
+
def reference(self) -> Any:
|
|
252
|
+
"""The base continuation as its own run: a run at the root of the debuggee's lineage
|
|
253
|
+
(``Run.fresh``: the same prompt and split, or the checkpoint it was rehydrated from)
|
|
254
|
+
restored to the branch point (edits on the path included) and run to the consumer with
|
|
255
|
+
no arm edit. Holds keep values from it; the nulls read native values from it."""
|
|
256
|
+
if self._reference is None:
|
|
257
|
+
run = self.debuggee
|
|
258
|
+
# the root of the debuggee's lineage: its prompt, or the checkpoint it was
|
|
259
|
+
# rehydrated from (no prefix recompute; the branch point restores from its marks)
|
|
260
|
+
ref = run.fresh()
|
|
261
|
+
ref.name = f"{self.name}:reference"
|
|
262
|
+
ref.hold(run.edit_tensors())
|
|
263
|
+
ref.restore(self.checkpoint)
|
|
264
|
+
# the debuggee's active holds are part of its base: the reference runs under them
|
|
265
|
+
# too, so ``reference == M0`` and the self-patch null reads 0 on a held run
|
|
266
|
+
for held in run.hold_objects():
|
|
267
|
+
if not held.cells:
|
|
268
|
+
ref.hold(held.text, source=held.source, name=held.name)
|
|
269
|
+
ref.until(f"t{self.row}.logits")
|
|
270
|
+
self._reference = ref
|
|
271
|
+
return self._reference
|
|
272
|
+
|
|
273
|
+
# --- arms -----------------------------------------------------------------------------
|
|
274
|
+
|
|
275
|
+
def _shaped(self, e: Edit) -> Edit:
|
|
276
|
+
"""The edit with a cache-cell value in the block shape ``(1, kv, rows, d)`` the stepped
|
|
277
|
+
``Run.set`` wants, when it holds exactly that many numbers in another shape (a flat
|
|
278
|
+
``(d,)`` for one kv head and one row): normalised once here so the batched path and the
|
|
279
|
+
stepped recheck accept the same arms."""
|
|
280
|
+
if not e.cell:
|
|
281
|
+
return e
|
|
282
|
+
from dataclasses import replace
|
|
283
|
+
|
|
284
|
+
from mdb.engine import refs
|
|
285
|
+
|
|
286
|
+
torch = _torch()
|
|
287
|
+
found = refs.resolve(self.debuggee, e.target)
|
|
288
|
+
kwargs = refs.cell_edit(self.debuggee, found, 0.0, None)
|
|
289
|
+
adapter = self.debuggee.adapter
|
|
290
|
+
block = (1, adapter.num_kv_heads if kwargs["kv"] is None else len(kwargs["kv"]),
|
|
291
|
+
len(kwargs["rows"]), adapter.head_dim if kwargs["d"] is None else len(kwargs["d"]))
|
|
292
|
+
ref = e.value if isinstance(e.value, refs.ValueRef) else None
|
|
293
|
+
value = ref.value if ref is not None else e.value
|
|
294
|
+
if (not isinstance(value, torch.Tensor) or tuple(value.shape) == block
|
|
295
|
+
or value.numel() != block[0] * block[1] * block[2] * block[3]):
|
|
296
|
+
return e
|
|
297
|
+
value = value.reshape(block)
|
|
298
|
+
if ref is not None:
|
|
299
|
+
value = refs.ValueRef(value, {**ref.pointer, "shape": list(block)})
|
|
300
|
+
return replace(e, value=value)
|
|
301
|
+
|
|
302
|
+
def add(self, name: str, edits: Sequence[Edit] = (), *, holds: Sequence[Any] = (),
|
|
303
|
+
final_scale: str = "native") -> Arm:
|
|
304
|
+
"""A named arm: ``edits`` staged from the branch point, ``holds`` (addresses held at the
|
|
305
|
+
reference run, or ``(address, run)``) on while it runs, ``final_scale`` ``held`` to read
|
|
306
|
+
the logits with the final RMSNorm scale held too."""
|
|
307
|
+
if name in self.arms or name == "base":
|
|
308
|
+
raise Refusal(f"an arm named {name!r} exists")
|
|
309
|
+
if final_scale not in ("native", "held"):
|
|
310
|
+
raise Refusal("final_scale is native or held")
|
|
311
|
+
arm = Arm(name, "edit",
|
|
312
|
+
[self._shaped(e if isinstance(e, Edit) else Edit(*e)) for e in edits],
|
|
313
|
+
list(holds), final_scale)
|
|
314
|
+
self.arms[name] = arm
|
|
315
|
+
return arm
|
|
316
|
+
|
|
317
|
+
def arm(self, name: str) -> Arm:
|
|
318
|
+
if name not in self.arms:
|
|
319
|
+
raise Refusal(f"no arm {name!r} (arms: {', '.join(self.arms) or 'none'})")
|
|
320
|
+
return self.arms[name]
|
|
321
|
+
|
|
322
|
+
def add_null(self, name: str, kind: str = "random", *, like: str, seed: int = 0,
|
|
323
|
+
holds: Sequence[Any] | None = None) -> Arm:
|
|
324
|
+
"""A built-in null derived from arm ``like`` (module docstring); it keeps ``like``'s
|
|
325
|
+
holds and final scale unless ``holds`` is given."""
|
|
326
|
+
if kind not in NULL_KINDS:
|
|
327
|
+
raise Refusal(f"null kind must be one of {', '.join(NULL_KINDS)}")
|
|
328
|
+
base = self.arm(like)
|
|
329
|
+
if name in self.arms or name == "base":
|
|
330
|
+
raise Refusal(f"an arm named {name!r} exists")
|
|
331
|
+
edits = [self._null(kind, e, like, seed + i) for i, e in enumerate(base.edits)]
|
|
332
|
+
arm = self.add(name, edits, holds=list(base.holds if holds is None else holds),
|
|
333
|
+
final_scale=base.final_scale)
|
|
334
|
+
arm.kind, arm.like, arm.seed = f"null:{kind}", like, seed
|
|
335
|
+
arm.rule = {"random": "matched-norm Gaussian add over the edited elements",
|
|
336
|
+
"self": "edited elements replaced by their native value (self-patch)",
|
|
337
|
+
"answer": "matched-norm add along the consumer readout direction"}[kind]
|
|
338
|
+
return arm
|
|
339
|
+
|
|
340
|
+
def _change(self, e: Edit) -> dict[str, Any]:
|
|
341
|
+
"""``{native, delta, mask, target, port}`` of an edit on the reference run (float64):
|
|
342
|
+
the change the edit makes at its address."""
|
|
343
|
+
from mdb.engine import refs
|
|
344
|
+
|
|
345
|
+
torch = _torch()
|
|
346
|
+
ref = self.reference
|
|
347
|
+
value = e.value.value if isinstance(e.value, refs.ValueRef) else e.value
|
|
348
|
+
found = refs.resolve(ref, e.target)
|
|
349
|
+
if found["kind"] == "cell":
|
|
350
|
+
raw = refs.ref(ref, e.target).value
|
|
351
|
+
native = f64(raw).cpu()
|
|
352
|
+
requested = f64(value).cpu() if isinstance(value, torch.Tensor) else \
|
|
353
|
+
torch.full_like(native, float(value))
|
|
354
|
+
delta = {"replace": lambda: requested - native, "add": lambda: requested,
|
|
355
|
+
"scale": lambda: native * (requested - 1.0),
|
|
356
|
+
"mix": lambda: float(e.dose or 0.0) * (requested - native)}[e.op]()
|
|
357
|
+
return {"native": native, "raw": raw, "delta": delta, "mask": None, "cell": True,
|
|
358
|
+
"target": found["address"], "port": None}
|
|
359
|
+
base = found["address"].partition("[")[0]
|
|
360
|
+
port = found["label"].split(".", 1)[1]
|
|
361
|
+
shape = ref.address_shape(base)
|
|
362
|
+
raw = ref.read(base)
|
|
363
|
+
native = f64(raw).cpu()
|
|
364
|
+
request = refs.port_edit(ref, found, value, None, e.mask, shape=shape)
|
|
365
|
+
mask = request["mask"]
|
|
366
|
+
full = request["value"]
|
|
367
|
+
requested = (f64(full).cpu().expand(shape) if isinstance(full, torch.Tensor)
|
|
368
|
+
else torch.full(shape, float(full), dtype=torch.float64))
|
|
369
|
+
result = {"replace": requested, "add": native + requested,
|
|
370
|
+
"scale": native * requested}[e.op]
|
|
371
|
+
delta = result - native
|
|
372
|
+
if mask is not None:
|
|
373
|
+
delta = torch.where(mask.cpu().broadcast_to(shape), delta, torch.zeros_like(delta))
|
|
374
|
+
return {"native": native, "raw": raw, "delta": delta, "mask": mask, "cell": False,
|
|
375
|
+
"target": base,
|
|
376
|
+
"port": port}
|
|
377
|
+
|
|
378
|
+
def _null(self, kind: str, e: Edit, like: str, seed: int) -> Edit:
|
|
379
|
+
torch = _torch()
|
|
380
|
+
change = self._change(e)
|
|
381
|
+
delta, mask = change["delta"], change["mask"]
|
|
382
|
+
size = float(delta.norm())
|
|
383
|
+
dtype = self.debuggee.adapter.dtype
|
|
384
|
+
origin = {"kind": "null", "null": kind, "like": like, "seed": seed,
|
|
385
|
+
"matched_norm": num(size, EXACT), "address": change["target"]}
|
|
386
|
+
if kind == "self":
|
|
387
|
+
value = change["raw"] # the native value as read: no cast at all
|
|
388
|
+
return Edit(e.target if change["cell"] else change["target"], value, "replace",
|
|
389
|
+
mask=None if change["cell"] else mask, origin=origin)
|
|
390
|
+
if kind == "random":
|
|
391
|
+
g = torch.randn(delta.shape, generator=torch.Generator().manual_seed(seed),
|
|
392
|
+
dtype=torch.float64)
|
|
393
|
+
if mask is not None:
|
|
394
|
+
g = torch.where(mask.cpu().broadcast_to(g.shape), g, torch.zeros_like(g))
|
|
395
|
+
g = g * (size / float(g.norm())) if float(g.norm()) else g
|
|
396
|
+
return Edit(e.target if change["cell"] else change["target"], g.to(dtype), "add",
|
|
397
|
+
mask=None if change["cell"] else mask, origin=origin)
|
|
398
|
+
if change["cell"] or change["port"] not in RESIDUAL_PORTS:
|
|
399
|
+
raise Refusal(f"an answer null writes along the readout direction: residual-stream "
|
|
400
|
+
f"ports only ({', '.join(RESIDUAL_PORTS)}), not {e.target}")
|
|
401
|
+
from .readout import readout
|
|
402
|
+
|
|
403
|
+
c = f64(readout(self.reference, self.consumer).vector).reshape(-1).cpu()
|
|
404
|
+
if not float(c.norm()):
|
|
405
|
+
raise Refusal("an answer null needs a nonzero readout direction: the consumer's "
|
|
406
|
+
"readout vector has zero norm (a == b, or degenerate weights)")
|
|
407
|
+
u = c / float(c.norm())
|
|
408
|
+
flat = delta.reshape(-1, delta.shape[-1])
|
|
409
|
+
rows = []
|
|
410
|
+
for vec in flat:
|
|
411
|
+
n = float(vec.norm())
|
|
412
|
+
sign = 1.0 if float(vec @ u) >= 0 else -1.0
|
|
413
|
+
rows.append(sign * n * u)
|
|
414
|
+
g = torch.stack(rows).reshape(delta.shape)
|
|
415
|
+
origin["direction"] = "readout vector (reads.readout(...).vector), signed like the change"
|
|
416
|
+
return Edit(change["target"], g.to(dtype), "add", origin=origin)
|
|
417
|
+
|
|
418
|
+
# --- measuring --------------------------------------------------------------------------
|
|
419
|
+
|
|
420
|
+
def _stage(self, e: Edit) -> None:
|
|
421
|
+
run = self.debuggee
|
|
422
|
+
value, origin = e.value, e.origin
|
|
423
|
+
if e.cell:
|
|
424
|
+
run.set(e.target, value, e.op, origin=origin) if e.dose is None else \
|
|
425
|
+
self._mix(e)
|
|
426
|
+
return
|
|
427
|
+
from mdb.engine import refs
|
|
428
|
+
|
|
429
|
+
found = refs.resolve(run, e.target)
|
|
430
|
+
row, label = found["row"], found["label"]
|
|
431
|
+
first = f"t{row}.{label.split('.')[0]}.{run.program.names[0]}"
|
|
432
|
+
here, there = run.parse(run.where), run.parse(first)
|
|
433
|
+
own = run.parse(found["address"].partition("[")[0])
|
|
434
|
+
if own < run.parse(self.at):
|
|
435
|
+
raise Refusal(f"{e.target} is before the branch point {self.at}")
|
|
436
|
+
if there > here:
|
|
437
|
+
run.until(first)
|
|
438
|
+
run.set(e.target, value, e.op, mask=e.mask, origin=origin)
|
|
439
|
+
|
|
440
|
+
def _mix(self, e: Edit) -> None:
|
|
441
|
+
from mdb.engine import refs
|
|
442
|
+
|
|
443
|
+
found = refs.resolve(self.debuggee, e.target)
|
|
444
|
+
kwargs = refs.cell_edit(self.debuggee, found, e.value, e.origin)
|
|
445
|
+
value = kwargs.pop("value")
|
|
446
|
+
self.debuggee.set_cell(kwargs.pop("layer"), kwargs.pop("tensor"), value, "mix", dose=e.dose,
|
|
447
|
+
**kwargs)
|
|
448
|
+
|
|
449
|
+
def _measure(self, arm: Arm) -> dict[str, Any]:
|
|
450
|
+
run = self.debuggee
|
|
451
|
+
started = time.monotonic()
|
|
452
|
+
run.restore(self.checkpoint)
|
|
453
|
+
names = []
|
|
454
|
+
try:
|
|
455
|
+
for i, held in enumerate(arm.holds):
|
|
456
|
+
address, source = (held, None) if isinstance(held, str) else held
|
|
457
|
+
hold_name = f"{arm.name}:{i}"
|
|
458
|
+
run.hold(address, source=source if source is not None else self.reference,
|
|
459
|
+
name=hold_name)
|
|
460
|
+
names.append(hold_name)
|
|
461
|
+
cells_first = sorted(arm.edits, key=lambda e: not e.cell)
|
|
462
|
+
from mdb.engine import refs
|
|
463
|
+
|
|
464
|
+
def order(e: Edit) -> Any:
|
|
465
|
+
return run.parse(refs.resolve(run, e.target)["address"].partition("[")[0])
|
|
466
|
+
|
|
467
|
+
ports = sorted((e for e in cells_first if not e.cell), key=order)
|
|
468
|
+
for e in [*(c for c in cells_first if c.cell), *ports]:
|
|
469
|
+
self._stage(e)
|
|
470
|
+
logits = self._to_consumer(arm.final_scale)
|
|
471
|
+
probed = self._probe()
|
|
472
|
+
start = int(self.checkpoint["transitions"])
|
|
473
|
+
committed = [c for c in run.committed_edits() if c["transition"] >= start]
|
|
474
|
+
hold_edits = [c for c in committed if c.get("origin", {}).get("kind") == "hold"]
|
|
475
|
+
user = [c for c in committed if c.get("origin", {}).get("kind") != "hold"]
|
|
476
|
+
cells = [c for c in run.committed_cells() if c["transition"] >= start]
|
|
477
|
+
holds = [h for h in run.holds if h["name"] in names]
|
|
478
|
+
finally:
|
|
479
|
+
for hold_name in names:
|
|
480
|
+
if any(h["name"] == hold_name for h in run.holds):
|
|
481
|
+
run.release(hold_name)
|
|
482
|
+
run.restore(self.checkpoint)
|
|
483
|
+
row = self._row(arm, logits, user, cells, holds, len(hold_edits),
|
|
484
|
+
time.monotonic() - started, self.kernel_path)
|
|
485
|
+
if self.probes:
|
|
486
|
+
row["probes"] = probed
|
|
487
|
+
return row
|
|
488
|
+
|
|
489
|
+
def _row(self, arm: Arm, logits: Any, edits: list, cells: list, holds: list, fired: int,
|
|
490
|
+
seconds: float, kernel_path: str, extra: float = 0.0) -> dict[str, Any]:
|
|
491
|
+
M = self._value(logits)
|
|
492
|
+
dM = M - self.M0
|
|
493
|
+
edits = [_keep(e) for e in edits]
|
|
494
|
+
cells = [_keep(c) for c in cells]
|
|
495
|
+
out: dict[str, Any] = {
|
|
496
|
+
"name": arm.name, "kind": arm.kind, "like": arm.like, "rule": arm.rule,
|
|
497
|
+
"M": num(M, MEASURED), "dM": num(dM, MEASURED),
|
|
498
|
+
"argmax": int(logits.reshape(-1).argmax()),
|
|
499
|
+
"edits": _safe(edits, SUPPLIED),
|
|
500
|
+
"cells": _safe(cells, SUPPLIED),
|
|
501
|
+
"holds": _safe([{**h, "edits_fired": fired} for h in holds], EXACT),
|
|
502
|
+
"final_scale": arm.final_scale, "kernel_path": kernel_path,
|
|
503
|
+
"seconds": num(seconds, MEASURED)}
|
|
504
|
+
if isinstance(self.consumer, (Margin, Logit)):
|
|
505
|
+
# the consumer's |logit| size on this arm: a floor over an item's arms
|
|
506
|
+
out["magnitude"] = num(magnitude(self.consumer, logits), MEASURED)
|
|
507
|
+
if arm.final_scale == "held":
|
|
508
|
+
out["final_scale_authority"] = EXACT
|
|
509
|
+
if self.floor is not None:
|
|
510
|
+
floor = self.floor + extra
|
|
511
|
+
stab = stability(dM, floor, kernel_path=kernel_path, calibration=self.calibration,
|
|
512
|
+
k=self.stable_floors)
|
|
513
|
+
out["floor"] = num(floor, MEASURED)
|
|
514
|
+
out["effect_floors"] = stab.pop("floors", None) # None: a zero floor
|
|
515
|
+
out["above_floor"] = abs(dM) > floor
|
|
516
|
+
out.update({k: v for k, v in stab.items() if k != "kernel_path"})
|
|
517
|
+
return out
|
|
518
|
+
|
|
519
|
+
def run_arms(self, names: Sequence[str] | None = None, *, again: bool = False
|
|
520
|
+
) -> list[dict[str, Any]]:
|
|
521
|
+
"""Measure the named arms (default: every arm not measured yet; ``again``: re-measure)
|
|
522
|
+
on the stepped path; returns their rows. The run is back at the branch point after."""
|
|
523
|
+
chosen = list(self.arms) if names is None else list(names)
|
|
524
|
+
rows = []
|
|
525
|
+
for name in chosen:
|
|
526
|
+
arm = self.arm(name)
|
|
527
|
+
if arm.result is None or again:
|
|
528
|
+
arm.result = self._measure(arm)
|
|
529
|
+
rows.append(arm.result)
|
|
530
|
+
return rows
|
|
531
|
+
|
|
532
|
+
def run(self, names: Sequence[str] | None = None, *, mode: str = "stepped",
|
|
533
|
+
recheck: int | str | None = "band", again: bool = False, batch: int = 64
|
|
534
|
+
) -> list[dict[str, Any]]:
|
|
535
|
+
"""Measure arms: ``mode="stepped"`` (``run_arms``, the authority; ``recheck`` unused) or
|
|
536
|
+
``"batched"`` (``batched``, with ``recheck`` stepped re-measurements)."""
|
|
537
|
+
if mode == "stepped":
|
|
538
|
+
return self.run_arms(names, again=again)
|
|
539
|
+
if mode == "batched":
|
|
540
|
+
return self.batched(names, recheck=recheck, batch=batch)
|
|
541
|
+
raise Refusal("mode is stepped or batched")
|
|
542
|
+
|
|
543
|
+
def _batched_edit(self, arm: Arm, e: Edit) -> Any:
|
|
544
|
+
"""The ``Cell`` or ``PortPatch`` of one batched arm edit (refusing what cannot batch)."""
|
|
545
|
+
from mdb.engine import refs
|
|
546
|
+
from mdb.engine.ports import PortEdit
|
|
547
|
+
|
|
548
|
+
from .sweep import Cell, PortPatch
|
|
549
|
+
|
|
550
|
+
torch = _torch()
|
|
551
|
+
found = refs.resolve(self.debuggee, e.target)
|
|
552
|
+
if e.cell:
|
|
553
|
+
if e.op != "replace" or e.dose is not None:
|
|
554
|
+
raise Refusal(f"arm {arm.name}: a batched cell arm replaces whole cells, not "
|
|
555
|
+
f"{e.target} ({e.dose is not None and 'mix' or e.op})")
|
|
556
|
+
keys = dict(found["selector"].keys)
|
|
557
|
+
kv, row = keys.get("kv"), keys.get("row")
|
|
558
|
+
if not isinstance(kv, int) or not isinstance(row, int) or "d" in keys:
|
|
559
|
+
raise Refusal(f"{e.target}: one kv head and one row, all of head_dim")
|
|
560
|
+
value = e.value.value if isinstance(e.value, refs.ValueRef) else e.value
|
|
561
|
+
if not isinstance(value, torch.Tensor):
|
|
562
|
+
raise Refusal(f"arm {arm.name}: batched cell {e.target} needs a tensor "
|
|
563
|
+
"value, not a number")
|
|
564
|
+
return Cell(found["layer"], found["tensor"], row, kv, value)
|
|
565
|
+
if e.dose is not None:
|
|
566
|
+
raise Refusal(f"arm {arm.name}: a dose applies to cell edits only")
|
|
567
|
+
if found["row"] != self.row:
|
|
568
|
+
raise Refusal(f"arm {arm.name}: batched port edits are at the pending row "
|
|
569
|
+
f"t{self.row}, not {e.target}")
|
|
570
|
+
layer_text, _, port = found["label"].partition(".")
|
|
571
|
+
base = found["address"].partition("[")[0]
|
|
572
|
+
if self.debuggee.parse(base) < self.debuggee.parse(self.at):
|
|
573
|
+
raise Refusal(f"{e.target} is before the branch point {self.at}")
|
|
574
|
+
request = refs.port_edit(self.debuggee, found, e.value, None, e.mask,
|
|
575
|
+
shape=self.reference.address_shape(base))
|
|
576
|
+
mask = request["mask"]
|
|
577
|
+
shape = tuple(self.reference.address_shape(base))
|
|
578
|
+
edit = PortEdit(port, request["value"], e.op,
|
|
579
|
+
mask=None if mask is None else mask.broadcast_to(shape).contiguous(),
|
|
580
|
+
selection=request["selection"])
|
|
581
|
+
return PortPatch(int(layer_text[1:]), port, edit)
|
|
582
|
+
|
|
583
|
+
def _batched_record(self, e: Edit) -> dict[str, Any]:
|
|
584
|
+
"""The edit record of a batched arm edit, in the stepped path's shape: a cell edit has
|
|
585
|
+
``cell``, a port edit ``layer``/``row``; both ``port``, ``op``, ``selection``, ``origin``."""
|
|
586
|
+
from mdb.engine import refs
|
|
587
|
+
|
|
588
|
+
found = refs.resolve(self.debuggee, e.target)
|
|
589
|
+
origin = getattr(e.value, "pointer", e.origin)
|
|
590
|
+
if e.cell:
|
|
591
|
+
out = {"port": f"cache.L{found['layer']}.{found['tensor']}", "op": e.op,
|
|
592
|
+
"selection": found["selection"],
|
|
593
|
+
"cell": {"layer": found["layer"], "tensor": found["tensor"]}}
|
|
594
|
+
else:
|
|
595
|
+
layer, _, port = found["label"].partition(".")
|
|
596
|
+
out = {"port": port, "op": e.op, "selection": found["selection"],
|
|
597
|
+
"layer": int(layer[1:]), "row": found["row"]}
|
|
598
|
+
return {**out, "origin": origin} if origin else out
|
|
599
|
+
|
|
600
|
+
def _recheck_plan(self, rows: list[dict[str, Any]], recheck: Any) -> dict[int, str]:
|
|
601
|
+
"""``{arm index: why}`` of the arms to re-measure stepped, and (in place) the
|
|
602
|
+
``recheck`` record of every row (``done``, ``why``)."""
|
|
603
|
+
if recheck in (None, False, 0):
|
|
604
|
+
plan: dict[int, str] = {}
|
|
605
|
+
why = {i: "recheck off" for i in range(len(rows))}
|
|
606
|
+
elif recheck == "all" or recheck is True:
|
|
607
|
+
plan = {i: "recheck='all'" for i in range(len(rows))}
|
|
608
|
+
why = {}
|
|
609
|
+
elif recheck == "band":
|
|
610
|
+
plan, why = {}, {}
|
|
611
|
+
for i, row in enumerate(rows):
|
|
612
|
+
f = (row.get("effect_floors") or {}).get("value")
|
|
613
|
+
k = float(row["k"]["value"]) if "k" in row else None
|
|
614
|
+
if f is None or k is None:
|
|
615
|
+
plan[i] = "no floor: the band cannot be judged, rechecked"
|
|
616
|
+
elif f > k:
|
|
617
|
+
why[i] = (f"above the band: {f:.3g} floors > k={k:g} (stable; no kernel-path "
|
|
618
|
+
"difference measured above k floors)")
|
|
619
|
+
elif f < 1.0 / k:
|
|
620
|
+
why[i] = f"clearly null: {f:.3g} floors < 1/k={1.0 / k:.3g}; verdict cannot flip"
|
|
621
|
+
else:
|
|
622
|
+
plan[i] = f"in the kernel-sensitive band: 1/k <= {f:.3g} floors <= k={k:g}"
|
|
623
|
+
elif isinstance(recheck, int) and not isinstance(recheck, bool) and recheck > 0:
|
|
624
|
+
order = sorted(range(len(rows)), key=lambda i: -abs(rows[i]["dM"]["value"]))
|
|
625
|
+
plan = {i: f"recheck={recheck}: among the {recheck} largest |dM|"
|
|
626
|
+
for i in order[:recheck]}
|
|
627
|
+
why = {i: f"recheck={recheck}: not among the {recheck} largest |dM|"
|
|
628
|
+
for i in range(len(rows)) if i not in plan}
|
|
629
|
+
else:
|
|
630
|
+
raise Refusal("recheck is 0 (none), 'band', 'all' or an int k (the k largest)")
|
|
631
|
+
for i, row in enumerate(rows):
|
|
632
|
+
row["recheck"] = {"done": i in plan, "why": plan.get(i) or why.get(i, "")}
|
|
633
|
+
return plan
|
|
634
|
+
|
|
635
|
+
def batched(self, names: Sequence[str] | None = None, *, recheck: int | str | None = "band",
|
|
636
|
+
batch: int = 64) -> list[dict[str, Any]]:
|
|
637
|
+
"""Arms measured in batched native forwards (``sweep.cell_sweep``): state-cell arms
|
|
638
|
+
(every edit a ``replace`` of whole cells ``cache.L<l>.k|v[kv<g>,row=<r>]``: one kv head,
|
|
639
|
+
one row, all of head_dim) and port arms at the pending row's native-module ports
|
|
640
|
+
(``a q k v n g sg u f A o m``; any op/selector/mask; holds refused), the branch point the
|
|
641
|
+
pending row's first port with no edits on the path. Kernel path ``batched``; the measured
|
|
642
|
+
null-vs-stepped delta is added to those arms' floor.
|
|
643
|
+
|
|
644
|
+
``recheck`` (module docstring): ``"band"`` (default) re-measures stepped only the arms
|
|
645
|
+
whose effect is within the kernel-sensitive band and could flip, ``"all"`` every arm,
|
|
646
|
+
an int ``k`` the ``k`` of largest ``|dM|``, ``0`` none. A rechecked row's
|
|
647
|
+
``M``, ``dM``, ``argmax``, floor and stability are the stepped measurement's (the
|
|
648
|
+
authority); the batched ones are under ``batched``, ``stepped`` holds the stepped
|
|
649
|
+
``dM``/``argmax``/``kernel_path`` and ``kernel_delta`` = batched - stepped; every row carries
|
|
650
|
+
``recheck = {done, why}``. ``seconds`` of a batched row is the whole sweep's wall time
|
|
651
|
+
divided by the arms (the batch is one measurement); a stepped arm's is its own."""
|
|
652
|
+
from ..numerics.stability import BATCHED
|
|
653
|
+
from .sweep import cell_sweep
|
|
654
|
+
|
|
655
|
+
torch = _torch()
|
|
656
|
+
chosen = [self.arm(n) for n in (list(self.arms) if names is None else names)]
|
|
657
|
+
cells_of = []
|
|
658
|
+
for arm in chosen:
|
|
659
|
+
if arm.holds or arm.final_scale != "native":
|
|
660
|
+
raise Refusal(f"arm {arm.name}: holds run on the stepped path only")
|
|
661
|
+
cells_of.append([self._batched_edit(arm, e) for e in arm.edits])
|
|
662
|
+
logits_all = self.base_logits
|
|
663
|
+
run = self.debuggee
|
|
664
|
+
first = f"t{self.row}.L0.{run.program.names[0]}"
|
|
665
|
+
moved = run.parse(run.where) != run.parse(first)
|
|
666
|
+
if moved:
|
|
667
|
+
# the sweep runs the pending row whole from its first port: with nothing edited on
|
|
668
|
+
# the path (cell_sweep refuses otherwise) the branch point's state is the same
|
|
669
|
+
run.rewind(first)
|
|
670
|
+
started = time.monotonic()
|
|
671
|
+
try:
|
|
672
|
+
swept = cell_sweep(run, cells_of, batch=batch, stepped_logits=logits_all)
|
|
673
|
+
finally:
|
|
674
|
+
if moved:
|
|
675
|
+
run.restore(self.checkpoint)
|
|
676
|
+
sweep_seconds = time.monotonic() - started # the whole batch's wall time
|
|
677
|
+
extra = float(swept["null_vs_stepped"] or 0.0)
|
|
678
|
+
# the same delta over the consumer's own tokens only (measured there;
|
|
679
|
+
# ``null_vs_stepped`` is the max over the whole vocabulary)
|
|
680
|
+
own = None
|
|
681
|
+
if isinstance(self.consumer, (Margin, Logit)) and len(swept["null"]):
|
|
682
|
+
ids = ([self.consumer.a, self.consumer.b] if isinstance(self.consumer, Margin)
|
|
683
|
+
else [self.consumer.i])
|
|
684
|
+
native = logits_all.reshape(-1).float().cpu()[ids]
|
|
685
|
+
own = float(max((n[ids] - native).abs().max() for n in swept["null"]))
|
|
686
|
+
rows = []
|
|
687
|
+
for i, arm in enumerate(chosen):
|
|
688
|
+
row_logits = swept["logits"][i]
|
|
689
|
+
records = [self._batched_record(e) for e in arm.edits]
|
|
690
|
+
arm.result = self._row(arm, row_logits, [r for r in records if "cell" not in r],
|
|
691
|
+
[r for r in records if "cell" in r], [], 0,
|
|
692
|
+
sweep_seconds / len(chosen), BATCHED, extra=2 * extra)
|
|
693
|
+
arm.result["kernel_delta_null"] = num(extra, MEASURED)
|
|
694
|
+
if own is not None:
|
|
695
|
+
arm.result["kernel_delta_null_consumer_tokens"] = num(own, MEASURED)
|
|
696
|
+
rows.append(arm.result)
|
|
697
|
+
for i, why in self._recheck_plan(rows, recheck).items():
|
|
698
|
+
stepped = self._measure(chosen[i])
|
|
699
|
+
row = rows[i]
|
|
700
|
+
kernel_delta = row["dM"]["value"] - stepped["dM"]["value"]
|
|
701
|
+
row["batched"] = {k: row[k] for k in _VERDICT if k in row}
|
|
702
|
+
row.update({k: stepped[k] for k in _VERDICT if k in stepped}) # the authority
|
|
703
|
+
row["stepped"] = {"dM": stepped["dM"], "argmax": stepped["argmax"],
|
|
704
|
+
"kernel_path": stepped["kernel_path"]}
|
|
705
|
+
row["kernel_delta"] = num(kernel_delta, MEASURED)
|
|
706
|
+
_ = torch
|
|
707
|
+
return rows
|
|
708
|
+
|
|
709
|
+
# --- debugger verbs -------------------------------------------------------------------------
|
|
710
|
+
|
|
711
|
+
def restore(self) -> str:
|
|
712
|
+
"""Put the run back at the branch point."""
|
|
713
|
+
return self.debuggee.restore(self.checkpoint)
|
|
714
|
+
|
|
715
|
+
def compare(self, a: str, b: str) -> dict[str, Any]:
|
|
716
|
+
"""Arm ``a`` minus arm ``b`` at the consumer, in the shared floor's units."""
|
|
717
|
+
ra, rb = (self.arm(n).result for n in (a, b))
|
|
718
|
+
if ra is None or rb is None:
|
|
719
|
+
raise Refusal("measure both arms first (run_arms)")
|
|
720
|
+
diff = ra["M"]["value"] - rb["M"]["value"]
|
|
721
|
+
out = {"a": a, "b": b, "difference": num(diff, MEASURED),
|
|
722
|
+
"kernel_paths": [ra["kernel_path"], rb["kernel_path"]],
|
|
723
|
+
"rechecked": [bool(r.get("recheck", {}).get("done")) for r in (ra, rb)]}
|
|
724
|
+
if self.floor:
|
|
725
|
+
out["floors"] = num(abs(diff) / self.floor, MEASURED)
|
|
726
|
+
out["above_floor"] = abs(diff) > self.floor
|
|
727
|
+
return out
|
|
728
|
+
|
|
729
|
+
def table(self) -> list[dict[str, Any]]:
|
|
730
|
+
"""One row per measured arm (base first): name, kind, dM, argmax, floors, stability."""
|
|
731
|
+
rows = [{"name": "base", "kind": "base", "M": self.M0, "dM": 0.0,
|
|
732
|
+
"argmax": self.base_argmax, "effect_floors": 0.0, "kernel_path": self.kernel_path,
|
|
733
|
+
"rechecked": False}]
|
|
734
|
+
for arm in self.arms.values():
|
|
735
|
+
r = arm.result
|
|
736
|
+
if r is None:
|
|
737
|
+
continue
|
|
738
|
+
rows.append({"name": arm.name, "kind": arm.kind, "M": r["M"]["value"],
|
|
739
|
+
"dM": r["dM"]["value"], "argmax": r["argmax"],
|
|
740
|
+
"effect_floors": (r.get("effect_floors") or {}).get("value"),
|
|
741
|
+
"stability": r.get("stability"), "kernel_path": r["kernel_path"],
|
|
742
|
+
"rechecked": bool(r.get("recheck", {}).get("done"))})
|
|
743
|
+
return rows
|
|
744
|
+
|
|
745
|
+
def seal(self, *, session_id: str | None = None) -> dict[str, Any]:
|
|
746
|
+
"""A ``branches`` record of every measured arm (at most 64; ``arms_omitted`` counts the
|
|
747
|
+
rest), with custody."""
|
|
748
|
+
from mdb.core.custody import custody
|
|
749
|
+
|
|
750
|
+
run = self.debuggee
|
|
751
|
+
measured = [a.result for a in self.arms.values() if a.result is not None]
|
|
752
|
+
row, index = run.parse(self.at)
|
|
753
|
+
consumer: dict[str, Any] = {"text": self.text, "row": int(self.row)}
|
|
754
|
+
if isinstance(self.consumer, Margin):
|
|
755
|
+
consumer.update(kind="margin", a=int(self.consumer.a), b=int(self.consumer.b))
|
|
756
|
+
elif isinstance(self.consumer, Logit):
|
|
757
|
+
consumer.update(kind="logit", i=int(self.consumer.i))
|
|
758
|
+
else:
|
|
759
|
+
consumer["kind"] = "callable"
|
|
760
|
+
body = {
|
|
761
|
+
"schema": SCHEMA, "name": self.name,
|
|
762
|
+
"at": {"where": self.at, "row": int(row), "cut": self.checkpoint["cut"],
|
|
763
|
+
"transitions": int(self.checkpoint["transitions"]),
|
|
764
|
+
"path_edits": _safe(self.path["edits"], SUPPLIED),
|
|
765
|
+
"path_cells": _safe(self.path["cells"], SUPPLIED)},
|
|
766
|
+
"consumer": consumer,
|
|
767
|
+
"base": {"M": num(self.M0, MEASURED), "argmax": self.base_argmax,
|
|
768
|
+
**({"probes": self.base_probes} if self.probes else {})},
|
|
769
|
+
"probes": sorted(self.probes),
|
|
770
|
+
"floor": ({"value": num(self.floor, MEASURED), "rule": self.floor_rule,
|
|
771
|
+
"spacings": num(self.floor_spacings, SUPPLIED),
|
|
772
|
+
"extra": num(self.extra_floor, MEASURED)} if self.floor is not None
|
|
773
|
+
else {"rule": self.floor_rule}),
|
|
774
|
+
"arms": measured[:_CAP], "n_arms": len(measured),
|
|
775
|
+
"arms_omitted": max(0, len(measured) - _CAP),
|
|
776
|
+
"procedure": procedure(run),
|
|
777
|
+
"custody": custody(self.kernel_path),
|
|
778
|
+
}
|
|
779
|
+
def sealed(b):
|
|
780
|
+
return seal_record(session_id=session_id or run_session_id(run), kind="branches",
|
|
781
|
+
model_identity=run.adapter.model_identity,
|
|
782
|
+
execution=dict(run.adapter.execution), authority=MEASURED, body=b, run=run)
|
|
783
|
+
from mdb.core.pointers import RecordError
|
|
784
|
+
|
|
785
|
+
try:
|
|
786
|
+
return sealed(body)
|
|
787
|
+
except RecordError:
|
|
788
|
+
# too large for one record (many arms with edits/probes): the full rows by pointer
|
|
789
|
+
# (bounded.put_json, held on the run), a compact per-arm table in the record
|
|
790
|
+
from mdb.core.bounded import put_json
|
|
791
|
+
|
|
792
|
+
body["arms_payload"] = put_json(measured, run=run)
|
|
793
|
+
body["arms"] = [{"name": r["name"], "kind": r["kind"], "M": r["M"], "dM": r["dM"],
|
|
794
|
+
"argmax": r["argmax"], "stability": r.get("stability"),
|
|
795
|
+
"effect_floors": r.get("effect_floors"),
|
|
796
|
+
"kernel_path": r["kernel_path"]} for r in measured[:_CAP]]
|
|
797
|
+
body["arms_compact"] = True
|
|
798
|
+
return sealed(body)
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def branches(run: Any, consumer: Any, **options: Any) -> Branches:
|
|
802
|
+
return Branches(run, consumer, **options)
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
__all__ = ["Arm", "Branches", "Edit", "NULL_KINDS", "RESIDUAL_PORTS", "SCHEMA", "branches",
|
|
806
|
+
"edit"]
|