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.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
@@ -0,0 +1,596 @@
1
+ """What-if: the change one edit makes in a downstream consumer, predicted at the cursor, then
2
+ measured natively, with the session left exactly where it was.
3
+
4
+ ``whatif(run, edit, consumer)`` works in three steps.
5
+
6
+ 1. **Prediction**, from values that exist at the cursor and the weights only (no native call):
7
+ the row model of ``forecast`` (``RowModel``) is evaluated over the rows from the edit's row to
8
+ the consumer's row, once without the edit (``base``) and once with the requested edit written
9
+ at the edited port (``edited``); later rows read the earlier rows' keys and values from the
10
+ same chain, and a sampled token is the chain's own argmax. ``exact = edited - base`` is
11
+ ``derived-exact`` with a rounding ``bound`` (the forecast bounds plus the cast of the edit
12
+ operand), and the first-order term ``linear = J delta`` (forward-mode derivative of the same
13
+ chain at the unedited point, P14) is ``derived-local``. ``exact`` is ``F(x1) - F(x0)`` (P09
14
+ section 1): both chains hold the edited port at ``x0`` or write the edit there and recompute
15
+ the same stops (those the edit reaches) from the same operands; the base is never the native
16
+ value (that would fold the base run's rounding into the exact change). The prediction is
17
+ sealed as a record (kind ``whatif``) before anything native runs. When the consumer is ahead
18
+ of the cursor, the operands past the cursor exist only as the chain's own float64 values: the
19
+ sealed exact change says so (``prediction.exact.operands.source == "forecast"``). Beside them
20
+ the **emulated** chains (``EmulatedRowModel``, forecast's premises: the dtype's rounding where
21
+ eager HF rounds, backend kernels on the model's device) give the emulated base and edited
22
+ values; their difference predicts the native change itself (``prediction.emulated``,
23
+ ``derived-exact`` under those premises). The edit is written there by the engine's own
24
+ arithmetic (``PortEdit.apply``, the cell write) on the emulated value. A staged edit ahead of
25
+ the cursor refuses the emulated chains (they would not see it); a refused emulation leaves the
26
+ rest of the prediction as it was. The emulated base does not depend on the edit: the what-ifs
27
+ of one ``whatif_many`` call share it (per first row, consumer and cursor).
28
+ 2. **Measurement**: checkpoint, stage the edit (moving to the edited layer first: forward, or back
29
+ by layer boundaries when the layer is already committed), run natively to the consumer, read
30
+ it, restore; the consumer's unedited value is read the same way. Labelled ``measured``. With
31
+ the consumer ahead of the cursor the edited branch runs first, then the unedited branch to
32
+ the consumer, where the exact chain is computed again on the measured operands (``report
33
+ ["exact"]``, after the seal, never presented as sealed).
34
+ 3. **Split** of the native change (P20): ``native = linear + nonlinear [+ operands] +
35
+ realisation + rounding`` with ``nonlinear = exact - linear``, ``operands`` (forecast seal
36
+ only) the exact change on measured operands minus the sealed one, ``realisation`` the change
37
+ of the exact value on measured operands when the edit operand is the value the edit actually
38
+ wrote (read back natively) instead of the requested one (all ``derived-exact``), ``rounding
39
+ effect = emulated - exact(written, measured operands)`` (``derived-exact`` under the emulation
40
+ premises; the worst-case interval ``bound`` on the native rounding is kept beside it only when
41
+ finite) and ``residual = native - emulated`` (``measured``: 0 when the emulation holds).
42
+ Without an emulated change the last two are one term, ``rounding = native - exact``
43
+ (``measured``). The linear number is never reported as the effect.
44
+ 4. **Verdict** (``report["effect"]``, ``verdict.decide``): the native change against the
45
+ emulated one within the floor of ``verdict.FLOOR_SPACINGS`` (1, supplied, the constant verify
46
+ uses) dtype spacings at the consumer. ``effect`` when they agree and the native change is not
47
+ zero; ``no effect`` when they agree and it is zero (the note gives the exact change the dtype
48
+ cannot show); beyond the floor verify's rule: ``not confirmed`` when a stage of the edited or
49
+ base run lies outside the bound of its identity on its native operands (the parting stop
50
+ named), else ``unresolved`` (rounding drift, or a chain over several rows: not stage-checked).
51
+ With no emulated change (refused): ``effect`` iff the native edited and base values differ.
52
+ The exact change is reported beside the verdict, never decides it. The result's ``state`` is
53
+ the verdict's; the interval bound never sets it.
54
+
55
+ A state-cell edit (``Edit.cell``: ``cache.L<l>.k|v[kv,row,d]``, ops ``replace | add | scale |
56
+ mix``) is staged where the cursor is when the consumer is still ahead (``pending``), else at
57
+ the entry ``t<c>.L<l>.h`` of the consumer's row (``rewind``). It reaches every read of the cell
58
+ not yet made: the first is the cell layer's ``kr`` (keys) or ``A`` (values) of the cursor's row
59
+ when that read is still ahead (``first_read``), else of the next row, and the same read in every
60
+ later row. The prediction writes the cell into the cache rows the chain reads (float64, the
61
+ requested operation unrounded; the written value's distance is the edit's bound) and refuses
62
+ when the first affected row has not started at the cursor; the linear term is the forward-mode
63
+ derivative through the attention read (a value cell enters ``A`` linearly, P06/P07).
64
+
65
+ The session's ``state_digest`` (cursor, cut fingerprint, transition count, staged and committed
66
+ edits, lookahead state) is taken before and after; a difference raises. Every edit tensor the
67
+ checkpoint names is held (``Run.hold``) before anything native runs, so the restore can rebuild
68
+ them; a checkpoint naming a tensor the run does not hold is refused first.
69
+ """
70
+
71
+ from __future__ import annotations
72
+
73
+ from typing import Any
74
+
75
+ from mdb.core.kinds import WHATIF
76
+
77
+ from ..numerics.labels import f64
78
+ from .consumers import Refusal
79
+ from .plan import Edit, Plan
80
+ from .rowmodel import EmulatedRowModel, RowModel, _split
81
+
82
+
83
+ def _torch():
84
+ import torch
85
+
86
+ return torch
87
+
88
+
89
+ # --------------------------------------------------------------------------- planning
90
+
91
+
92
+
93
+
94
+ # --------------------------------------------------------------------------- prediction
95
+
96
+
97
+ def _port_edits(run: Any, p: Plan) -> dict[int, dict[str, list[Any]]]:
98
+ """Every port edit that fires (staged at the pending layer) or fired (committed) in the
99
+ rows ``p.row .. p.consumer_row``, as the engine's ``PortEdit`` (value and mask from the run's
100
+ held edit tensors), by row and stop, in firing order. The chains apply them where they
101
+ compute the stop; a captured value already carries its edit."""
102
+ from mdb.engine.ports import PortEdit
103
+
104
+ tensors = run.edit_tensors()
105
+ rows = range(p.row, p.consumer_row + 1)
106
+ found: list[tuple[int, int, dict[str, Any]]] = [
107
+ (int(e["row"]), int(e["layer"]), e) for e in run.committed_edits()]
108
+ layer = run.status()["pending_layer"]
109
+ if layer is not None:
110
+ found += [(p.here[0], int(layer), e) for e in run.edits]
111
+ out: dict[int, dict[str, list[Any]]] = {}
112
+ for row, layer, manifest in found:
113
+ if row not in rows:
114
+ continue
115
+ described = manifest["value"]
116
+ value = (described["value"] if described["kind"] == "scalar"
117
+ else tensors[described["sha256"]])
118
+ mask = tensors[manifest["mask_sha256"]] if manifest.get("mask_sha256") else None
119
+ port = run.program.spec(manifest["port"]).name
120
+ edit = PortEdit(port, value, manifest["op"], mask=mask)
121
+ out.setdefault(row, {}).setdefault(f"L{layer}.{port}", []).append(edit)
122
+ return out
123
+
124
+
125
+ def _edit_functions(run: Any, p: Plan, kind: str) -> dict[int, dict[str, Any]]:
126
+ """``RowModel.edits`` per row for a chain of ``kind``: ``exact`` (float64 with the rounding
127
+ bound of the native write), ``linear`` (float64, no bound: the forward-mode chain) or
128
+ ``emulated`` (the engine's own ``PortEdit.apply`` on the dtype value). An ``r`` edit is
129
+ realised natively as an ``o`` edit (``o' = op(h + o) - h``, ``r = h + o'``): exactly
130
+ ``r' = op(r)``, emulated as the engine does it."""
131
+ out: dict[int, dict[str, Any]] = {}
132
+ for row, stops in _port_edits(run, p).items():
133
+ for label, edits in stops.items():
134
+ address = f"t{row}.{label}"
135
+ out.setdefault(row, {})[label] = _edit_function(run, address, label, edits, kind)
136
+ return out
137
+
138
+
139
+ def _edit_function(run: Any, address: str, label: str, edits: list[Any], kind: str) -> Any:
140
+ torch = _torch()
141
+ port = _split(label)[1]
142
+ here = f"L{_split(label)[0]}."
143
+
144
+ def emulated(model: Any, name: str, value: Any, bound: Any) -> tuple[Any, Any]:
145
+ shape = tuple(run.address_shape(address))
146
+ x = model._on(value).reshape(shape)
147
+ target = x
148
+ for edit in edits:
149
+ target = edit.apply(target)
150
+ if port == "r":
151
+ h = model._on(model.values[here + "h"]).reshape(shape)
152
+ new = h + (target - h)
153
+ union = None
154
+ for edit in edits:
155
+ selected = edit.selected(shape, x.device)
156
+ if selected is None:
157
+ union = None
158
+ break
159
+ union = selected if union is None else union | selected
160
+ target = new if union is None else torch.where(union, new, x)
161
+ return model._back(target).reshape(value.shape), None
162
+
163
+ def exact(model: Any, name: str, value: Any, bound: Any) -> tuple[Any, Any]:
164
+ # the real-number edit and the bound of its native write (``_request``: the operand
165
+ # cast to the dtype, one rounded op)
166
+ for edit in edits:
167
+ request = Edit(address, edit.value, edit.op, edit.mask)
168
+ value, _, bound = _request(run, request, tuple(value.shape), value, bound, model.u)
169
+ if kind == "linear" or not model.bounds:
170
+ return value, None
171
+ if port == "r" and bound is not None: # o' = r' - h and r = h + o', both rounded
172
+ h, u = model.values[here + "h"], model.u
173
+ bound = bound + u * ((value - h).abs() * (1 + u) + value.abs())
174
+ return value, bound
175
+
176
+ return emulated if kind == "emulated" else exact
177
+
178
+
179
+ def _chain(run: Any, p: Plan, *, bounds: bool, overrides: dict[str, Any] | None = None,
180
+ skip: bool = False, tokens: dict[int, int] | None = None,
181
+ cell: Any = None, model: type = RowModel) -> list[RowModel]:
182
+ """Row models for rows ``p.row .. p.consumer_row``. Stops at or before the cursor are taken
183
+ as captured, except (``skip``) the ones the edit reaches; row ``j > p.row`` reads the cache
184
+ rows ``p.row..j-1`` from the chain and its token from the prompt, from ``tokens`` or from the
185
+ chain's argmax of row ``j - 1``. ``cell(layer, kind, value, spread)`` rewrites the cache
186
+ rows ``0..p.row-1`` every row reads (a state-cell edit; the first row then reads them
187
+ through it too). ``model``: ``RowModel`` (float64) or ``EmulatedRowModel`` (the dtype's
188
+ rounding, no bounds). Every staged or committed port edit of those rows is applied where
189
+ the chain computes its stop (``_edit_functions``); staged cells are in the cache the
190
+ rows read (``Run.read_cache``)."""
191
+ torch = _torch()
192
+ models: list[RowModel] = []
193
+ here = p.here
194
+ rows: dict[tuple[int, str], tuple[Any, Any]] = {} # cache rows 0..p.row-1, cast once
195
+ kind = ("emulated" if issubclass(model, EmulatedRowModel) else "exact" if bounds
196
+ else "linear")
197
+ fired = _edit_functions(run, p, kind)
198
+
199
+ def known_for(j: int):
200
+ drop = p.affected.get(j, set()) if skip else set()
201
+
202
+ def known(name: str) -> Any:
203
+ if name == "start" or name in drop or run.parse(f"t{j}.{name}") > here:
204
+ return None
205
+ return run.read(f"t{j}.{name}")
206
+
207
+ return known
208
+
209
+ def cached(layer: int, kind: str) -> tuple[Any, Any]:
210
+ """The cache rows every row of the chain reads (``cell`` written in), read and cast
211
+ once per chain."""
212
+ if (layer, kind) not in rows:
213
+ base = f64(run.read_cache(layer, kind)[..., : p.row, :])[0]
214
+ spread0 = torch.zeros_like(base)
215
+ if cell is not None:
216
+ base, spread0 = cell(layer, kind, base, spread0)
217
+ rows[layer, kind] = base, spread0
218
+ return rows[layer, kind]
219
+
220
+ for j in range(p.row, p.consumer_row + 1):
221
+ earlier = list(models)
222
+
223
+ def past(layer: int, kind: str, earlier=earlier) -> Any:
224
+ base, spread0 = cached(layer, kind)
225
+ parts, spreads = [base], [spread0]
226
+ for model in earlier:
227
+ name = f"L{layer}.kr" if kind == "k" else f"L{layer}.v"
228
+ value, spread = yield from model.need(name)
229
+ shape = (model.kv_heads, -1, model.head_dim)
230
+ value = value.reshape(shape)[:, -1:, :]
231
+ parts.append(value)
232
+ spreads.append(None if spread is None else spread.reshape(shape)[:, -1:, :])
233
+ if any(s is None for s in spreads):
234
+ return torch.cat(parts, 1), None
235
+ return torch.cat(parts, 1), torch.cat(spreads, 1)
236
+
237
+ def token(j=j, earlier=earlier) -> Any:
238
+ if j < len(run.tokens):
239
+ return run.tokens[j], None
240
+ if tokens is not None:
241
+ return tokens[j], None
242
+ previous = earlier[-1]
243
+ value, spread = yield from previous.need("sample")
244
+ sampled = int(value)
245
+ if bounds and spread is None:
246
+ return sampled, (f"the sampled token of t{j - 1} is not certified: "
247
+ + previous.unbounded.get("sample", "no bound on its logits"))
248
+ return sampled, None
249
+
250
+ first = j == p.row
251
+ models.append(model(run, j, known_for(j), bounds=bounds,
252
+ overrides=(overrides or {}) if first else None,
253
+ past=None if first and cell is None else past,
254
+ token=None if first else token, edits=fired.get(j)))
255
+ return models
256
+
257
+
258
+ def _consumer_value(p: Plan, model: RowModel) -> tuple[Any, Any]:
259
+ value, bound = model.get(p.consumer_label), model.bound(p.consumer_label)
260
+ if p.margin is not None:
261
+ value = value[p.margin.a] - value[p.margin.b]
262
+ bound = None if bound is None else bound[p.margin.a] + bound[p.margin.b]
263
+ elif p.logit is not None:
264
+ value = value[p.logit.i]
265
+ bound = None if bound is None else bound[p.logit.i]
266
+ return value, bound
267
+
268
+
269
+ def _sampled_tokens(p: Plan, models: list[RowModel], run: Any) -> dict[int, int]:
270
+ return {j: int(models[j - p.row - 1].get("sample"))
271
+ for j in range(p.row + 1, p.consumer_row + 1) if j >= len(run.tokens)}
272
+
273
+
274
+ def _request(run: Any, edit: Edit, shape: tuple[int, ...], x0: Any, b0: Any, u: float
275
+ ) -> tuple[Any, Any, Any]:
276
+ """``(requested, delta, bound)`` at the edited port in float64: the exact result of
277
+ ``x0 op value`` on the selected elements and its rounding bound against the value the native
278
+ edit writes (the operand cast to the model dtype, one rounded op; a ``mix`` is float64
279
+ rounded once and casts no operand; ``b0`` the bound of ``x0``
280
+ itself when ``x0`` is a prediction)."""
281
+ torch = _torch()
282
+ port_shape = tuple(run.address_shape(edit.address)) # the edited row's frame, not the cursor's
283
+ if isinstance(edit.value, torch.Tensor):
284
+ value = f64(edit.value).broadcast_to(port_shape).reshape(shape)
285
+ else:
286
+ value = torch.full(shape, float(edit.value), dtype=torch.float64)
287
+ mask = (torch.ones(shape, dtype=torch.bool) if edit.mask is None
288
+ else edit.mask.to(device=x0.device, dtype=torch.bool).broadcast_to(port_shape).reshape(shape))
289
+ on: Any = None
290
+ if edit.op == "replace":
291
+ full = value
292
+ on = u * value.abs()
293
+ elif edit.op == "add":
294
+ full = x0 + value
295
+ if b0 is not None:
296
+ on = u * (full.abs() + u * value.abs()) + u * value.abs() + b0 * (1 + u)
297
+ else:
298
+ full = x0 * value
299
+ if b0 is not None:
300
+ on = (2 * u + u * u) * full.abs() + b0 * value.abs() * (1 + u) ** 2
301
+ requested = torch.where(mask, full, x0)
302
+ if bool(mask.all()):
303
+ bound = on
304
+ else:
305
+ bound = None if on is None or b0 is None else torch.where(mask, on, b0)
306
+ return requested, requested - x0, bound
307
+
308
+
309
+ def _cell_edit(edit: Edit, value: Any = None) -> Any:
310
+ """``edit`` as the engine's ``CellEdit`` (``value`` replaces its value when given)."""
311
+ from mdb.engine.edits import CellEdit
312
+
313
+ cell = edit.cell
314
+ return CellEdit(int(cell["layer"]), cell["tensor"], tuple(cell["rows"]),
315
+ edit.value if value is None else value, edit.op, kv=cell.get("kv"),
316
+ d=cell.get("d"), dose=edit.dose, selection=edit.selection,
317
+ origin=edit.origin)
318
+
319
+
320
+ def _cell_writer(edit: Edit, written: Any, mode: str) -> Any:
321
+ """``_chain``'s ``cell`` for a state-cell edit, on the cache rows ``0..row-1`` it reads.
322
+ ``written`` is the whole cache tensor with the block the engine writes. ``mode``:
323
+ ``ideal`` the float64 request on the selected block, its distance to the written block
324
+ added to the spread; ``written`` the written block itself; ``tangent`` the unedited rows
325
+ with the displacement ``ideal - base`` as forward-mode tangent (no spread)."""
326
+ import torch.autograd.forward_ad as fwad
327
+
328
+ torch = _torch()
329
+ request = _cell_edit(edit)
330
+
331
+ def write(layer: int, kind: str, value: Any, spread: Any) -> tuple[Any, Any]:
332
+ if (layer, kind) != (request.layer, request.tensor):
333
+ return value, spread
334
+ x = value.unsqueeze(0)
335
+ index = request.index(x.shape)
336
+ ideal = request.ideal(x[index])
337
+ actual = f64(written[..., : x.shape[2], :])[index]
338
+ if mode == "tangent":
339
+ direction = torch.zeros_like(x)
340
+ direction[index] = ideal - x[index]
341
+ return fwad.make_dual(value, direction[0]), None
342
+ out = x.clone()
343
+ out[index] = ideal if mode == "ideal" else actual
344
+ if spread is None:
345
+ return out[0], None
346
+ grown = spread.unsqueeze(0).clone()
347
+ if mode == "ideal":
348
+ grown[index] = grown[index] + (ideal - actual).abs()
349
+ return out[0], grown[0]
350
+
351
+ return write
352
+
353
+
354
+ def _written_cell(run: Any, edit: Edit) -> Any:
355
+ """The cache tensor at the cursor with the block the cell edit writes, by the engine's own
356
+ arithmetic (``CellEdit.realise``, the code the native layer call runs)."""
357
+ request = _cell_edit(edit)
358
+ return request.realise(run.read_cache(request.layer, request.tensor))[0]
359
+
360
+
361
+ def _settle(run: Any, p: Plan, chain: list[RowModel], seen: dict[str, dict[str, Any]]
362
+ ) -> dict[str, Any]:
363
+ """Everything the report reads from one chain, so the chain (one float64 row model per row)
364
+ can be dropped before the next is built: the consumer's value and bound, the premises, why
365
+ its consumer is unbounded (the last row's reason, ``last``; the first row model's with a
366
+ reason, ``first``), the sampled tokens, and its operand digests (added to ``seen``). Read
367
+ in the order a whatif always read them, so every number and digest is unchanged."""
368
+ value, bound = _consumer_value(p, chain[-1])
369
+ out = {"value": value, "bound": bound,
370
+ "premises": set().union(*(m.premises for m in chain)),
371
+ "last": chain[-1].unbounded.get(p.consumer_label)}
372
+ out["tokens"] = _sampled_tokens(p, chain, run)
373
+ _operands(run, chain, seen)
374
+ out["first"] = next((m.unbounded[p.consumer_label] for m in chain
375
+ if p.consumer_label in m.unbounded), None)
376
+ out["broken"] = next((m.broken for m in chain if m.broken is not None), None)
377
+ out["wide"] = next((m.wide for m in chain if m.wide is not None), None)
378
+ out["walk"] = _walk(chain)
379
+ return out
380
+
381
+
382
+ def _flip_reason(p: Plan, base: dict[str, Any], edited: dict[str, Any]) -> str | None:
383
+ """Why the first-order term is refused: the edit flips a sampled token of the chain."""
384
+ flipped = {j: (t, e) for (j, t), e in zip(base["tokens"].items(), edited["tokens"].values())
385
+ if t != e}
386
+ if not flipped:
387
+ return None
388
+ j, (was, now) = next(iter(flipped.items()))
389
+ return (f"the edit flips the sampled token of t{j} ({was} -> {now}): the first-order term "
390
+ "does not cross a token change")
391
+
392
+
393
+ def _found(base: dict[str, Any], edited: dict[str, Any], seen: dict[str, dict[str, Any]],
394
+ shape: Any) -> dict[str, Any]:
395
+ """The prediction of two settled chains (``_settle``)."""
396
+ bound, base_bound = edited["bound"], base["bound"]
397
+ return {
398
+ "base": base["value"], "base_bound": base_bound, "exact": edited["value"] - base["value"],
399
+ "exact_bound": None if bound is None or base_bound is None else bound + base_bound,
400
+ "edit_shape": shape, "operands": list(seen.values()),
401
+ "unbounded": next((r for r in (edited["last"], base["last"]) if r is not None),
402
+ "no rounding bound for this chain"),
403
+ "operand_reason": base["first"] if base["first"] is not None else edited["first"],
404
+ "premises": base["premises"] | edited["premises"],
405
+ "broken": edited["broken"] or base["broken"],
406
+ "wide": edited["wide"] or base["wide"],
407
+ "walk_base": base["walk"], "walk_edited": edited["walk"],
408
+ }
409
+
410
+
411
+ WRITE_PREMISE = ("the edit is written by the engine's own arithmetic (PortEdit.apply, "
412
+ "CellEdit.realise) on the emulated value of the edited port or cache")
413
+
414
+
415
+ def _emulated_base(run: Any, p: Plan, shared: dict | None) -> dict[str, Any]:
416
+ """The emulated unedited chain (``EmulatedRowModel``: stops at or before the cursor as
417
+ captured, the rest with the dtype's rounding): the consumer's value, the sampled tokens and
418
+ the edited port's value ``x0`` (no row model is kept). The consumer's value does not depend
419
+ on the edit, so the what-ifs of one call with the same first row, consumer and cursor share
420
+ it (``shared``); ``x0`` is kept per edited port (a fresh first row model, evaluated only up
421
+ to that port, for a port not seen yet)."""
422
+ key = (p.row, p.consumer_stop, p.here)
423
+ out = None if shared is None else shared.get(key)
424
+ if out is None:
425
+ chain = _chain(run, p, bounds=False, model=EmulatedRowModel)
426
+ out = {"x0": {p.label: chain[0].get(p.label)},
427
+ "value": _consumer_value(p, chain[-1])[0],
428
+ "tokens": _sampled_tokens(p, chain, run), "walk": _walk(chain)}
429
+ del chain # one chain of row models alive at a time
430
+ if shared is not None:
431
+ shared[key] = out
432
+ if p.label not in out["x0"]:
433
+ first = _chain(run, p, bounds=False, model=EmulatedRowModel)[0]
434
+ out["x0"][p.label] = first.get(p.label)
435
+ del first
436
+ return out
437
+
438
+
439
+ def _emulated_written(run: Any, p: Plan, edit: Edit, x0: Any) -> Any:
440
+ """The value a port edit writes, by the engine's arithmetic (``PortEdit.apply``) on the
441
+ emulated (or captured) value of the port in the model dtype, as float64 in the chain's
442
+ shape."""
443
+ from mdb.engine.ports import PortEdit
444
+
445
+ shape = tuple(run.address_shape(p.edit_stop))
446
+ port = run.program.spec(_split(p.label)[1]).name
447
+ x = x0.reshape(shape).to(getattr(run.adapter, "device", None) or "cpu", run.adapter.dtype)
448
+ written = PortEdit(port, edit.value, edit.op, mask=edit.mask).apply(x)
449
+ return f64(written).reshape(x0.shape)
450
+
451
+
452
+ def _emulated_edited(run: Any, p: Plan, edit: Edit, written: Any) -> list[RowModel]:
453
+ """The emulated edited chain: the stops the edit reaches recomputed with the dtype's rounding,
454
+ the edit written at its port (``written``: a port edit's value) or into the cache (a cell
455
+ edit: the engine's own write, ``_written_cell``)."""
456
+ if edit.cell is not None:
457
+ return _chain(run, p, bounds=False, skip=True, model=EmulatedRowModel,
458
+ cell=_cell_writer(edit, _written_cell(run, edit), "written"))
459
+ return _chain(run, p, bounds=False, skip=True, model=EmulatedRowModel,
460
+ overrides={p.label: lambda value, bound: (written, None)})
461
+
462
+
463
+ def _emulate(run: Any, p: Plan, edit: Edit, shared: dict | None) -> dict[str, Any]:
464
+ """The emulated base and edited consumer values and their change, or ``emulated_reason``.
465
+ Staged and committed port edits are applied where the chains compute their stops
466
+ (``_edit_functions``); ``emulated_walk_*``: the stops each chain computed, by row (the stages
467
+ the measurement's checks walk)."""
468
+ try:
469
+ base = _emulated_base(run, p, shared)
470
+ written = None if edit.cell is not None else _emulated_written(run, p, edit,
471
+ base["x0"][p.label])
472
+ chain = _emulated_edited(run, p, edit, written)
473
+ edited = _consumer_value(p, chain[-1])[0]
474
+ walk = _walk(chain)
475
+ del chain
476
+ except Refusal as error:
477
+ return {"emulated_reason": str(error)}
478
+ return {"emulated_base": base["value"], "emulated_edited": edited,
479
+ "emulated": edited - base["value"], "emulated_written": written,
480
+ "emulated_walk_base": base["walk"], "emulated_walk_edited": walk}
481
+
482
+
483
+ def _walk(chain: list[RowModel]) -> list[tuple[int, str]]:
484
+ """The stops a chain computed, ``(row, stop)`` in row order."""
485
+ return [(model.row, name) for model in chain for name in model.computed]
486
+
487
+
488
+ def _predict_cell(run: Any, p: Plan, edit: Edit, *, linear: bool = True,
489
+ emulate: bool = True, shared: dict | None = None) -> dict[str, Any]:
490
+ """The prediction of a state-cell edit (``base``, ``exact`` and bounds, ``linear``), or
491
+ ``reason``: the chain from the first affected row with the cell written into the cache rows
492
+ every row reads. The base chain recomputes the same stops as the edited one, from the same
493
+ operands (P09 section 1: ``F(x1) - F(x0)``, never ``F(x1)`` minus a native value)."""
494
+ torch = _torch()
495
+ if p.row > p.here[0]:
496
+ return {"reason": f"the first read of {edit.address} is t{p.row}.{p.label}, in a row "
497
+ f"that has not started at the cursor {run.where}: none of its "
498
+ "operands exist yet"}
499
+ written = _written_cell(run, edit)
500
+ seen: dict[str, dict[str, Any]] = {}
501
+ base = _settle(run, p, _chain(run, p, bounds=True, skip=True), seen)
502
+ edited = _settle(run, p, _chain(run, p, bounds=True, skip=True,
503
+ cell=_cell_writer(edit, written, "ideal")), seen)
504
+ out = _found(base, edited, seen, None)
505
+ if emulate:
506
+ out.update(_emulate(run, p, edit, shared))
507
+ reason = _flip_reason(p, base, edited)
508
+ if reason is not None:
509
+ out["linear_reason"] = reason
510
+ return out
511
+ if not linear:
512
+ return out
513
+ import torch.autograd.forward_ad as fwad
514
+
515
+ with torch.inference_mode(False), fwad.dual_level():
516
+ dual = _chain(run, p, bounds=False, skip=True, tokens=base["tokens"],
517
+ cell=_cell_writer(edit, written, "tangent"))
518
+ primal, tangent = fwad.unpack_dual(_consumer_value(p, dual[-1])[0])
519
+ out["linear"] = (torch.zeros_like(primal) if tangent is None else tangent).detach().clone()
520
+ return out
521
+
522
+
523
+ def _predict(run: Any, p: Plan, edit: Edit, *, linear: bool = True, emulate: bool = True,
524
+ shared: dict | None = None) -> dict[str, Any]:
525
+ """The prediction's tensors (``base``, ``exact`` and bounds, ``linear``), or ``reason``.
526
+
527
+ ``exact = F(x1) - F(x0)`` (P09 section 1, P20): both chains hold the edited port at its value
528
+ at the cursor (``x0``: captured, or the chain's own value when the port is ahead) and
529
+ recompute the same stops (those the edit reaches) from the same operands, every other stop
530
+ taken as captured when it is at or before ``p.here``. ``linear`` (P14) is the forward-mode
531
+ derivative of that base chain at ``x0``. ``linear=False`` skips it (the post-hoc exact
532
+ chain on measured operands, ``_measured_exact``). With ``emulate`` the emulated base and
533
+ edited chains (``_emulate``) predict the native change itself; ``shared`` holds the emulated
534
+ base across the what-ifs of one call."""
535
+ torch = _torch()
536
+ if edit.cell is not None:
537
+ return _predict_cell(run, p, edit, linear=linear, emulate=emulate, shared=shared)
538
+ if p.row > p.here[0]:
539
+ return {"reason": f"the edit site t{p.row}.{p.label} is in a row that has not started at "
540
+ f"the cursor {run.where}: none of its operands exist yet"}
541
+ seen: dict[str, dict[str, Any]] = {}
542
+ head = _chain(run, p, bounds=True)[:1]
543
+ x0, b0, u = head[0].get(p.label), head[0].bound(p.label), head[0].u
544
+ _operands(run, head, seen)
545
+ del head # one chain of row models alive at a time
546
+ shape = tuple(x0.shape)
547
+ requested, delta, spread = _request(run, edit, shape, x0, b0, u)
548
+ base = _settle(run, p, _chain(run, p, bounds=True, skip=True,
549
+ overrides={p.label: lambda value, bound: (x0, b0)}), seen)
550
+ edited = _settle(run, p, _chain(run, p, bounds=True, skip=True,
551
+ overrides={p.label: lambda value, bound: (requested,
552
+ spread)}), seen)
553
+ out = _found(base, edited, seen, shape)
554
+ if emulate:
555
+ out.update(_emulate(run, p, edit, shared))
556
+ reason = _flip_reason(p, base, edited)
557
+ if reason is not None:
558
+ out["linear_reason"] = reason
559
+ return out
560
+ if not linear:
561
+ return out
562
+ import torch.autograd.forward_ad as fwad
563
+
564
+ with torch.inference_mode(False), fwad.dual_level():
565
+ point = x0.clone()
566
+ dual = _chain(run, p, bounds=False, skip=True, tokens=base["tokens"],
567
+ overrides={p.label: lambda value, bound: (fwad.make_dual(point, delta),
568
+ None)})
569
+ primal, tangent = fwad.unpack_dual(_consumer_value(p, dual[-1])[0])
570
+ out["linear"] = (torch.zeros_like(primal) if tangent is None else tangent).detach().clone()
571
+ return out
572
+
573
+
574
+ # --------------------------------------------------------------------------- measurement
575
+
576
+
577
+
578
+
579
+ # --------------------------------------------------------------------------- report
580
+
581
+
582
+ def _operands(run: Any, models: list[RowModel], seen: dict[str, dict[str, Any]]) -> None:
583
+ """Add the address, digest and shape of every captured operand of ``models`` to ``seen``
584
+ (the first chain to read an address names it)."""
585
+ from mdb.engine.ports import tensor_digest
586
+
587
+ for model in models:
588
+ tensors = {**{f"t{model.row}.{n}": t for n, t in model.captured.items()},
589
+ **{f"{n}[row=0:{model.row}]": t for n, t in model.cache_reads.items()}}
590
+ for address, tensor in tensors.items():
591
+ seen.setdefault(address, {"address": address,
592
+ "sha256": tensor_digest(tensor.contiguous()),
593
+ "shape": list(tensor.shape)})
594
+
595
+
596
+ __all__ = ["WHATIF"]