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,455 @@
|
|
|
1
|
+
"""Who reads a value: the attention reads of one source row, with mass, exact contribution and a
|
|
2
|
+
natively measured causal verdict.
|
|
3
|
+
|
|
4
|
+
The attention value mix is exact (P06/P07): at reader row ``j`` and layer ``l`` head ``h``
|
|
5
|
+
writes ``A_h = sum_s p[h, s] v[kappa(h), s]`` and the layer writes ``o = sum_h W_o,h A_h``. So
|
|
6
|
+
the part of ``o`` that source ``s`` sends through head ``h`` is ``p[h, s] W_o,h v[kappa(h), s]``
|
|
7
|
+
(``derived-exact``, float64 on captured operands). A declared consumer reads it through an exact
|
|
8
|
+
linear map: a margin ``M[a,b]`` or a logit through the final-norm readout with the final-norm
|
|
9
|
+
scale ``rho`` evaluated once at the native final state (P19, the convention of
|
|
10
|
+
``explain_margin``), a residual-stream port of the same row (``h``, ``r``, ``h_out`` of a later
|
|
11
|
+
point) as itself, and ``o`` of the read's own layer (the default consumer) as itself.
|
|
12
|
+
|
|
13
|
+
The causal verdict of a read is a native measurement: the source's weight in that head is set to
|
|
14
|
+
zero (``p[h, src] = 0``, a masked ``replace`` at the ``p`` port) through
|
|
15
|
+
``analysis.predict.propagate.whatif``, which measures the consumer natively and restores the
|
|
16
|
+
session.
|
|
17
|
+
The verdict follows whatif's P20 verdict (``verdict.decide``: the native change against the
|
|
18
|
+
emulated change, the base and edited chains with the dtype's rounding where eager HF rounds,
|
|
19
|
+
within one spacing at the consumer): ``causal`` when whatif finds an effect (the native change is
|
|
20
|
+
not zero, as the emulation predicts) and the change exceeds ``min_effect`` (default 0); ``not
|
|
21
|
+
causal at this dose`` when whatif finds no effect (the dtype shows no change at the consumer);
|
|
22
|
+
``unresolved`` (with the reason) otherwise, or when the measurement could not be made. Both facts
|
|
23
|
+
are kept when they differ: a read whose exact change is real but below the dtype's resolution
|
|
24
|
+
at the consumer is ``not causal at this dose`` with the reason ``no change at bfloat16
|
|
25
|
+
resolution; exact ΔM 0.33``, and a native change that is rounding only carries its exact change.
|
|
26
|
+
No worst-case rounding bound gates it. Mass and effect are always reported side by side; a small
|
|
27
|
+
mass never hides a read.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import math
|
|
33
|
+
import re
|
|
34
|
+
from collections.abc import Sequence
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
from typing import Any
|
|
37
|
+
|
|
38
|
+
from ..numerics.labels import BOUND, EXACT, MEASURED, SUPPLIED, f64, num
|
|
39
|
+
from ..numerics.verdict import EFFECT, NO_EFFECT
|
|
40
|
+
from ..predict.consumers import Refusal
|
|
41
|
+
from .readout import (
|
|
42
|
+
HeadMix,
|
|
43
|
+
Readout,
|
|
44
|
+
claim,
|
|
45
|
+
edited_block,
|
|
46
|
+
first_row,
|
|
47
|
+
head_mask,
|
|
48
|
+
head_mix,
|
|
49
|
+
readout,
|
|
50
|
+
refused,
|
|
51
|
+
size,
|
|
52
|
+
unresolved,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
VERDICTS = ("causal", "not causal at this dose", "unresolved")
|
|
56
|
+
_ROW = re.compile(r"t(?P<row>\d+)")
|
|
57
|
+
_SOURCE = re.compile(r"t(?P<row>\d+)(?:\.L(?P<layer>\d+)\.(?P<port>kr|kn|k|v))?")
|
|
58
|
+
_CELL = re.compile(r"cache\.L(?P<layer>\d+)\.(?P<port>k|v)\[(?P<sel>[^\]]*)\]")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# --------------------------------------------------------------------------- consumers
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# --------------------------------------------------------------------------- the value mix
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# --------------------------------------------------------------------------- sources
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class Source:
|
|
76
|
+
"""Cache cells of one source row: ``layers`` / ``kv`` / ``ports`` (``k``, ``v``) None means
|
|
77
|
+
all. ``covers(layer, kv)`` asks about a read (any port); with ``port`` about one cell."""
|
|
78
|
+
|
|
79
|
+
row: int
|
|
80
|
+
layers: tuple[int, ...] | None = None
|
|
81
|
+
kv: tuple[int, ...] | None = None
|
|
82
|
+
text: str = ""
|
|
83
|
+
ports: tuple[str, ...] | None = None
|
|
84
|
+
|
|
85
|
+
def covers(self, layer: int, kv: int, port: str | None = None) -> bool:
|
|
86
|
+
return ((self.layers is None or layer in self.layers)
|
|
87
|
+
and (self.kv is None or kv in self.kv)
|
|
88
|
+
and (port is None or self.ports is None or port in self.ports))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_source(run: Any, text: str) -> Source:
|
|
92
|
+
"""``t<r>``, ``t<r>.L<l>.k|v|kn|kr`` or ``cache.L<l>.k|v[row=<r>]`` (with ``kv<i>``)."""
|
|
93
|
+
text = text.strip()
|
|
94
|
+
layers = run.adapter.layers
|
|
95
|
+
match = _SOURCE.fullmatch(text)
|
|
96
|
+
if match is not None:
|
|
97
|
+
row = int(match["row"])
|
|
98
|
+
layer = None if match["layer"] is None else int(match["layer"])
|
|
99
|
+
if layer is not None and layer >= layers:
|
|
100
|
+
raise Refusal(f"no layer {layer} in a {layers}-layer model")
|
|
101
|
+
port = match["port"]
|
|
102
|
+
return Source(row, None if layer is None else (layer,), None, text,
|
|
103
|
+
None if port is None else ("v",) if port == "v" else ("k",))
|
|
104
|
+
match = _CELL.fullmatch(text)
|
|
105
|
+
if match is None:
|
|
106
|
+
raise Refusal(f"a read source is a token row t<r>, a cache-row occurrence t<r>.L<l>.k|v "
|
|
107
|
+
f"or a cache cell cache.L<l>.k|v[row=<r>], not {text!r}")
|
|
108
|
+
layer = int(match["layer"])
|
|
109
|
+
if layer >= layers:
|
|
110
|
+
raise Refusal(f"no layer {layer} in a {layers}-layer model")
|
|
111
|
+
row = kv = None
|
|
112
|
+
for part in filter(None, (p.strip() for p in match["sel"].split(","))):
|
|
113
|
+
key, _, value = part.partition("=")
|
|
114
|
+
if not value and key.startswith("kv") and key[2:].isdigit():
|
|
115
|
+
kv = int(key[2:])
|
|
116
|
+
elif key == "kv" and value.isdigit():
|
|
117
|
+
kv = int(value)
|
|
118
|
+
elif key == "row" and value.isdigit():
|
|
119
|
+
row = int(value)
|
|
120
|
+
else:
|
|
121
|
+
raise Refusal(f"{text}: a cache-cell source takes row=<r> and kv<i> only")
|
|
122
|
+
if row is None:
|
|
123
|
+
raise Refusal(f"{text}: name the source row (row=<r>)")
|
|
124
|
+
if kv is not None and kv >= run.adapter.num_kv_heads:
|
|
125
|
+
raise Refusal(f"{text}: no KV head {kv}")
|
|
126
|
+
return Source(row, (layer,), None if kv is None else (kv,), text, (match["port"],))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def reader_rows(run: Any, source: Source, rows: str | None) -> list[int]:
|
|
130
|
+
"""Reader rows: the cursor's row by default; ``rows`` ``R``, ``A:B`` (half-open) or
|
|
131
|
+
``all`` (every stepped row from the source row to the cursor's row)."""
|
|
132
|
+
here = int(_ROW.match(run.where)["row"])
|
|
133
|
+
if rows is None:
|
|
134
|
+
found = [here]
|
|
135
|
+
elif rows == "all":
|
|
136
|
+
found = list(range(max(source.row, first_row(run)), here + 1))
|
|
137
|
+
elif re.fullmatch(r"\d+", rows):
|
|
138
|
+
found = [int(rows)]
|
|
139
|
+
elif re.fullmatch(r"\d+:\d+", rows):
|
|
140
|
+
low, high = map(int, rows.split(":"))
|
|
141
|
+
found = list(range(low, high))
|
|
142
|
+
else:
|
|
143
|
+
raise Refusal(f"rows is R, A:B or all, not {rows!r}")
|
|
144
|
+
if not found:
|
|
145
|
+
raise Refusal(f"rows={rows} names no row")
|
|
146
|
+
late = [r for r in found if r > here]
|
|
147
|
+
if late:
|
|
148
|
+
raise Refusal(f"t{late[0]} has not been computed at {run.where}")
|
|
149
|
+
early = [r for r in found if r < source.row]
|
|
150
|
+
if early:
|
|
151
|
+
raise Refusal(f"t{early[0]} cannot read t{source.row}: a row reads only itself and "
|
|
152
|
+
"earlier rows")
|
|
153
|
+
return found
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# --------------------------------------------------------------------------- reads
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass
|
|
160
|
+
class Reads:
|
|
161
|
+
"""A ``reads`` result: ``report`` (bounded JSON, every number labelled) and the float64
|
|
162
|
+
``tensors`` behind it (for in-process callers and tests)."""
|
|
163
|
+
|
|
164
|
+
report: dict[str, Any]
|
|
165
|
+
tensors: dict[str, Any]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _consumer_for(run: Any, consumer: Any, row: int, layer: int) -> Readout:
|
|
169
|
+
"""The declared consumer, or the default: ``o`` of the read's own row and layer."""
|
|
170
|
+
if consumer is None:
|
|
171
|
+
return readout(run, f"t{row}.L{layer}.o")
|
|
172
|
+
return readout(run, consumer)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _request(address: str, mask: Any, selection: str, target: Any) -> tuple[Any, Any]:
|
|
176
|
+
"""The what-if of one read: ``p`` at ``address`` set to 0 on ``mask``."""
|
|
177
|
+
from ..predict.plan import Edit
|
|
178
|
+
|
|
179
|
+
return (Edit(address, 0.0, "replace", mask, selection,
|
|
180
|
+
"remove the source's weight in this head"), target)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _verdict(result: Any, min_effect: float) -> dict[str, Any]:
|
|
184
|
+
"""The causal verdict of one read from its what-if ``result`` (a ``WhatIf``, or the
|
|
185
|
+
``Refusal`` the what-if gave before anything native ran)."""
|
|
186
|
+
if isinstance(result, Refusal):
|
|
187
|
+
return {"verdict": "unresolved", "reason": str(result)}
|
|
188
|
+
delta = f64(result.tensors["native_delta"]).reshape(-1)
|
|
189
|
+
bound = result.tensors.get("rounding_bound")
|
|
190
|
+
out: dict[str, Any] = {
|
|
191
|
+
"delta": result.report["measured"]["delta"],
|
|
192
|
+
"min_effect": num(float(min_effect), SUPPLIED),
|
|
193
|
+
"record": result.report["record"],
|
|
194
|
+
"dose": "p[h, src] = 0 (the source removed from this head; the other weights kept)",
|
|
195
|
+
}
|
|
196
|
+
prediction = result.report["prediction"]
|
|
197
|
+
out["predicted"] = (prediction["exact"]["value"] if prediction["state"] == "resolved"
|
|
198
|
+
else {"state": prediction["state"], "reason": prediction["reason"]})
|
|
199
|
+
emulated = prediction.get("emulated")
|
|
200
|
+
if emulated is not None: # the emulated change: what the verdict holds native against
|
|
201
|
+
out["emulated"] = (emulated["value"] if "value" in emulated
|
|
202
|
+
else {"state": emulated["state"], "reason": emulated["reason"]})
|
|
203
|
+
terms = {} if result.report["split"].get("state") == "refused" else {
|
|
204
|
+
t["name"]: t for t in result.report["split"]["terms"]}
|
|
205
|
+
term = terms.get("rounding effect") or terms.get("rounding") or {}
|
|
206
|
+
if "bound_note" in term: # no informative interval (cut, or at least |exact|): say why
|
|
207
|
+
out["bound_note"] = term["bound_note"]
|
|
208
|
+
elif bound is not None: # the worst-case interval bound: shown beside, never decides
|
|
209
|
+
out["rounding_bound"] = claim(f64(bound).reshape(-1).max(), BOUND)
|
|
210
|
+
effect = result.report["effect"]
|
|
211
|
+
out["effect"] = {key: value for key, value in effect.items() if key != "state"}
|
|
212
|
+
out.update(_decide(delta, effect, min_effect))
|
|
213
|
+
return out
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
_POOLED = {"causal": EFFECT, "not causal at this dose": NO_EFFECT}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _donor_verdicts(run: Any, entries: list[dict[str, Any]], requests: list[Any],
|
|
220
|
+
donors: Sequence[Any], min_effect: float) -> None:
|
|
221
|
+
"""Multi-donor mode (``donors.pooled``): each listed read's ``p[h, j, src]`` is set to each
|
|
222
|
+
donor run's weight at the same address (the donor must have computed it), measured like the
|
|
223
|
+
removal; ``causal.donors`` holds the pooled verdict and the per-donor rows."""
|
|
224
|
+
from ..numerics.pooling import pooled
|
|
225
|
+
from ..predict.plan import Edit
|
|
226
|
+
from ..predict.whatif import whatif_many
|
|
227
|
+
|
|
228
|
+
rows: list[list[dict[str, Any]]] = [[] for _ in entries]
|
|
229
|
+
for donor in donors:
|
|
230
|
+
batch, where = [], []
|
|
231
|
+
for i, (edit, target) in enumerate(requests):
|
|
232
|
+
try:
|
|
233
|
+
value = donor.read(edit.address)
|
|
234
|
+
except (ValueError, KeyError, IndexError) as error:
|
|
235
|
+
rows[i].append({"verdict": "unresolved", "informative": None,
|
|
236
|
+
"reason": f"the donor has no {edit.address}: {error}"})
|
|
237
|
+
continue
|
|
238
|
+
batch.append((Edit(edit.address, value, "replace", edit.mask, edit.selection,
|
|
239
|
+
f"donor {getattr(donor, 'name', '?')}"), target))
|
|
240
|
+
where.append(i)
|
|
241
|
+
for i, result in zip(where, whatif_many(run, batch, stages=False) if batch else [],
|
|
242
|
+
strict=True):
|
|
243
|
+
one = _verdict(result, min_effect)
|
|
244
|
+
known = ((one.get("effect") or {}).get("donors") or {}).get("informative", {})
|
|
245
|
+
rows[i].append({"verdict": _POOLED.get(one["verdict"], "unresolved"),
|
|
246
|
+
"informative": bool(known["value"]) if "value" in known else None,
|
|
247
|
+
"delta": one.get("delta")})
|
|
248
|
+
for entry, found in zip(entries, rows, strict=True):
|
|
249
|
+
entry["causal"]["donors"] = {**pooled(found), "per_donor": found,
|
|
250
|
+
"dose": "p[h, j, src] := the donor's weight there"}
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def verdict(run: Any, address: str, mask: Any, selection: str, target: Any,
|
|
254
|
+
min_effect: float) -> dict[str, Any]:
|
|
255
|
+
"""The causal verdict of one read: ``p`` at ``address`` set to 0 on ``mask`` through
|
|
256
|
+
``propagate.whatif`` (prediction sealed, measured natively, session restored)."""
|
|
257
|
+
from ..predict.whatif import whatif
|
|
258
|
+
|
|
259
|
+
try:
|
|
260
|
+
result = whatif(run, *_request(address, mask, selection, target))
|
|
261
|
+
except Refusal as error:
|
|
262
|
+
result = error
|
|
263
|
+
return _verdict(result, min_effect)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _decide(delta: Any, effect: dict[str, Any], min_effect: float) -> dict[str, Any]:
|
|
267
|
+
"""The read's verdict from whatif's P20 verdict ``effect`` (``verdict.decide``): ``causal``
|
|
268
|
+
on an effect beyond ``min_effect``; ``not causal at this dose`` on no effect (the reason
|
|
269
|
+
says the dtype shows no change and gives the exact change); else ``unresolved`` with the
|
|
270
|
+
whatif verdict and its reason (``not confirmed`` or ``unresolved``)."""
|
|
271
|
+
if effect["verdict"] == NO_EFFECT:
|
|
272
|
+
return {"verdict": "not causal at this dose",
|
|
273
|
+
"reason": effect.get("note", f"no change at {effect['dtype']} resolution")}
|
|
274
|
+
if effect["verdict"] == EFFECT:
|
|
275
|
+
if size(delta) <= min_effect:
|
|
276
|
+
return {"verdict": "unresolved", "reason": "changed, at or below min_effect"}
|
|
277
|
+
return {"verdict": "causal", **({"reason": effect["note"]} if "note" in effect else {})}
|
|
278
|
+
return {"verdict": "unresolved", "reason": f"whatif {effect['verdict']}: {effect['reason']}"}
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def reads(run: Any, source: str | Source, *, rows: str | None = None, consumer: Any = None,
|
|
282
|
+
top: int = 8, causal: bool = True, min_effect: float = 0.0,
|
|
283
|
+
donors: Sequence[Any] = ()) -> Reads:
|
|
284
|
+
"""The attention reads of ``source`` made at the reader rows (the cursor's row by default),
|
|
285
|
+
one entry per (reader row, layer, head), ranked by the size of the exact contribution to
|
|
286
|
+
the consumer (default: ``o`` of the read's own layer). The first ``top`` entries carry a
|
|
287
|
+
native causal verdict (``causal``); the rest are summed into ``omitted`` (count and sums).
|
|
288
|
+
Layers whose ``p`` has not been computed are listed under ``not_computed``."""
|
|
289
|
+
if not isinstance(source, Source):
|
|
290
|
+
source = parse_source(run, source)
|
|
291
|
+
if top < 1:
|
|
292
|
+
raise Refusal("top must be at least 1")
|
|
293
|
+
if not math.isfinite(min_effect) or min_effect < 0:
|
|
294
|
+
raise Refusal("min_effect must be a finite number >= 0")
|
|
295
|
+
found = reader_rows(run, source, rows)
|
|
296
|
+
layers = run.adapter.layers
|
|
297
|
+
entries: list[dict[str, Any]] = []
|
|
298
|
+
missing: list[str] = []
|
|
299
|
+
checks: list[dict[str, Any]] = []
|
|
300
|
+
weights: dict[int, Any] = {} # float64 o_proj by layer, for this call only
|
|
301
|
+
for j in found:
|
|
302
|
+
for layer in range(layers):
|
|
303
|
+
if source.layers is not None and layer not in source.layers:
|
|
304
|
+
continue
|
|
305
|
+
try:
|
|
306
|
+
mix = head_mix(run, j, layer, weights)
|
|
307
|
+
except Refusal as error:
|
|
308
|
+
missing.append(f"t{j}.L{layer}: {error}")
|
|
309
|
+
continue
|
|
310
|
+
checks.append(mix.checks())
|
|
311
|
+
try:
|
|
312
|
+
reader = _consumer_for(run, consumer, j, layer)
|
|
313
|
+
except Refusal as error:
|
|
314
|
+
reader = error
|
|
315
|
+
parts = mix.o_parts()
|
|
316
|
+
heads = [h for h in range(mix.p.shape[0]) if source.covers(layer, mix.kappa[h])]
|
|
317
|
+
for h in heads:
|
|
318
|
+
s = source.row
|
|
319
|
+
part = parts[h, s]
|
|
320
|
+
entry: dict[str, Any] = {
|
|
321
|
+
"name": f"t{j}.L{layer}.h{h}", "address": f"t{j}.L{layer}.p[h{h},src={s}]",
|
|
322
|
+
"row": j, "layer": layer,
|
|
323
|
+
"mass": num(float(mix.p[h, s]), source_label(run, mix, h, s)),
|
|
324
|
+
"to_head": {"norm": num(float(mix.source_parts()[h, s].norm()), EXACT,
|
|
325
|
+
"P06")},
|
|
326
|
+
}
|
|
327
|
+
blocked = edited_block(mix, run, h)
|
|
328
|
+
entry["to_o"] = refused(blocked) if blocked else claim(part, EXACT, "P07")
|
|
329
|
+
value = None
|
|
330
|
+
if isinstance(reader, Refusal):
|
|
331
|
+
entry["to_consumer"] = refused(str(reader))
|
|
332
|
+
elif blocked:
|
|
333
|
+
entry["to_consumer"] = refused(blocked)
|
|
334
|
+
elif reader.reaches(layer, "attn") is not None or reader.row != j:
|
|
335
|
+
why = reader.reaches(layer, "attn") or (
|
|
336
|
+
f"{reader.text} is in another row: t{j} reaches it only through the "
|
|
337
|
+
"cache (no additive path)")
|
|
338
|
+
entry["to_consumer"] = refused(why)
|
|
339
|
+
else:
|
|
340
|
+
value = reader.apply(part)
|
|
341
|
+
entry["to_consumer"] = claim(value, EXACT, "P19" if reader.scalar else "P07")
|
|
342
|
+
entry["_rank"] = -1.0 if value is None else size(value)
|
|
343
|
+
entry["_mask"] = (j, layer, h, s)
|
|
344
|
+
# an edit that blocks the value mix decides the verdict too: not measured
|
|
345
|
+
entry["_target"] = (None if isinstance(reader, Refusal) or blocked
|
|
346
|
+
else reader.target)
|
|
347
|
+
entry["_value"] = value
|
|
348
|
+
entries.append(entry)
|
|
349
|
+
weights.clear()
|
|
350
|
+
mix = parts = None # the last value mix is not needed by the verdicts' whatifs
|
|
351
|
+
entries.sort(key=lambda e: (-e["_rank"], e["row"], e["layer"], e["name"]))
|
|
352
|
+
listed, rest = entries[:top], entries[top:]
|
|
353
|
+
measured: list[dict[str, Any]] = []
|
|
354
|
+
requests = []
|
|
355
|
+
for entry in listed:
|
|
356
|
+
j, layer, h, s = entry["_mask"]
|
|
357
|
+
if not causal:
|
|
358
|
+
entry["causal"] = {"verdict": "unresolved", "reason": "causal=false: not measured"}
|
|
359
|
+
elif entry["_target"] is None:
|
|
360
|
+
entry["causal"] = {"verdict": "unresolved", "reason": entry["to_consumer"]["reason"]}
|
|
361
|
+
else:
|
|
362
|
+
measured.append(entry)
|
|
363
|
+
requests.append(_request(f"t{j}.L{layer}.p", head_mask(run, j, layer, h, s),
|
|
364
|
+
f"h{h},src={s}", entry["_target"]))
|
|
365
|
+
if requests: # one excursion for all the listed reads (the rewinds and the restore shared)
|
|
366
|
+
from ..predict.whatif import whatif_many
|
|
367
|
+
|
|
368
|
+
# the per-stage containment is not part of a read's verdict: not computed (M56c)
|
|
369
|
+
for entry, result in zip(measured, whatif_many(run, requests, stages=False),
|
|
370
|
+
strict=True):
|
|
371
|
+
entry["causal"] = _verdict(result, min_effect)
|
|
372
|
+
if donors:
|
|
373
|
+
_donor_verdicts(run, measured, requests, donors, min_effect)
|
|
374
|
+
report: dict[str, Any] = {
|
|
375
|
+
"source": {"row": source.row, "address": source.text or f"t{source.row}",
|
|
376
|
+
"token": int(run.tokens[source.row]) if source.row < len(run.tokens) else
|
|
377
|
+
None},
|
|
378
|
+
"rows": found,
|
|
379
|
+
"consumer": ("o of each read's layer (default)" if consumer is None
|
|
380
|
+
else getattr(consumer, "text", consumer)),
|
|
381
|
+
"reads": [_public(e) for e in listed],
|
|
382
|
+
"total": len(entries),
|
|
383
|
+
}
|
|
384
|
+
if report["source"]["token"] is None:
|
|
385
|
+
report["source"].pop("token")
|
|
386
|
+
if rest:
|
|
387
|
+
values = [e["_value"] for e in rest if e["_value"] is not None]
|
|
388
|
+
report["omitted"] = {
|
|
389
|
+
"count": len(rest),
|
|
390
|
+
"mass": num(sum(float(e["mass"]["value"]) for e in rest), EXACT),
|
|
391
|
+
"to_consumer": _omitted_sum(rest, values, consumer),
|
|
392
|
+
"meaning": f"+{len(rest)} more reads (ranked below the top {top}), summed",
|
|
393
|
+
}
|
|
394
|
+
report["checks"] = _check_summary(checks)
|
|
395
|
+
if missing:
|
|
396
|
+
report["not_computed"] = missing[:16]
|
|
397
|
+
if len(missing) > 16:
|
|
398
|
+
report["not_computed_total"] = len(missing)
|
|
399
|
+
return Reads(report, {"entries": entries})
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _omitted_sum(rest: list[dict[str, Any]], values: list[Any], consumer: Any) -> dict:
|
|
403
|
+
"""The omitted reads' summed contribution, only when they share one consumer (a declared
|
|
404
|
+
one, or by default ``o`` of one row and layer)."""
|
|
405
|
+
if not values:
|
|
406
|
+
return unresolved("no omitted read reaches the consumer")
|
|
407
|
+
if consumer is None and len({(e["row"], e["layer"]) for e in rest}) > 1:
|
|
408
|
+
return unresolved("the omitted reads have different consumers (o of their own layers): "
|
|
409
|
+
"their contributions do not add")
|
|
410
|
+
if len(values) < len(rest):
|
|
411
|
+
return unresolved("some omitted reads do not reach the consumer")
|
|
412
|
+
return claim(sum(values[1:], values[0]), EXACT)
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def source_label(run: Any, mix: HeadMix, head: int, source: int) -> str:
|
|
416
|
+
info = run.read_info(f"t{mix.row}.L{mix.layer}.p",
|
|
417
|
+
select=head_mask(run, mix.row, mix.layer, head, source))
|
|
418
|
+
return info["authority"] or MEASURED
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _public(entry: dict[str, Any]) -> dict[str, Any]:
|
|
422
|
+
return {k: v for k, v in entry.items() if not k.startswith("_")}
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _check_summary(checks: list[dict[str, Any]]) -> dict[str, Any]:
|
|
426
|
+
"""The value-mix (P06) and head-write (P07) identities over every (row, layer) visited:
|
|
427
|
+
the largest measured ``|eta|``, the largest ratio ``|eta| / bound`` and whether every
|
|
428
|
+
element is within its bound."""
|
|
429
|
+
out: dict[str, Any] = {}
|
|
430
|
+
for name in ("value_mix", "head_write"):
|
|
431
|
+
found = [c[name] for c in checks if name in c]
|
|
432
|
+
if not found:
|
|
433
|
+
out[name] = unresolved("not computed at the cursor (the port is past it)")
|
|
434
|
+
continue
|
|
435
|
+
failed = next((c["refused"] for c in found if c["bound"] is None), None)
|
|
436
|
+
if failed is not None:
|
|
437
|
+
out[name] = refused(failed)
|
|
438
|
+
continue
|
|
439
|
+
eta = max(float(c["eta"].abs().max()) for c in found)
|
|
440
|
+
ratio = max(float((c["eta"].abs() / c["bound"].clamp_min(1e-300)).max())
|
|
441
|
+
for c in found)
|
|
442
|
+
out[name] = {"eta_max_abs": num(eta, MEASURED, found[0]["proof"]),
|
|
443
|
+
"worst_ratio": num(ratio, MEASURED, found[0]["proof"]),
|
|
444
|
+
"within_bound": all(bool((c["eta"].abs() <= c["bound"]).all())
|
|
445
|
+
for c in found),
|
|
446
|
+
"count": len(found), "premises": found[0]["premises"]}
|
|
447
|
+
return out
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
# old private names, kept for one commit
|
|
451
|
+
_edited_block, _first_row, _label = edited_block, first_row, source_label
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
__all__ = ["Reads", "Source", "VERDICTS", "parse_source", "reader_rows", "reads", "source_label",
|
|
455
|
+
"verdict"]
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Batched native sweeps of state-cell edits at a run's pending row.
|
|
2
|
+
|
|
3
|
+
``cell_sweep(run, arms)`` measures many alternative versions of the key/value cache in one
|
|
4
|
+
native forward of the pending row per chunk: arm ``i`` is a list of cell replacements
|
|
5
|
+
``Cell(layer, "k"|"v", row, kv, value)``; the cache of batch element ``i`` is the run's prefill
|
|
6
|
+
cache with those cells replaced (the value cast once to the cache dtype), and the pending token
|
|
7
|
+
runs through the model's own forward (``model(token, past_key_values=cache)``), batch ``B``. It
|
|
8
|
+
is the batched form of ``Run.set_cell(layer, t, value, rows=[row], kv=[kv])`` followed by
|
|
9
|
+
``until logits`` from the first port of the pending row: the edited cells are read only by the
|
|
10
|
+
pending row (the prefill rows already ran), exactly as a staged cell is realised there.
|
|
11
|
+
|
|
12
|
+
Numerics: a batch-1 forward is the Hugging Face incremental program the stepped run equals
|
|
13
|
+
(tested on the tiny models). A batch of ``B > 1`` may round differently (another matmul
|
|
14
|
+
shape). Each chunk therefore carries a null arm (no edit) at batch index 0, and the result
|
|
15
|
+
reports ``null_vs_stepped``: the largest ``|logit|`` difference between that null arm and the
|
|
16
|
+
run's stepped native logits, measured, so a caller can put it into its noise floor.
|
|
17
|
+
|
|
18
|
+
Port patches (``PortPatch(layer, port, edit)``): an arm may also carry edits
|
|
19
|
+
of the native-module ports of the pending row (``a q k v n g sg u f A o m ...``: every port whose
|
|
20
|
+
program entry is a ``pre`` or ``out`` hook on a layer submodule, so not ``h``, ``r``, ``h_out``
|
|
21
|
+
or the eager-attention ports). ``edit`` is the engine's own ``PortEdit`` (value, op, mask); a
|
|
22
|
+
forward hook on that submodule applies it to batch element ``i`` only, as ``edit.apply`` on the
|
|
23
|
+
``(1, 1, ...)`` slice, i.e. the same cast-once, one-rounded-op arithmetic the stepped run
|
|
24
|
+
realises, with that arm's own mask. Edits of one arm at one port apply in the order given.
|
|
25
|
+
|
|
26
|
+
Labels: every returned logit is ``measured`` (native forward), under the edits of its arm.
|
|
27
|
+
Memory: one chunk's cache (``B`` copies of the prefill cache) and logits of the requested token
|
|
28
|
+
ids only; nothing else is kept.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import re
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
from typing import Any, Sequence
|
|
36
|
+
|
|
37
|
+
from ..predict.consumers import Refusal
|
|
38
|
+
|
|
39
|
+
_ROW = re.compile(r"t(?P<row>\d+)\.L0\.")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Cell:
|
|
44
|
+
"""One cell replacement: ``cache.L<layer>.<tensor>[kv<kv>, row=<row>]`` = ``value``
|
|
45
|
+
(a tensor of ``head_dim`` values)."""
|
|
46
|
+
|
|
47
|
+
layer: int
|
|
48
|
+
tensor: str
|
|
49
|
+
row: int
|
|
50
|
+
kv: int
|
|
51
|
+
value: Any
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class PortPatch:
|
|
56
|
+
"""One port edit of the pending row at ``layer``: ``edit`` is an ``engine.ports.PortEdit``
|
|
57
|
+
whose value/mask have the port's ``(1, 1, ...)`` shape (the stepped run's)."""
|
|
58
|
+
|
|
59
|
+
layer: int
|
|
60
|
+
port: str
|
|
61
|
+
edit: Any
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _port_ok(program: Any, port: str) -> Any:
|
|
65
|
+
"""The program entry of ``port`` when a batched hook can realise an edit there."""
|
|
66
|
+
spec = program.spec(port)
|
|
67
|
+
if not spec.editable or spec.hook not in ("pre", "out") or not spec.site or port == "r":
|
|
68
|
+
ok = [p.name for p in program.ports
|
|
69
|
+
if p.editable and p.hook in ("pre", "out") and p.site and p.name != "r"]
|
|
70
|
+
raise Refusal(f"a batched port edit needs a native-module port ({', '.join(ok)}), "
|
|
71
|
+
f"not {port}")
|
|
72
|
+
return spec
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _hooks(adapter: Any, items: dict[tuple[int, str], list[tuple[int, Any]]], program: Any):
|
|
76
|
+
"""Forward hooks that apply each (layer, port)'s edits to their batch elements."""
|
|
77
|
+
from mdb.engine.ports import _module
|
|
78
|
+
|
|
79
|
+
handles = []
|
|
80
|
+
for (layer, port), todo in items.items():
|
|
81
|
+
spec = program.spec(port)
|
|
82
|
+
module = _module(adapter._layer_modules[layer], spec.site)
|
|
83
|
+
|
|
84
|
+
def apply(x, todo=todo):
|
|
85
|
+
out = x.clone()
|
|
86
|
+
for index, edit in todo:
|
|
87
|
+
out[index:index + 1] = edit.apply(out[index:index + 1])
|
|
88
|
+
return out
|
|
89
|
+
|
|
90
|
+
if spec.hook == "pre":
|
|
91
|
+
handles.append(module.register_forward_pre_hook(
|
|
92
|
+
lambda m, args, apply=apply: (apply(args[0]), *args[1:])))
|
|
93
|
+
else:
|
|
94
|
+
handles.append(module.register_forward_hook(
|
|
95
|
+
lambda m, args, output, apply=apply: apply(output)))
|
|
96
|
+
return handles
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _check(run: Any) -> int:
|
|
100
|
+
"""The pending row, after refusing a cursor that is not at the pending row's first port or a
|
|
101
|
+
run that carries edits (the sweep starts from the native prefill cache)."""
|
|
102
|
+
first = run.program.names[0]
|
|
103
|
+
match = _ROW.match(run.where)
|
|
104
|
+
if match is None or not run.where.endswith(f".L0.{first}"):
|
|
105
|
+
raise Refusal(f"cell_sweep needs the cursor at the pending row's first port "
|
|
106
|
+
f"(t<row>.L0.{first}, where start leaves it), not {run.where}")
|
|
107
|
+
if run.edits or run.cells or run.committed_cells() or run.committed_edits():
|
|
108
|
+
raise Refusal("cell_sweep starts from the native prefill cache: the run carries edits")
|
|
109
|
+
row = int(match["row"])
|
|
110
|
+
if row != len(run.tokens) - 1:
|
|
111
|
+
raise Refusal("cell_sweep runs the last prompt row only")
|
|
112
|
+
return row
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def cell_sweep(run: Any, arms: Sequence[Sequence[Cell]], *, tokens: Sequence[int] | None = None,
|
|
116
|
+
batch: int = 64, stepped_logits: Any = None) -> dict[str, Any]:
|
|
117
|
+
"""Logits of the pending row under each arm's cell replacements, measured natively in
|
|
118
|
+
batches of ``batch`` (index 0 of every chunk is a null arm, not counted in ``batch``).
|
|
119
|
+
|
|
120
|
+
``tokens``: vocabulary ids to return (default: all). ``stepped_logits``: the run's own
|
|
121
|
+
native logits at the pending row (to report ``null_vs_stepped``); when omitted the run is
|
|
122
|
+
not moved and the check is not made.
|
|
123
|
+
|
|
124
|
+
Returns ``{"logits": float32 tensor (len(arms), len(tokens)), "argmax": long (len(arms),),
|
|
125
|
+
"null": float32 (chunks, len(tokens)), "null_vs_stepped": float or None, "batches": n}``.
|
|
126
|
+
"""
|
|
127
|
+
import torch
|
|
128
|
+
from transformers import DynamicCache
|
|
129
|
+
|
|
130
|
+
row = _check(run)
|
|
131
|
+
if batch < 1:
|
|
132
|
+
raise Refusal("batch must be at least 1")
|
|
133
|
+
adapter = run.adapter
|
|
134
|
+
model = adapter.model
|
|
135
|
+
layers = adapter.layers
|
|
136
|
+
keys = [run.read_cache(layer, "k", staged=False) for layer in range(layers)]
|
|
137
|
+
values = [run.read_cache(layer, "v", staged=False) for layer in range(layers)]
|
|
138
|
+
length = int(keys[0].shape[2])
|
|
139
|
+
if length != row:
|
|
140
|
+
raise Refusal(f"the cache holds {length} rows, the pending row is t{row}")
|
|
141
|
+
from mdb.engine.ports import program_for
|
|
142
|
+
|
|
143
|
+
program = program_for(adapter)
|
|
144
|
+
for arm in arms:
|
|
145
|
+
for cell in arm:
|
|
146
|
+
if isinstance(cell, PortPatch):
|
|
147
|
+
if not 0 <= cell.layer < layers:
|
|
148
|
+
raise Refusal(f"no layer {cell.layer} for port {cell.port}")
|
|
149
|
+
_port_ok(program, cell.port)
|
|
150
|
+
cell.edit.validate(program.shape(cell.port, adapter.model.config, src=row + 1))
|
|
151
|
+
continue
|
|
152
|
+
if cell.tensor not in ("k", "v"):
|
|
153
|
+
raise Refusal("a cell is k or v")
|
|
154
|
+
if not (0 <= cell.layer < layers and 0 <= cell.row < row
|
|
155
|
+
and 0 <= cell.kv < adapter.num_kv_heads):
|
|
156
|
+
raise Refusal(f"no cell cache.L{cell.layer}.{cell.tensor}"
|
|
157
|
+
f"[kv{cell.kv},row={cell.row}] before t{row}")
|
|
158
|
+
if int(cell.value.numel()) != adapter.head_dim:
|
|
159
|
+
raise Refusal(f"a cell value has {adapter.head_dim} values, got "
|
|
160
|
+
f"{int(cell.value.numel())}")
|
|
161
|
+
device = keys[0].device
|
|
162
|
+
pick = None if tokens is None else torch.tensor(list(tokens), dtype=torch.long, device=device)
|
|
163
|
+
token = int(run.tokens[row])
|
|
164
|
+
out, argmax, nulls = [], [], []
|
|
165
|
+
with torch.no_grad():
|
|
166
|
+
for start in range(0, len(arms), batch):
|
|
167
|
+
chunk = [[]] + [list(arm) for arm in arms[start:start + batch]]
|
|
168
|
+
size = len(chunk)
|
|
169
|
+
cache = DynamicCache(config=model.config)
|
|
170
|
+
items: dict[tuple[int, str], list[tuple[int, Any]]] = {}
|
|
171
|
+
for index, arm in enumerate(chunk):
|
|
172
|
+
for cell in arm:
|
|
173
|
+
if isinstance(cell, PortPatch):
|
|
174
|
+
items.setdefault((cell.layer, cell.port), []).append((index, cell.edit))
|
|
175
|
+
for layer in range(layers):
|
|
176
|
+
k = keys[layer].expand(size, -1, -1, -1).clone()
|
|
177
|
+
v = values[layer].expand(size, -1, -1, -1).clone()
|
|
178
|
+
for index, arm in enumerate(chunk):
|
|
179
|
+
for cell in arm:
|
|
180
|
+
if isinstance(cell, PortPatch) or cell.layer != layer:
|
|
181
|
+
continue
|
|
182
|
+
target = k if cell.tensor == "k" else v
|
|
183
|
+
target[index, cell.kv, cell.row] = cell.value.reshape(-1).to(
|
|
184
|
+
device=device, dtype=target.dtype)
|
|
185
|
+
cache.update(k, v, layer)
|
|
186
|
+
ids = torch.full((size, 1), token, dtype=torch.long, device=device)
|
|
187
|
+
handles = _hooks(adapter, items, program)
|
|
188
|
+
try:
|
|
189
|
+
logits = model(ids, past_key_values=cache, use_cache=True).logits[:, -1]
|
|
190
|
+
finally:
|
|
191
|
+
for handle in handles:
|
|
192
|
+
handle.remove()
|
|
193
|
+
del cache
|
|
194
|
+
chosen = logits if pick is None else logits.index_select(1, pick)
|
|
195
|
+
argmax.append(logits.argmax(dim=-1)[1:].cpu())
|
|
196
|
+
out.append(chosen[1:].float().cpu())
|
|
197
|
+
nulls.append(chosen[0].float().cpu())
|
|
198
|
+
del logits
|
|
199
|
+
result: dict[str, Any] = {
|
|
200
|
+
"logits": torch.cat(out) if out else torch.zeros(0),
|
|
201
|
+
"argmax": torch.cat(argmax) if argmax else torch.zeros(0, dtype=torch.long),
|
|
202
|
+
"null": torch.stack(nulls) if nulls else torch.zeros(0),
|
|
203
|
+
"batches": len(out),
|
|
204
|
+
"null_vs_stepped": None,
|
|
205
|
+
"authority": "measured",
|
|
206
|
+
}
|
|
207
|
+
if stepped_logits is not None and nulls:
|
|
208
|
+
native = stepped_logits.reshape(-1)
|
|
209
|
+
native = native if pick is None else native.index_select(0, pick.to(native.device))
|
|
210
|
+
native = native.float().cpu()
|
|
211
|
+
result["null_vs_stepped"] = float(max((n - native).abs().max() for n in nulls))
|
|
212
|
+
return result
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
__all__ = ["Cell", "PortPatch", "cell_sweep"]
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Numerics: authority labels, the proof-series identities (``finite``), accumulation
|
|
2
|
+
precision, verdict floors, stability margins, unit attribution and summaries.
|
|
3
|
+
|
|
4
|
+
Lowest analysis sublayer (``numerics < predict < measure < circuits < symbols < features``):
|
|
5
|
+
its modules import nothing from the other analysis sublayers at module level.
|
|
6
|
+
"""
|