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,840 @@
|
|
|
1
|
+
"""What-if: measure natively the change an edit makes in a consumer, beside its prediction.
|
|
2
|
+
|
|
3
|
+
``whatif`` stages the edit, predicts the consumer's change (``propagate``), measures it
|
|
4
|
+
natively from the same checkpoint (``stage``/``guard`` restore the session exactly), and
|
|
5
|
+
reports both with the P20 verdict; ``whatif_many`` measures several edits in one batch.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from mdb.core.bounded import MAX_ITEMS, bound_list, load_json
|
|
14
|
+
from mdb.core.kinds import procedure
|
|
15
|
+
from mdb.core.records import num, seal_record
|
|
16
|
+
|
|
17
|
+
from ..numerics.accumulation import bound_state
|
|
18
|
+
from ..numerics.labels import BOUND, EXACT, LOCAL, MEASURED, SUPPLIED, f64
|
|
19
|
+
from ..numerics.verdict import FLOOR_SPACINGS, NOT_CONFIRMED, decide, magnitude, spacing
|
|
20
|
+
from .consumers import Refusal, run_session_id
|
|
21
|
+
from .plan import Edit, Plan, plan, state_digest
|
|
22
|
+
from .propagate import (
|
|
23
|
+
WRITE_PREMISE,
|
|
24
|
+
_cell_writer,
|
|
25
|
+
_chain,
|
|
26
|
+
_consumer_value,
|
|
27
|
+
_emulated_edited,
|
|
28
|
+
_port_edits,
|
|
29
|
+
_predict,
|
|
30
|
+
_torch,
|
|
31
|
+
)
|
|
32
|
+
from .rowmodel import EMULATION_PREMISE, EMULATION_PREMISES, EmulatedRowModel, RowModel, _split
|
|
33
|
+
from .verify import containment, stage_checks, stage_parting
|
|
34
|
+
|
|
35
|
+
SCHEMA = "mdb-whatif-v1"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def stage(run: Any, edit: Edit) -> dict[str, Any]:
|
|
39
|
+
"""Stage ``edit`` on ``run`` at the cursor (``Run.set`` at its port, or ``Run.set_cell`` for
|
|
40
|
+
a state-cell edit); returns the engine's manifest."""
|
|
41
|
+
if edit.cell is None:
|
|
42
|
+
return run.set(edit.address, edit.value, edit.op, mask=edit.mask,
|
|
43
|
+
selection=edit.selection, origin=edit.origin)
|
|
44
|
+
cell = edit.cell
|
|
45
|
+
return run.set_cell(int(cell["layer"]), cell["tensor"], edit.value, edit.op,
|
|
46
|
+
rows=cell["rows"], kv=cell.get("kv"), d=cell.get("d"), dose=edit.dose,
|
|
47
|
+
selection=edit.selection, origin=edit.origin)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def guard(run: Any, checkpoint: dict[str, Any]) -> None:
|
|
51
|
+
"""Hold every edit tensor the checkpoint names so ``restore`` can rebuild it; refuse, before
|
|
52
|
+
anything native runs, a checkpoint naming a tensor this run does not hold."""
|
|
53
|
+
held = run.edit_tensors()
|
|
54
|
+
manifests = [*checkpoint["edits"], *(m for item in checkpoint["path_edits"]
|
|
55
|
+
for m in item["edits"])]
|
|
56
|
+
for manifest in manifests:
|
|
57
|
+
needed = [manifest["value"].get("sha256"), manifest.get("mask_sha256")]
|
|
58
|
+
missing = [sha for sha in needed if sha is not None and sha not in held]
|
|
59
|
+
if missing:
|
|
60
|
+
raise Refusal(f"the session cannot be restored after the what-if: edit tensor "
|
|
61
|
+
f"{missing[0][:12]} at {manifest['port']} is not held by this run")
|
|
62
|
+
run.hold(held)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _complete_restore(run: Any, checkpoint: dict[str, Any], state: list[bool]) -> None:
|
|
66
|
+
"""``run.restore(checkpoint)`` that completes whatever interrupts it, then re-raises the
|
|
67
|
+
interrupt (``state[0]`` is set once the restore has completed)."""
|
|
68
|
+
interrupted = None
|
|
69
|
+
while True:
|
|
70
|
+
try:
|
|
71
|
+
run.restore(checkpoint, defer_interrupt=True)
|
|
72
|
+
break
|
|
73
|
+
except KeyboardInterrupt as error: # before the restore ran, or inside it
|
|
74
|
+
interrupted = error
|
|
75
|
+
state[0] = True
|
|
76
|
+
if interrupted is not None:
|
|
77
|
+
raise interrupted
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _restoring(run: Any, checkpoint: dict[str, Any], body: Any) -> Any:
|
|
81
|
+
"""``body()``, then ``checkpoint`` restored whatever happens, interrupts included: the
|
|
82
|
+
restore is unconditional, so an interrupt landing exactly at the entry of the ``finally``
|
|
83
|
+
(before its first statement) still finds the restore done before it propagates. An interrupt
|
|
84
|
+
during the restore cannot roll it back to the edited excursion either."""
|
|
85
|
+
state = [False]
|
|
86
|
+
try:
|
|
87
|
+
try:
|
|
88
|
+
return body()
|
|
89
|
+
finally:
|
|
90
|
+
_complete_restore(run, checkpoint, state)
|
|
91
|
+
except KeyboardInterrupt:
|
|
92
|
+
if not state[0]:
|
|
93
|
+
_complete_restore(run, checkpoint, state)
|
|
94
|
+
raise
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _check(run: Any, out: dict[str, Any], side: str) -> None:
|
|
98
|
+
"""Run the what-if's check of ``side`` (``edited`` or ``base``) while the native state of
|
|
99
|
+
that run is at the consumer (``_checker``)."""
|
|
100
|
+
check = out.get("check")
|
|
101
|
+
if check is not None:
|
|
102
|
+
out[f"check_{side}"] = check(run, side, out[side])
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _measure_cell(run: Any, p: Plan, edit: Edit, checkpoint: dict[str, Any],
|
|
106
|
+
check: Any = None) -> dict[str, Any]:
|
|
107
|
+
"""``_measure`` of a state-cell edit: staged at ``p.stage_at``; ``realised`` is the cache
|
|
108
|
+
tensor the native layer call wrote, read back at the consumer."""
|
|
109
|
+
layer, tensor = int(edit.cell["layer"]), edit.cell["tensor"]
|
|
110
|
+
out: dict[str, Any] = {"moves": [], "check": check}
|
|
111
|
+
|
|
112
|
+
def edited() -> None:
|
|
113
|
+
stage(run, edit)
|
|
114
|
+
out["moves"].append(f"set {edit.address} at {run.where}")
|
|
115
|
+
run.until(p.consumer_stop)
|
|
116
|
+
out["moves"].append(f"until {p.consumer_stop}")
|
|
117
|
+
out["edited"] = run.read(p.consumer_stop).clone()
|
|
118
|
+
out["edited_info"] = run.read_info(p.consumer_stop)
|
|
119
|
+
out["realised"] = run.read_cache(layer, tensor, staged=False).clone()
|
|
120
|
+
_check(run, out, "edited")
|
|
121
|
+
|
|
122
|
+
def body() -> None:
|
|
123
|
+
if p.mode == "pending": # the consumer is ahead: edited branch first, then the base
|
|
124
|
+
edited()
|
|
125
|
+
run.restore(checkpoint)
|
|
126
|
+
out["moves"].append(f"restore {checkpoint['where']}")
|
|
127
|
+
_base_ahead(run, p, edit, out)
|
|
128
|
+
return
|
|
129
|
+
out["base"] = run.read(p.consumer_stop).clone()
|
|
130
|
+
out["base_info"] = run.read_info(p.consumer_stop)
|
|
131
|
+
_check(run, out, "base") # the unedited run already stands past the consumer
|
|
132
|
+
while run.parse(run.where) >= run.parse(p.stage_at):
|
|
133
|
+
run.reverse_step("layer")
|
|
134
|
+
out["moves"].append(f"reverse-step layer to {run.where}")
|
|
135
|
+
if run.where != p.stage_at:
|
|
136
|
+
run.until(p.stage_at)
|
|
137
|
+
out["moves"].append(f"until {p.stage_at}")
|
|
138
|
+
edited()
|
|
139
|
+
|
|
140
|
+
_restoring(run, checkpoint, body)
|
|
141
|
+
out["moves"].append(f"restore {checkpoint['where']}")
|
|
142
|
+
return out
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _measure(run: Any, p: Plan, edit: Edit, checkpoint: dict[str, Any],
|
|
146
|
+
check: Any = None) -> dict[str, Any]:
|
|
147
|
+
"""Native consumer values without and with the edit, the value the edit wrote, and the
|
|
148
|
+
native-call trail; restores ``checkpoint`` whatever happens. ``check(run, side, value)``
|
|
149
|
+
(``_checker``) runs while each native run is at the consumer."""
|
|
150
|
+
if edit.cell is not None:
|
|
151
|
+
return _measure_cell(run, p, edit, checkpoint, check)
|
|
152
|
+
layer = _split(p.label)[0]
|
|
153
|
+
entry = f"t{p.row}.L{layer}.h"
|
|
154
|
+
out: dict[str, Any] = {"moves": [], "check": check}
|
|
155
|
+
|
|
156
|
+
def body() -> None:
|
|
157
|
+
if p.consumer_key > p.here: # edited branch first, then the base and its exact chain
|
|
158
|
+
_edited(run, p, edit, entry, out)
|
|
159
|
+
run.restore(checkpoint)
|
|
160
|
+
out["moves"].append(f"restore {checkpoint['where']}")
|
|
161
|
+
_base_ahead(run, p, edit, out)
|
|
162
|
+
return
|
|
163
|
+
out["base"] = run.read(p.consumer_stop).clone()
|
|
164
|
+
out["base_info"] = run.read_info(p.consumer_stop)
|
|
165
|
+
_check(run, out, "base") # the unedited run already stands past the consumer
|
|
166
|
+
out["base_port"] = _base_port(run, p)
|
|
167
|
+
_edited(run, p, edit, entry, out)
|
|
168
|
+
|
|
169
|
+
_restoring(run, checkpoint, body)
|
|
170
|
+
out["moves"].append(f"restore {checkpoint['where']}")
|
|
171
|
+
return out
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _base_ahead(run: Any, p: Plan, edit: Edit, out: dict[str, Any]) -> None:
|
|
175
|
+
"""From the checkpoint, with the consumer ahead of it: run the unedited branch to the
|
|
176
|
+
consumer, read it, and compute there (every operand of the chain now measured) the exact
|
|
177
|
+
change on measured operands (``out["posthoc"]``, ``_measured_exact``; the edited branch has
|
|
178
|
+
already put the written operand in ``out["realised"]``). Runs after the prediction was
|
|
179
|
+
sealed, so nothing it computes is presented as sealed."""
|
|
180
|
+
run.until(p.consumer_stop)
|
|
181
|
+
out["moves"].append(f"until {p.consumer_stop}")
|
|
182
|
+
out["base"] = run.read(p.consumer_stop).clone()
|
|
183
|
+
out["base_info"] = run.read_info(p.consumer_stop)
|
|
184
|
+
_check(run, out, "base")
|
|
185
|
+
out["base_port"] = _base_port(run, p)
|
|
186
|
+
out["posthoc"] = _measured_exact(run, p, edit, out["realised"])
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _base_port(run: Any, p: Plan) -> Any:
|
|
190
|
+
"""The unedited run's value at the edited port (None when it cannot be read): what
|
|
191
|
+
``donors.informative`` compares the written value with."""
|
|
192
|
+
try:
|
|
193
|
+
return run.read(p.edit_stop).clone()
|
|
194
|
+
except (ValueError, KeyError, IndexError, RuntimeError):
|
|
195
|
+
return None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _written_exact(run: Any, p: Plan, edit: Edit, found: dict[str, Any], realised: Any
|
|
199
|
+
) -> dict[str, Any]:
|
|
200
|
+
"""The exact change with the operand the edit wrote (``realised``, read back natively) on
|
|
201
|
+
the operands of ``found``'s chains: ``at_realised`` (its consumer minus ``found["base"]``),
|
|
202
|
+
its rounding ``spread`` (None when unbounded) and ``spread_reason``."""
|
|
203
|
+
torch = _torch()
|
|
204
|
+
if edit.cell is not None:
|
|
205
|
+
chain = _chain(run, p, bounds=True, skip=True,
|
|
206
|
+
cell=_cell_writer(edit, realised, "written"))
|
|
207
|
+
else:
|
|
208
|
+
written = f64(realised).reshape(found["edit_shape"])
|
|
209
|
+
chain = _chain(run, p, bounds=True, skip=True,
|
|
210
|
+
overrides={p.label: lambda value, bound: (written,
|
|
211
|
+
torch.zeros_like(written))})
|
|
212
|
+
value, bound = _consumer_value(p, chain[-1])
|
|
213
|
+
return {"at_realised": value - found["base"],
|
|
214
|
+
"spread": None if bound is None or found["base_bound"] is None else (
|
|
215
|
+
bound + found["base_bound"]),
|
|
216
|
+
"spread_reason": _realised_reason(p, chain[-1], found),
|
|
217
|
+
"spread_broken": next((m.broken for m in chain if m.broken is not None),
|
|
218
|
+
found.get("broken")),
|
|
219
|
+
"spread_wide": next((m.wide for m in chain if m.wide is not None),
|
|
220
|
+
found.get("wide"))}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _measured_exact(run: Any, p: Plan, edit: Edit, realised: Any) -> dict[str, Any]:
|
|
224
|
+
"""The exact chains again with the cursor at (or past) the consumer, so every operand they
|
|
225
|
+
read is the native value of the unedited run: ``base``, ``exact`` and bounds (requested
|
|
226
|
+
operand) and ``at_realised`` (written operand), or ``reason``. P09 section 1 / P20 define
|
|
227
|
+
``native delta = F(x1) - F(x0) + residual`` on the retained operands; before the native run
|
|
228
|
+
those operands past the cursor exist only as the chain's own forecast."""
|
|
229
|
+
from dataclasses import replace
|
|
230
|
+
|
|
231
|
+
q = replace(p, here=run.parse(run.where))
|
|
232
|
+
try:
|
|
233
|
+
post = _predict(run, q, edit, linear=False, emulate=False)
|
|
234
|
+
except Refusal as error:
|
|
235
|
+
return {"reason": str(error)}
|
|
236
|
+
if post.get("reason") is None:
|
|
237
|
+
post.update(_written_exact(run, q, edit, post, realised))
|
|
238
|
+
return post
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _edited(run: Any, p: Plan, edit: Edit, entry: str, out: dict[str, Any],
|
|
242
|
+
cut: dict[str, Any] | None = None, keep: bool = False) -> dict[str, Any] | None:
|
|
243
|
+
"""From the current cursor: reach ``entry`` (the layer's entry: back by layer boundaries in
|
|
244
|
+
``rewind`` mode, forward otherwise, or ``restore(cut)`` of a checkpoint taken at it), stage
|
|
245
|
+
the edit, run to the consumer and read the edited value and the value the edit wrote into
|
|
246
|
+
``out``. With ``keep``, returns the checkpoint at ``entry`` taken before the edit (``cut``
|
|
247
|
+
itself when given): restoring it drops the edit and keeps the edits committed at that layer, which
|
|
248
|
+
stepping back stages again."""
|
|
249
|
+
if cut is not None:
|
|
250
|
+
run.restore(cut)
|
|
251
|
+
out["moves"].append(f"restore the cut at {entry}")
|
|
252
|
+
elif p.mode == "rewind":
|
|
253
|
+
while run.parse(run.where) >= run.parse(entry):
|
|
254
|
+
run.reverse_step("layer")
|
|
255
|
+
out["moves"].append(f"reverse-step layer to {run.where}")
|
|
256
|
+
if p.mode != "pending" and run.where != entry:
|
|
257
|
+
run.until(entry)
|
|
258
|
+
out["moves"].append(f"until {entry}")
|
|
259
|
+
cut = cut or (run.checkpoint() if keep else None)
|
|
260
|
+
run.set(p.edit_stop, edit.value, edit.op, mask=edit.mask, selection=edit.selection,
|
|
261
|
+
origin=edit.origin)
|
|
262
|
+
out["moves"].append(f"set {p.edit_stop}")
|
|
263
|
+
if run.parse(run.where) < p.consumer_key:
|
|
264
|
+
run.until(p.consumer_stop)
|
|
265
|
+
out["moves"].append(f"until {p.consumer_stop}")
|
|
266
|
+
out["edited"] = run.read(p.consumer_stop).clone()
|
|
267
|
+
out["edited_info"] = run.read_info(p.consumer_stop)
|
|
268
|
+
out["realised"] = run.read(p.edit_stop).clone()
|
|
269
|
+
_check(run, out, "edited")
|
|
270
|
+
return cut
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _measure_batch(run: Any, items: list[_Prepared]) -> list[dict[str, Any]]:
|
|
274
|
+
"""``_measure`` of several prepared what-ifs made at the same cursor, in one excursion.
|
|
275
|
+
|
|
276
|
+
A what-if in ``rewind`` mode with the consumer at or before the cursor starts from
|
|
277
|
+
a clean boundary of the original run, and the trail's marks below an edit are untouched by
|
|
278
|
+
it: so they are measured from the latest entry to the earliest, each stepping back by layer
|
|
279
|
+
boundaries from where the previous one ended, and the cursor is restored once at the end
|
|
280
|
+
(the replay from the earliest entry) instead of after every one. The consumer's unedited
|
|
281
|
+
value is read at the cursor before the first leaves it. The other what-ifs are measured one
|
|
282
|
+
by one, first. Returns the native measurements in the order of ``items``; the session is
|
|
283
|
+
restored whatever happens."""
|
|
284
|
+
checkpoint = items[0].checkpoint
|
|
285
|
+
results: list[dict[str, Any] | None] = [None] * len(items)
|
|
286
|
+
batch = []
|
|
287
|
+
for i, item in enumerate(items):
|
|
288
|
+
if (item.edit.cell is None and item.p.mode == "rewind"
|
|
289
|
+
and item.p.consumer_key <= item.p.here):
|
|
290
|
+
batch.append(i)
|
|
291
|
+
else:
|
|
292
|
+
results[i] = _measure(run, item.p, item.edit, item.checkpoint, item.check)
|
|
293
|
+
base = {i: (run.read(items[i].p.consumer_stop).clone(),
|
|
294
|
+
run.read_info(items[i].p.consumer_stop), _base_port(run, items[i].p))
|
|
295
|
+
for i in batch}
|
|
296
|
+
# the unedited run stands past every batched consumer: check its stages there, as `_measure`
|
|
297
|
+
checked = {i: items[i].check(run, "base", base[i][0]) for i in batch
|
|
298
|
+
if items[i].check is not None}
|
|
299
|
+
entries = {i: f"t{items[i].p.row}.L{_split(items[i].p.label)[0]}.h" for i in batch}
|
|
300
|
+
batch.sort(key=lambda i: (run.parse(entries[i]), i), reverse=True)
|
|
301
|
+
|
|
302
|
+
def body() -> None:
|
|
303
|
+
cuts: dict[str, dict[str, Any]] = {} # entry -> checkpoint there (several heads per layer)
|
|
304
|
+
for i in batch:
|
|
305
|
+
out: dict[str, Any] = {"moves": [], "base": base[i][0], "base_info": base[i][1],
|
|
306
|
+
"base_port": base[i][2], "check": items[i].check}
|
|
307
|
+
if i in checked:
|
|
308
|
+
out["check_base"] = checked[i]
|
|
309
|
+
cuts[entries[i]] = _edited(run, items[i].p, items[i].edit, entries[i], out,
|
|
310
|
+
cuts.get(entries[i]), keep=True)
|
|
311
|
+
results[i] = out
|
|
312
|
+
|
|
313
|
+
if batch:
|
|
314
|
+
_restoring(run, checkpoint, body)
|
|
315
|
+
for i in batch:
|
|
316
|
+
results[i]["moves"].append(f"restore {checkpoint['where']}")
|
|
317
|
+
return results
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def whatif_many(run: Any, requests: list[tuple[Edit, Any]], *, store: Any = None,
|
|
321
|
+
stages: bool = True) -> list[WhatIf | Refusal]:
|
|
322
|
+
"""``whatif`` of each ``(edit, consumer)`` at the cursor, measured in one excursion: the
|
|
323
|
+
predictions are sealed first (each needs the cursor's values), the native measurements share
|
|
324
|
+
their rewinds and one final restore (``_measure_batch``), and each is then split and judged
|
|
325
|
+
at the cursor again. Every result is the one ``whatif`` returns, number for number (the
|
|
326
|
+
``measured.moves`` trail names the shared steps); a request ``whatif`` refuses before
|
|
327
|
+
anything native runs comes back as its ``Refusal``. ``stages`` False: no per-stage
|
|
328
|
+
containment in the reports (a caller that drops it; the checks then run only where emulated
|
|
329
|
+
and native part beyond the floor, which the verdict needs), saving their layer probes."""
|
|
330
|
+
before = state_digest(run)
|
|
331
|
+
prepared: list[_Prepared | Refusal] = []
|
|
332
|
+
shared: dict = {} # the emulated base chains, shared by the what-ifs of this call
|
|
333
|
+
for edit, consumer in requests:
|
|
334
|
+
try:
|
|
335
|
+
prepared.append(_prepare(run, edit, consumer, before=before, store=store,
|
|
336
|
+
shared=shared, stages=stages))
|
|
337
|
+
except Refusal as error:
|
|
338
|
+
prepared.append(error)
|
|
339
|
+
shared.clear() # nothing wider than the call: the row models go here
|
|
340
|
+
ready = [item for item in prepared if isinstance(item, _Prepared)]
|
|
341
|
+
natives = iter(_measure_batch(run, ready) if ready else [])
|
|
342
|
+
after = state_digest(run) if ready else before
|
|
343
|
+
return [item if isinstance(item, Refusal) else _finish(run, item, next(natives), after)
|
|
344
|
+
for item in prepared]
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
# --------------------------------------------------------------------------- report
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _scalar(p: Plan, value: Any) -> Any:
|
|
351
|
+
"""The consumer's float64 value from the tensor read at its stop (index, then cast)."""
|
|
352
|
+
flat = value.reshape(-1)
|
|
353
|
+
if p.margin is not None:
|
|
354
|
+
return f64(flat[p.margin.a]) - f64(flat[p.margin.b])
|
|
355
|
+
if p.logit is not None:
|
|
356
|
+
return f64(flat[p.logit.i])
|
|
357
|
+
return f64(flat)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _claim(value: Any, authority: str, proof: str | None = None) -> dict[str, Any]:
|
|
361
|
+
"""One labelled number for a scalar; ``{max_abs, norm}`` (both labelled) for a vector."""
|
|
362
|
+
if value.dim() == 0:
|
|
363
|
+
return num(float(value), authority, proof=proof)
|
|
364
|
+
flat = value.reshape(-1)
|
|
365
|
+
return {"max_abs": num(float(flat.abs().max()), authority, proof=proof),
|
|
366
|
+
"norm": num(float(flat.norm()), authority, proof=proof)}
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _realised_reason(p: Plan, model: RowModel, found: dict[str, Any]) -> str:
|
|
370
|
+
"""Why the consumer of the realised chain has no rounding bound: its own reason, else the
|
|
371
|
+
first one of the prediction's chains."""
|
|
372
|
+
if p.consumer_label in model.unbounded:
|
|
373
|
+
return model.unbounded[p.consumer_label]
|
|
374
|
+
reason = found["operand_reason"]
|
|
375
|
+
return reason if reason is not None else "no rounding bound for this chain"
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _bound_note(reason: str, broken: dict[str, str] | None) -> dict[str, Any]:
|
|
379
|
+
"""Why a worst-case interval is absent, as information: the stop where it stopped
|
|
380
|
+
being informative and the cause with its numbers, else the refused premise or the reason."""
|
|
381
|
+
if broken is not None and bound_state(reason) != "refused":
|
|
382
|
+
return {"bound_note": broken["text"], "bound_informative": False,
|
|
383
|
+
"bound_from": broken["stage"]}
|
|
384
|
+
return {"bound_note": f"no worst-case interval bound ({bound_state(reason)}: {reason})"}
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _informative(bound: Any, size: Any, stage: str, wide: dict[str, str] | None
|
|
388
|
+
) -> dict[str, Any] | None:
|
|
389
|
+
"""The note (and the recorded numeric bound) when a finite ``bound`` is at least ``size``,
|
|
390
|
+
the consumer's ``|exact delta|`` (it does not fix the change's sign): None when it says
|
|
391
|
+
something. Never printed as ``within bound <huge>``."""
|
|
392
|
+
from .forecast import consumer_note
|
|
393
|
+
|
|
394
|
+
worst = float(bound.reshape(-1).max())
|
|
395
|
+
size = float(size.abs().max()) if size is not None and size.numel() else float("inf")
|
|
396
|
+
note = consumer_note(worst, size, stage, wide)
|
|
397
|
+
if note is None:
|
|
398
|
+
return None
|
|
399
|
+
return {"bound_note": note["text"], "bound_informative": False, "bound_from": note["stage"],
|
|
400
|
+
"bound_value": num(worst, BOUND)}
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _within(gap: Any, bound: Any, reason: str,
|
|
404
|
+
broken: dict[str, str] | None = None, size: Any = None, stage: str = "",
|
|
405
|
+
wide: dict[str, str] | None = None) -> dict[str, Any]:
|
|
406
|
+
if bound is None:
|
|
407
|
+
return _bound_note(reason, broken)
|
|
408
|
+
note = _informative(bound, size, stage, wide)
|
|
409
|
+
if note is not None:
|
|
410
|
+
return note
|
|
411
|
+
return {"bound": num(float(bound.reshape(-1).max()), BOUND),
|
|
412
|
+
"within_bound": bool((gap.abs() <= bound).all())}
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _edit_view(run: Any, p: Plan, edit: Edit) -> dict[str, Any]:
|
|
416
|
+
from mdb.engine.ports import tensor_digest
|
|
417
|
+
|
|
418
|
+
torch = _torch()
|
|
419
|
+
out: dict[str, Any] = {"address": p.edit_stop, "row": p.row, "layer": _split(p.label)[0],
|
|
420
|
+
"port": _split(p.label)[1], "op": edit.op}
|
|
421
|
+
if edit.cell is not None:
|
|
422
|
+
cell = edit.cell
|
|
423
|
+
out.update(address=edit.address, layer=int(cell["layer"]),
|
|
424
|
+
port=f"cache.L{cell['layer']}.{cell['tensor']}",
|
|
425
|
+
cell={key: cell.get(key) for key in ("layer", "tensor", "rows", "kv", "d")},
|
|
426
|
+
stage_at=p.stage_at, first_read=p.edit_stop)
|
|
427
|
+
if edit.dose is not None:
|
|
428
|
+
out["dose"] = num(float(edit.dose), SUPPLIED)
|
|
429
|
+
if edit.origin is not None:
|
|
430
|
+
out["origin"] = dict(edit.origin)
|
|
431
|
+
if isinstance(edit.value, torch.Tensor):
|
|
432
|
+
out.update(sha256=tensor_digest(edit.value.contiguous()),
|
|
433
|
+
shape=list(edit.value.shape))
|
|
434
|
+
else:
|
|
435
|
+
out["value"] = num(float(edit.value), SUPPLIED)
|
|
436
|
+
if edit.mask is not None:
|
|
437
|
+
out["mask_count"] = int(edit.mask.sum())
|
|
438
|
+
if edit.selection is not None:
|
|
439
|
+
out["selection"] = edit.selection
|
|
440
|
+
if edit.source is not None:
|
|
441
|
+
out["source"] = edit.source
|
|
442
|
+
return out
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
@dataclass
|
|
446
|
+
class WhatIf:
|
|
447
|
+
"""A what-if result: ``report`` (bounded JSON, every number labelled), the sealed prediction
|
|
448
|
+
``record`` and the float64 ``tensors`` behind the numbers (for in-process callers)."""
|
|
449
|
+
|
|
450
|
+
report: dict[str, Any]
|
|
451
|
+
record: dict[str, Any]
|
|
452
|
+
tensors: dict[str, Any]
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _within_view(found: dict[str, Any], stage: str = "") -> dict[str, Any]:
|
|
456
|
+
if found["exact_bound"] is None:
|
|
457
|
+
return _bound_note(found["unbounded"], found.get("broken"))
|
|
458
|
+
premises = sorted(found["premises"] | {"round to nearest, no overflow or underflow",
|
|
459
|
+
"replace/add/scale: the operand is cast to "
|
|
460
|
+
"the model dtype and applied in one rounded "
|
|
461
|
+
"op; mix: float64, rounded once"})
|
|
462
|
+
note = _informative(found["exact_bound"], found["exact"], stage, found.get("wide"))
|
|
463
|
+
if note is not None: # a finite interval at least |exact|: the note, the number kept
|
|
464
|
+
return {**note, "premises": premises}
|
|
465
|
+
return {"bound": num(float(found["exact_bound"].reshape(-1).max()), BOUND),
|
|
466
|
+
"premises": premises}
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _bound_scope(view: dict[str, Any], ahead: int) -> dict[str, Any]:
|
|
470
|
+
"""What the sealed worst-case bound covers, said plainly: it is interval arithmetic
|
|
471
|
+
on the dtype's rounding, compounded through every stop of the chain, and through each
|
|
472
|
+
forecast stop (one past the cursor, computed by the chain, not captured) on top of the
|
|
473
|
+
rounding of the operands. Each RMSNorm scales an input interval by about ``1/rms`` of its
|
|
474
|
+
input, so on a model with a small residual (the random tiny models: rms near 0.016) a
|
|
475
|
+
bound through a few forecast layers reaches 1e4..1e5 while the realised gap stays within
|
|
476
|
+
a spacing. ``wider_than_value``: the bound is at least ``|exact|``, so it does not fix the
|
|
477
|
+
change's sign; it never decides a verdict either way."""
|
|
478
|
+
bound, value = view.get("bound") or view.get("bound_value"), view.get("value")
|
|
479
|
+
if not isinstance(bound, dict) or not isinstance(value, dict) \
|
|
480
|
+
or not isinstance(value.get("value"), float):
|
|
481
|
+
return {}
|
|
482
|
+
wider = bound["value"] >= abs(value["value"])
|
|
483
|
+
scope = ("worst-case interval of the dtype's rounding through the chain"
|
|
484
|
+
+ (f", {ahead} of its stops forecast from the cursor" if ahead else "")
|
|
485
|
+
+ ("; at least |exact|: it does not fix the sign" if wider else ""))
|
|
486
|
+
return {"bound_scope": scope, "wider_than_value": wider}
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
@dataclass
|
|
490
|
+
class _Prepared:
|
|
491
|
+
"""A what-if up to its sealed prediction: everything that needs the cursor's values."""
|
|
492
|
+
|
|
493
|
+
p: Plan
|
|
494
|
+
edit: Edit
|
|
495
|
+
checkpoint: dict[str, Any]
|
|
496
|
+
found: dict[str, Any]
|
|
497
|
+
prediction: dict[str, Any]
|
|
498
|
+
body: dict[str, Any]
|
|
499
|
+
record: dict[str, Any]
|
|
500
|
+
before: str
|
|
501
|
+
check: Any = None
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
CHECK_ERRORS = (Refusal, KeyError, IndexError, ValueError, RuntimeError)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _checker(p: Plan, edit: Edit, found: dict[str, Any], report: bool = True) -> Any:
|
|
508
|
+
"""``check(run, side, value)``, run while the native run of ``side`` (``edited`` or
|
|
509
|
+
``base``) stands at the consumer: every stage the side's chain walked (the emulated chain's
|
|
510
|
+
stops, else the exact chain's), over every row of the chain, checked by its identity on its
|
|
511
|
+
native operands (``forecast.stage_checks``; ``stages``: the containment summary); the
|
|
512
|
+
spacings between the native consumer value and the emulated one; beyond the floor, where
|
|
513
|
+
they part (``finding``, ``stage_parting`` across the rows: not confirmed when a stage
|
|
514
|
+
lies outside its identity's bound on its native operands, else unresolved).
|
|
515
|
+
|
|
516
|
+
The checks read every walked port natively: a port inside a committed layer costs a probe
|
|
517
|
+
of that layer (one native layer call per layer not yet probed). With ``report`` False (a
|
|
518
|
+
caller that drops ``stages``, as ``reads``) they run only when needed: beyond the floor."""
|
|
519
|
+
|
|
520
|
+
def checked(run: Any, side: str) -> tuple[list[dict[str, Any]] | None, dict[str, Any]]:
|
|
521
|
+
walk = found.get(f"emulated_walk_{side}") or found[f"walk_{side}"]
|
|
522
|
+
skip: dict[tuple[int, str], str] = {}
|
|
523
|
+
if side == "edited" and edit.cell is not None:
|
|
524
|
+
skip = {(j, p.label): "reads the edited cell"
|
|
525
|
+
for j in range(p.row, p.consumer_row + 1)}
|
|
526
|
+
try:
|
|
527
|
+
checks = stage_checks(run, walk, skip)
|
|
528
|
+
except CHECK_ERRORS as error:
|
|
529
|
+
return None, {"state": "refused", "reason": f"stages not checked ({error})"}
|
|
530
|
+
# no wall-clock field: `each` holds a what-if's numbers bit for bit against running it
|
|
531
|
+
# by hand; the cost is stated as a count (`cost`)
|
|
532
|
+
return checks, containment(checks, MEASURED)
|
|
533
|
+
|
|
534
|
+
def check(run: Any, side: str, value: Any) -> dict[str, Any]:
|
|
535
|
+
out: dict[str, Any] = {}
|
|
536
|
+
checks = stages = None
|
|
537
|
+
if report:
|
|
538
|
+
checks, stages = checked(run, side)
|
|
539
|
+
out["stages"] = stages
|
|
540
|
+
predicted = found.get(f"emulated_{side}")
|
|
541
|
+
if predicted is None:
|
|
542
|
+
return out
|
|
543
|
+
native = _scalar(p, value).reshape(predicted.shape)
|
|
544
|
+
step = spacing(magnitude(p.margin or p.logit, value), value.dtype)
|
|
545
|
+
gap = float((native - predicted).abs().max())
|
|
546
|
+
out["spacings"] = gap / step
|
|
547
|
+
if gap <= FLOOR_SPACINGS * step:
|
|
548
|
+
return out
|
|
549
|
+
if not report:
|
|
550
|
+
checks, stages = checked(run, side)
|
|
551
|
+
try:
|
|
552
|
+
if checks is None:
|
|
553
|
+
raise Refusal(stages["reason"])
|
|
554
|
+
chain = (_chain(run, p, bounds=False, model=EmulatedRowModel) if side == "base"
|
|
555
|
+
else _emulated_edited(run, p, edit, found["emulated_written"]))
|
|
556
|
+
chain[-1].get(p.consumer_label)
|
|
557
|
+
finding = stage_parting(run, chain, MEASURED, checks)
|
|
558
|
+
except CHECK_ERRORS as error:
|
|
559
|
+
finding = {"verdict": "unresolved", "state": "unresolved",
|
|
560
|
+
"reason": f"stages not checked ({error})"}
|
|
561
|
+
finding["reason"] = f"{side} run: {finding['reason']}"
|
|
562
|
+
out["finding"] = finding
|
|
563
|
+
return out
|
|
564
|
+
|
|
565
|
+
return check
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _parting(native: dict[str, Any]) -> dict[str, Any] | None:
|
|
569
|
+
"""The verdict-relevant finding of the measurement's checks: a ``not confirmed`` one first,
|
|
570
|
+
else the first ``unresolved`` one, else None."""
|
|
571
|
+
findings = [native[key]["finding"] for key in ("check_edited", "check_base")
|
|
572
|
+
if native.get(key) and "finding" in native[key]]
|
|
573
|
+
return next((f for f in findings if f["verdict"] == NOT_CONFIRMED),
|
|
574
|
+
findings[0] if findings else None)
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def _prepare(run: Any, edit: Edit, consumer: Any, before_native: Any = None,
|
|
578
|
+
before: str | None = None, store: Any = None,
|
|
579
|
+
shared: dict | None = None, stages: bool = True) -> _Prepared:
|
|
580
|
+
"""Plan, hold the edit tensors, predict and seal; nothing native runs. ``before``: the
|
|
581
|
+
``state_digest`` of the cursor when the caller already has it. ``store``: a project store
|
|
582
|
+
for the full operand list when it is over the record bound (see ``bound_operands``).
|
|
583
|
+
``shared``: the emulated base chains of one call (``_emulated_base``). ``stages``: report
|
|
584
|
+
the per-stage containment (``_checker``)."""
|
|
585
|
+
from mdb.analysis.predict.forecast import refuse_held
|
|
586
|
+
|
|
587
|
+
refuse_held(run)
|
|
588
|
+
p = plan(run, edit, consumer)
|
|
589
|
+
if before is None:
|
|
590
|
+
before = state_digest(run)
|
|
591
|
+
checkpoint = run.checkpoint()
|
|
592
|
+
guard(run, checkpoint)
|
|
593
|
+
try:
|
|
594
|
+
found = _predict(run, p, edit, shared=shared)
|
|
595
|
+
except Refusal as error:
|
|
596
|
+
found = {"reason": str(error)}
|
|
597
|
+
reason = found.get("reason")
|
|
598
|
+
prediction: dict[str, Any]
|
|
599
|
+
if reason is not None:
|
|
600
|
+
prediction = {"state": "refused", "reason": reason}
|
|
601
|
+
else:
|
|
602
|
+
exact_view = {"value": _claim(found["exact"], EXACT), **_within_view(found, p.consumer_stop)}
|
|
603
|
+
stops = len(run.stops())
|
|
604
|
+
ahead = sum(1 for j in range(p.row, p.consumer_row + 1) for i in range(stops)
|
|
605
|
+
if p.here < (j, i) <= p.consumer_key)
|
|
606
|
+
if p.consumer_key > p.here:
|
|
607
|
+
exact_view["operands"] = {
|
|
608
|
+
"source": "forecast", "at": run.where,
|
|
609
|
+
"stops": num(ahead, EXACT),
|
|
610
|
+
"premise": f"the stops after {run.where} are this chain's own float64 values "
|
|
611
|
+
"from the operands captured there (a forecast), not native ones; "
|
|
612
|
+
"the exact change on measured operands is computed after the "
|
|
613
|
+
"native run (split term operands)"}
|
|
614
|
+
else:
|
|
615
|
+
exact_view["operands"] = {"source": "measured", "at": run.where}
|
|
616
|
+
exact_view.update(_bound_scope(exact_view, ahead))
|
|
617
|
+
if "linear" in found:
|
|
618
|
+
linear_view: dict[str, Any] = {"value": _claim(found["linear"], LOCAL, "P14"),
|
|
619
|
+
"meaning": "gradient of the consumer times the edit "
|
|
620
|
+
"displacement; not the effect"}
|
|
621
|
+
else:
|
|
622
|
+
linear_view = {"state": "refused", "reason": found["linear_reason"]}
|
|
623
|
+
if found.get("emulated") is not None:
|
|
624
|
+
emulated_view: dict[str, Any] = {
|
|
625
|
+
"value": _claim(found["emulated"], EXACT),
|
|
626
|
+
"base": _claim(found["emulated_base"], EXACT),
|
|
627
|
+
"edited": _claim(found["emulated_edited"], EXACT),
|
|
628
|
+
"premise": EMULATION_PREMISE,
|
|
629
|
+
"premises": [*EMULATION_PREMISES, WRITE_PREMISE],
|
|
630
|
+
"meaning": "the native change predicted bit for bit: base and edited chains "
|
|
631
|
+
"with the dtype's rounding where eager HF rounds"}
|
|
632
|
+
else:
|
|
633
|
+
emulated_view = {"state": "refused",
|
|
634
|
+
"reason": found.get("emulated_reason", "not computed")}
|
|
635
|
+
prediction = {"state": "resolved", "linear": linear_view, "exact": exact_view,
|
|
636
|
+
"emulated": emulated_view, "base": _claim(found["base"], EXACT)}
|
|
637
|
+
applied = [f"t{row}.{label} {' then '.join(e.op for e in edits)}"
|
|
638
|
+
for row, stops in sorted(_port_edits(run, p).items())
|
|
639
|
+
for label, edits in stops.items()]
|
|
640
|
+
if applied: # the chains honour every staged and committed edit of their rows
|
|
641
|
+
prediction["other_edits"] = {
|
|
642
|
+
"applied": applied[:MAX_ITEMS], "count": num(len(applied), EXACT),
|
|
643
|
+
"rule": "staged and committed port edits of the chain's rows, applied where the "
|
|
644
|
+
"chains compute their stop (a captured value already carries its edit)"}
|
|
645
|
+
body = {
|
|
646
|
+
"schema": SCHEMA, "edit": _edit_view(run, p, edit),
|
|
647
|
+
"consumer": {"address": p.consumer_text, "row": p.consumer_key[0],
|
|
648
|
+
"index": p.consumer_key[1],
|
|
649
|
+
"kind": "margin" if p.margin else "logit" if p.logit else "value",
|
|
650
|
+
**({"indices": [p.margin.a, p.margin.b]} if p.margin else {})},
|
|
651
|
+
"sealed_at": {"where": run.where, "cut": checkpoint["cut"], "row": p.here[0],
|
|
652
|
+
"index": p.here[1], "transition": int(checkpoint["transitions"])},
|
|
653
|
+
"mode": p.mode, "prediction": prediction,
|
|
654
|
+
"method": {"exact": "F(x1) - F(x0): port-program identities on values at the cursor, "
|
|
655
|
+
"base and edited chains recomputing the same stops (those the edit "
|
|
656
|
+
"reaches) with the port at its value x0 or the edit written there "
|
|
657
|
+
"(rows chained through the cache)",
|
|
658
|
+
"linear": "forward-mode derivative of the same chain at the unedited point "
|
|
659
|
+
"(P14)",
|
|
660
|
+
"emulated": "the same chains with the dtype's rounding at every eager-HF "
|
|
661
|
+
"rounding point (EmulatedRowModel); the base takes the stops at "
|
|
662
|
+
"or before the cursor as captured"},
|
|
663
|
+
}
|
|
664
|
+
body["procedure"] = procedure(run) # the prefill split the edit and consumer rows run under
|
|
665
|
+
pointers: list[dict[str, Any]] = []
|
|
666
|
+
if reason:
|
|
667
|
+
body["operands"] = []
|
|
668
|
+
else:
|
|
669
|
+
body["operands"], summary = bound_list(
|
|
670
|
+
found["operands"], MAX_ITEMS, store=store, run=run,
|
|
671
|
+
keep=f"the first {MAX_ITEMS} in capture order (a row's ports, then its cache reads)")
|
|
672
|
+
if summary is not None:
|
|
673
|
+
tensor = summary["pointer"].pop("tensor", None)
|
|
674
|
+
pointers = [] if tensor is None else [tensor]
|
|
675
|
+
body["operands_summary"] = summary
|
|
676
|
+
record = seal_record(session_id=run_session_id(run), kind="whatif",
|
|
677
|
+
model_identity=run.adapter.model_identity,
|
|
678
|
+
execution=dict(run.adapter.execution),
|
|
679
|
+
authority=LOCAL if reason is None else SUPPLIED, body=body,
|
|
680
|
+
pointers=pointers, run=run)
|
|
681
|
+
# An evidence writer can persist/flush the sealed forecast before the first
|
|
682
|
+
# counterfactual measurement. Writer failure prevents native release.
|
|
683
|
+
if before_native is not None:
|
|
684
|
+
before_native(record)
|
|
685
|
+
return _Prepared(p, edit, checkpoint, found, prediction, body, record, before,
|
|
686
|
+
_checker(p, edit, found, stages) if reason is None else None)
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def load_operands(record: dict[str, Any], *, store: Any = None, run: Any = None
|
|
690
|
+
) -> list[dict[str, Any]]:
|
|
691
|
+
"""The full operand list of a ``whatif`` record: ``body.operands`` itself within the record
|
|
692
|
+
bound, else the blob ``body.operands_summary.pointer`` names (project ``store``, or the
|
|
693
|
+
run's in-memory copy), checked against its sha256; ``ValueError`` if absent or changed."""
|
|
694
|
+
body = record["body"]
|
|
695
|
+
summary = body.get("operands_summary")
|
|
696
|
+
if summary is None:
|
|
697
|
+
return body["operands"]
|
|
698
|
+
pointer = summary["pointer"]
|
|
699
|
+
tensor = next((p for p in record["pointers"]
|
|
700
|
+
if p.get("kind") == "tensor" and p.get("ref") == pointer.get("ref")), None)
|
|
701
|
+
return load_json(pointer, store=store, run=run, tensor=tensor)
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def whatif(run: Any, edit: Edit, consumer: Any, *, before_native: Any = None,
|
|
705
|
+
store: Any = None) -> WhatIf:
|
|
706
|
+
"""Predict, seal, measure and split the change of ``consumer`` (a ``Margin``, a ``Logit`` or
|
|
707
|
+
a stop address) under ``edit``; the session is left exactly where it was (checked by
|
|
708
|
+
``state_digest``; a difference raises ``RuntimeError``). ``before_native(record)``
|
|
709
|
+
may persist and flush the sealed prediction; an exception prevents measurement.
|
|
710
|
+
"""
|
|
711
|
+
prep = _prepare(run, edit, consumer, before_native, store=store)
|
|
712
|
+
native = _measure(run, prep.p, edit, prep.checkpoint, prep.check)
|
|
713
|
+
return _finish(run, prep, native, state_digest(run))
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def _finish(run: Any, prep: _Prepared, native: dict[str, Any], after: str) -> WhatIf:
|
|
717
|
+
"""Split and judge the native change of a prepared what-if (needs the cursor's values, so
|
|
718
|
+
the session is back where it was); ``after``: the session digest then.
|
|
719
|
+
|
|
720
|
+
The split and the verdict use the exact chain on measured operands: computed at the cursor
|
|
721
|
+
when the consumer was already captured at the seal (the sealed chain itself), else at the
|
|
722
|
+
consumer inside the measurement (``_base_ahead``); then ``operands`` (that minus the sealed
|
|
723
|
+
exact change) joins the split, so ``native = linear + nonlinear + operands + realisation +
|
|
724
|
+
rounding effect + residual`` still holds term by term. The verdict holds the native change
|
|
725
|
+
against the sealed emulated one (``verdict.decide``), the same at any cursor."""
|
|
726
|
+
p, edit, found, prediction = prep.p, prep.edit, prep.found, prep.prediction
|
|
727
|
+
body, record, before = prep.body, prep.record, prep.before
|
|
728
|
+
reason = found.get("reason")
|
|
729
|
+
if after != before:
|
|
730
|
+
raise RuntimeError("whatif did not leave the session where it was (state digest "
|
|
731
|
+
f"{before[:12]} -> {after[:12]})")
|
|
732
|
+
base_label = native["base_info"]["authority"] or MEASURED
|
|
733
|
+
edited_label = native["edited_info"]["authority"] or MEASURED
|
|
734
|
+
base, edited = _scalar(p, native["base"]), _scalar(p, native["edited"])
|
|
735
|
+
change = edited - base
|
|
736
|
+
from ..numerics.pooling import informative
|
|
737
|
+
known = informative(native.get("base_port"), native.get("realised"))
|
|
738
|
+
donors = (1, None if known is None else int(known))
|
|
739
|
+
size = magnitude(p.margin or p.logit, native["base"], native["edited"])
|
|
740
|
+
dtype = native["base"].dtype
|
|
741
|
+
measured = {"base": _claim(base, base_label), "edited": _claim(edited, edited_label),
|
|
742
|
+
"delta": _claim(change, MEASURED), "moves": native["moves"]}
|
|
743
|
+
report: dict[str, Any] = {
|
|
744
|
+
"edit": body["edit"], "consumer": body["consumer"], "mode": p.mode,
|
|
745
|
+
"record": record["id"], "prediction": prediction, "measured": measured,
|
|
746
|
+
"session": {"before": before, "after": after, "unchanged": True},
|
|
747
|
+
}
|
|
748
|
+
stages = {side: native[f"check_{side}"]["stages"] for side in ("edited", "base")
|
|
749
|
+
if "stages" in (native.get(f"check_{side}") or {})}
|
|
750
|
+
if stages: # each walked stage on its native operands, information
|
|
751
|
+
report["stages"] = stages
|
|
752
|
+
tensors = {"native_base": native["base"], "native_edited": native["edited"],
|
|
753
|
+
"realised": native["realised"], "native_delta": change}
|
|
754
|
+
forecast = "posthoc" in native # the operands past the cursor were forecast at the seal
|
|
755
|
+
post = native.get("posthoc")
|
|
756
|
+
if reason is None and post is not None and post.get("reason") is not None:
|
|
757
|
+
reason = f"the exact chain on measured operands is refused ({post['reason']})"
|
|
758
|
+
report["exact"] = {"state": "refused", "reason": reason}
|
|
759
|
+
if reason is None:
|
|
760
|
+
if post is None: # every operand was measured when the prediction was sealed
|
|
761
|
+
post = {**found, **_written_exact(run, p, edit, found, native["realised"])}
|
|
762
|
+
exact, at_realised, spread = found["exact"], post["at_realised"], post["spread"]
|
|
763
|
+
native_change = change.reshape(exact.shape)
|
|
764
|
+
terms = []
|
|
765
|
+
if "linear" in found:
|
|
766
|
+
terms += [{"name": "linear", "value": _claim(found["linear"], LOCAL, "P14")},
|
|
767
|
+
{"name": "nonlinear", "value": _claim(exact - found["linear"], EXACT,
|
|
768
|
+
"P20"),
|
|
769
|
+
"meaning": "exact minus linear: the curvature the first-order term misses"}]
|
|
770
|
+
else:
|
|
771
|
+
terms.append({"name": "exact", "value": _claim(exact, EXACT)})
|
|
772
|
+
if forecast:
|
|
773
|
+
terms.append({"name": "operands", "value": _claim(post["exact"] - exact, EXACT, "P20"),
|
|
774
|
+
"meaning": "exact change on the measured operands minus the sealed "
|
|
775
|
+
"exact change on operands forecast from "
|
|
776
|
+
f"{body['sealed_at']['where']}"})
|
|
777
|
+
rounding = native_change - at_realised
|
|
778
|
+
terms.append(
|
|
779
|
+
{"name": "realisation", "value": _claim(at_realised - post["exact"], EXACT, "P20"),
|
|
780
|
+
"meaning": "exact change with the operand the edit wrote (read back) minus the "
|
|
781
|
+
"exact change with the requested operand, both on measured operands"})
|
|
782
|
+
emulated = found.get("emulated")
|
|
783
|
+
if emulated is not None:
|
|
784
|
+
emulated = emulated.reshape(native_change.shape)
|
|
785
|
+
terms += [
|
|
786
|
+
{"name": "rounding effect", "value": _claim(emulated - at_realised, EXACT, "P20"),
|
|
787
|
+
"meaning": "the emulated change (the dtype's rounding where eager HF rounds, "
|
|
788
|
+
"sealed) minus the exact change with the written operand; derived "
|
|
789
|
+
"under the emulation premises",
|
|
790
|
+
**_within(rounding, spread, post["spread_reason"], post.get("spread_broken"),
|
|
791
|
+
post["exact"], p.consumer_stop, post.get("spread_wide"))},
|
|
792
|
+
{"name": "residual", "value": _claim(native_change - emulated, MEASURED, "P20"),
|
|
793
|
+
"meaning": "native change minus the emulated change"}]
|
|
794
|
+
else:
|
|
795
|
+
terms.append({"name": "rounding", "value": _claim(rounding, MEASURED, "P20"),
|
|
796
|
+
"meaning": "native change minus the exact change with the written "
|
|
797
|
+
"operand (no emulated chain: "
|
|
798
|
+
f"{found.get('emulated_reason', 'not computed')})",
|
|
799
|
+
**_within(rounding, spread, post["spread_reason"],
|
|
800
|
+
post.get("spread_broken"), post["exact"],
|
|
801
|
+
p.consumer_stop, post.get("spread_wide"))})
|
|
802
|
+
report["exact"] = {
|
|
803
|
+
"requested": _claim(post["exact"], EXACT, "P20"),
|
|
804
|
+
"written": _claim(at_realised, EXACT, "P20"),
|
|
805
|
+
"operands": "measured",
|
|
806
|
+
"meaning": "F(x1) - F(x0) (P09 section 1) on the native operands of the unedited "
|
|
807
|
+
"run; written: x1 the value the edit wrote (read back). The verdict "
|
|
808
|
+
"holds native against the written one",
|
|
809
|
+
}
|
|
810
|
+
report["difference"] = {
|
|
811
|
+
"native_minus_exact": {"value": _claim(native_change - exact, MEASURED),
|
|
812
|
+
**_within(native_change - exact, found["exact_bound"],
|
|
813
|
+
found["unbounded"], found.get("broken"), exact,
|
|
814
|
+
p.consumer_stop, found.get("wide"))},
|
|
815
|
+
**({"native_minus_linear": _claim(native_change - found["linear"], MEASURED)}
|
|
816
|
+
if "linear" in found else {}),
|
|
817
|
+
}
|
|
818
|
+
report["split"] = {"proof": "P20", "terms": terms,
|
|
819
|
+
"rule": "native delta = sum of the terms (float64)"}
|
|
820
|
+
tensors.update(exact=exact, exact_bound=found["exact_bound"], exact_measured=post["exact"],
|
|
821
|
+
linear=found.get("linear"), at_realised=at_realised, rounding_bound=spread,
|
|
822
|
+
emulated=emulated)
|
|
823
|
+
effect = decide(native_change, emulated, size, dtype, exact=at_realised,
|
|
824
|
+
why_native_only=f"the emulated chain is refused "
|
|
825
|
+
f"({found.get('emulated_reason')})",
|
|
826
|
+
parting=_parting(native), donors=donors)
|
|
827
|
+
else:
|
|
828
|
+
report["split"] = {"state": "refused", "reason": reason}
|
|
829
|
+
effect = decide(change, None, size, dtype,
|
|
830
|
+
why_native_only=f"the prediction is refused ({reason})", donors=donors)
|
|
831
|
+
# the verdict follows the P20 accounting (measured), never the worst-case interval bound
|
|
832
|
+
report["effect"] = effect
|
|
833
|
+
report["state"] = effect["state"]
|
|
834
|
+
return WhatIf(report, record, tensors)
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
_guard = guard # old private name, kept for one commit
|
|
838
|
+
|
|
839
|
+
|
|
840
|
+
__all__ = ["WhatIf", "guard", "stage", "whatif"]
|