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,1465 @@
1
+ """Breakpoints, watches and run-to-hit over a port-level ``Run``, kept as plain data.
2
+
3
+ A breakpoint is an address pattern (``L*.p``, ``t5.L1.o``, ``t*.logits``) plus an optional
4
+ condition; a watch is an address pattern plus an optional predicate and a mode:
5
+
6
+ * ``change``: fires when the selected value differs (bitwise) from the value seen at the
7
+ previous matching stop (and the predicate, if any, holds). The baseline is the value at the
8
+ time the watch is set (the cursor's stop, or the nearest earlier matching stop of the cursor's
9
+ row); with none, the first evaluation only records it.
10
+ * ``level``: fires at every matching stop where the predicate holds.
11
+ * ``edge``: fires where the predicate holds and did not hold at the previous matching stop
12
+ (the state before the first evaluation counts as not holding).
13
+
14
+ A pattern's selector (``L*.p[h0]``) does not restrict where it stops; it selects the part of
15
+ the port value that conditions and watches see.
16
+
17
+ Conditions are a small safe expression language, parsed with ``ast.parse(mode="eval")`` and
18
+ checked against a node whitelist::
19
+
20
+ norm > 3 and argmax == 2 # reductions of the (selected) port value
21
+ abs_max(v["h0,src=3"]) < 0.5 # a reduction of an address selector on the full value
22
+ v[0, 0, 3] > 0 # one element of the selected value (kept dimensions)
23
+
24
+ Reductions: ``norm min max mean abs_max argmax numel``. Allowed syntax: numeric literals,
25
+ ``+ - * /``, comparisons, ``and or not``, unary minus, subscripts of ``v`` (integers or one
26
+ quoted selector) and calls of the reductions with one argument. Nothing else.
27
+
28
+ ``run_forward`` walks the stops after the cursor in order, and at every stop matched by an
29
+ armed breakpoint or watch moves the cursor there with ``Run.until`` (exact port), evaluates,
30
+ and either stops or keeps going, until a hit, a token budget, or the end of the context.
31
+ ``run_reverse`` walks backwards reading past values without moving, then moves to the hit
32
+ with ``Run.reverse_step``. Neither edits ``run.py`` or ``ports.py``.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import ast
38
+ import dataclasses
39
+ import math
40
+ from collections.abc import Sequence
41
+ from dataclasses import dataclass, field
42
+ from typing import Any
43
+
44
+ import torch
45
+
46
+ from mdb.core import address as addresses
47
+
48
+ from .ports import tensor_digest
49
+
50
+ GLOBALS = (*addresses.DEFAULT_GLOBALS, "start")
51
+ _D = ("batch", "row", "d_model")
52
+ GLOBAL_AXES = {
53
+ "start": ("batch", "row"),
54
+ "emb": _D,
55
+ "fn": _D,
56
+ "logits": ("batch", "vocab"),
57
+ "sample": ("batch", "row"),
58
+ }
59
+ CELL_AXES = ("batch", "kv_head", "row", "head_dim")
60
+ REDUCTIONS = ("norm", "min", "max", "mean", "abs_max", "argmax", "numel")
61
+ WATCH_MODES = ("change", "level", "edge")
62
+ _MAX_CONDITION = 256
63
+ _MAX_NODES = 64
64
+
65
+
66
+ class ConditionError(ValueError):
67
+ """A condition is malformed or uses syntax outside the whitelist."""
68
+
69
+
70
+ class SelectionError(ValueError):
71
+ """A selector does not fit the value's axes."""
72
+
73
+
74
+ class SelectionRange(SelectionError):
75
+ """A selector (or a breakpoint layer) is outside the size of its axis. Checked against the
76
+ axis size before anything is materialised, so ``d=0:10**15`` costs nothing."""
77
+
78
+
79
+ # --------------------------------------------------------------------------- addresses
80
+
81
+
82
+ def stop_occurrence(row: int, label: str) -> addresses.Occurrence:
83
+ """The occurrence address of a ``Run`` stop label (``L0.p``, ``logits``, ``start``)."""
84
+ if label.startswith("L") and "." in label:
85
+ layer, port = label.split(".", 1)
86
+ return addresses.Occurrence(row, port, int(layer[1:]))
87
+ return addresses.Occurrence(row, label)
88
+
89
+
90
+ def stop_axes(program: Any, label: str) -> tuple[str, ...]:
91
+ if label in GLOBAL_AXES:
92
+ return GLOBAL_AXES[label]
93
+ return program.spec(label.split(".", 1)[1]).axes
94
+
95
+
96
+ def parse_pattern(text: str, program: Any) -> addresses.Pattern:
97
+ """A breakpoint pattern; a bare port means ``L*.<port>``, a bare global ``t*.<global>``."""
98
+ text = text.strip()
99
+ base = text.split("[", 1)[0]
100
+ if base in program.names:
101
+ text = "L*." + text
102
+ elif base in GLOBALS:
103
+ text = "t*." + text
104
+ pattern = addresses.parse_pattern(text, ports=program.names, global_ports=GLOBALS)
105
+ if pattern.origin is not None or pattern.program is not None:
106
+ raise addresses.AddressError("breakpoint origins and programs are not supported yet")
107
+ if pattern.kind == "cell" and not isinstance(pattern.layer, int):
108
+ raise addresses.AddressError("a cache-cell breakpoint needs a concrete layer, e.g. "
109
+ "cache.L0.k[kv0]")
110
+ if pattern.step is not None:
111
+ raise addresses.AddressError("the decoder engine has no diffusion-step clock")
112
+ return pattern
113
+
114
+
115
+ def location(pattern: addresses.Pattern) -> addresses.Pattern:
116
+ """The pattern without its selector: where it stops (the selector picks what it sees)."""
117
+ return dataclasses.replace(pattern, selector=addresses.Selector())
118
+
119
+
120
+ def stops_at(pattern: addresses.Pattern, occurrence: addresses.Occurrence) -> bool:
121
+ """Whether a debugger stop matches a pattern; selectors never constrain a stop. A cache
122
+ cell (``cache.L0.k[...]``) is read at the committed boundary, so it matches boundary stops
123
+ only (the globals and every layer's ``h_out``)."""
124
+ if pattern.kind == "cell":
125
+ return occurrence.port in GLOBALS or occurrence.port == "h_out"
126
+ matcher = getattr(addresses, "matches_stop", None)
127
+ if matcher is not None:
128
+ return matcher(pattern, occurrence)
129
+ return addresses.matches(location(pattern), occurrence)
130
+
131
+
132
+ # --------------------------------------------------------------------------- selection
133
+
134
+
135
+ @dataclass
136
+ class Selection:
137
+ """A selected part of a value: the sub-tensor (dimensions kept) and original indices."""
138
+
139
+ value: torch.Tensor
140
+ axes: tuple[str, ...]
141
+ coords: list[list[int]]
142
+
143
+ def original(self, flat: int) -> list[int]:
144
+ index = []
145
+ for size, coord in zip(reversed(self.value.shape), reversed(self.coords)):
146
+ index.append(coord[flat % size])
147
+ flat //= size
148
+ return index[::-1]
149
+
150
+
151
+ def _indices(value: Any, size: int | None, key: str, axis: str = "") -> Sequence[int]:
152
+ """The picked positions of one selector key: an int list or a lazy ``range``, validated
153
+ against the axis ``size`` (None: unknown here, checked at evaluation) before any expansion."""
154
+ where = f" (axis {axis!r} has size {size})" if axis else f" (size {size})"
155
+ if isinstance(value, int):
156
+ if size is not None and value >= size:
157
+ raise SelectionRange(f"selector {key}={value} is out of range{where}")
158
+ return (value,)
159
+ if isinstance(value, addresses.Span):
160
+ if size is not None and value.stop > size:
161
+ raise SelectionRange(
162
+ f"selector {key}={value.start}:{value.stop} is out of range{where}")
163
+ return range(value.start, value.stop)
164
+ items = tuple(value.values)
165
+ if size is not None:
166
+ bad = [item for item in items if item >= size]
167
+ if bad:
168
+ raise SelectionRange(f"selector {key}={bad[0]} is out of range{where}")
169
+ return items
170
+
171
+
172
+ def _token_ids(tokens: tuple, tokenizer: Any) -> list[int]:
173
+ ids = []
174
+ for token in tokens:
175
+ if token.id is not None:
176
+ ids.append(token.id)
177
+ continue
178
+ if tokenizer is None:
179
+ raise SelectionError(
180
+ f"token text {token.text!r} needs a tokenizer; write it as {token.text!r}=ID"
181
+ )
182
+ encoded = tokenizer.encode(token.text, add_special_tokens=False)
183
+ if len(encoded) != 1:
184
+ raise SelectionError(f"{token.text!r} is {len(encoded)} tokens, not one")
185
+ ids.append(int(encoded[0]))
186
+ return ids
187
+
188
+
189
+ def plan(
190
+ axes: tuple[str, ...],
191
+ sizes: Sequence[int | None],
192
+ selector: addresses.Selector,
193
+ *,
194
+ head_dim: int | None = None,
195
+ row: int | None = None,
196
+ tokenizer: Any = None,
197
+ ) -> list[Sequence[int] | None]:
198
+ """Bound-check a selector against axis ``sizes`` (None = unknown) and return the picked
199
+ positions per axis (None = the whole axis). Nothing is allocated beyond the axis size."""
200
+ if len(axes) != len(sizes):
201
+ raise SelectionError(f"value has {len(sizes)} dimensions, axes {axes}")
202
+ picks: list[Sequence[int] | None] = [None] * len(axes)
203
+ keys = dict(selector.keys)
204
+
205
+ def axis(*names: str) -> int | None:
206
+ for name in names:
207
+ if name in axes:
208
+ return axes.index(name)
209
+ return None
210
+
211
+ for key, flat, block in (("h", "head*head_dim", "head"), ("kv", "kv_head*head_dim", "kv_head")):
212
+ if key not in keys:
213
+ continue
214
+ at = axis(block)
215
+ if at is not None:
216
+ picks[at] = _indices(keys.pop(key), sizes[at], key, axes[at])
217
+ continue
218
+ at = axis(flat)
219
+ if at is None or not head_dim:
220
+ raise SelectionError(f"selector {key} does not apply to axes {axes}")
221
+ count = None if sizes[at] is None else sizes[at] // head_dim
222
+ heads = _indices(keys.pop(key), count, key, block)
223
+ offsets: Sequence[int] = range(head_dim)
224
+ if "d" in keys:
225
+ offsets = _indices(keys.pop("d"), head_dim, "d", "head_dim")
226
+ picks[at] = [h * head_dim + d for h in heads for d in offsets]
227
+ for key, names in (("src", ("src",)), ("i", ("d_ff", "vocab")),
228
+ ("d", ("d_model", "head_dim", "head*head_dim", "kv_head*head_dim"))):
229
+ if key not in keys:
230
+ continue
231
+ at = axis(*names)
232
+ if at is None:
233
+ raise SelectionError(f"selector {key} does not apply to axes {axes}")
234
+ picks[at] = _indices(keys.pop(key), sizes[at], key, axes[at])
235
+ if "row" in keys:
236
+ at = axis("row")
237
+ if at is None:
238
+ raise SelectionError(f"selector row does not apply to axes {axes}")
239
+ wanted = keys.pop("row")
240
+ if row is not None:
241
+ if wanted != row:
242
+ raise SelectionError(f"this value holds only row {row}")
243
+ picks[at] = (0,)
244
+ else:
245
+ picks[at] = _indices(wanted, sizes[at], "row", axes[at])
246
+ if selector.tokens:
247
+ at = axis("vocab")
248
+ if at is None:
249
+ raise SelectionError(f"token selectors apply to a vocabulary axis, not {axes}")
250
+ if picks[at] is not None:
251
+ raise SelectionError("select vocabulary entries by i or by token text, not both")
252
+ ids = _token_ids(selector.tokens, tokenizer)
253
+ for token_id in ids:
254
+ _indices(token_id, sizes[at], "token", axes[at])
255
+ picks[at] = ids # given order kept: M[" hot"," cold"] is an ordered contrast
256
+ return picks
257
+
258
+
259
+ def select(
260
+ value: torch.Tensor,
261
+ axes: tuple[str, ...],
262
+ selector: addresses.Selector,
263
+ *,
264
+ head_dim: int | None = None,
265
+ row: int | None = None,
266
+ tokenizer: Any = None,
267
+ ) -> Selection:
268
+ """Apply an address selector to a port value with the given axis names.
269
+
270
+ Keys map to axes: ``h`` head (or a head block of a flat ``head*head_dim`` axis), ``kv`` kv
271
+ head (or block), ``src`` source position, ``row`` token row, ``i`` the d_ff or vocabulary
272
+ axis, ``d`` d_model, head_dim, or the offset inside a selected head block. Token text
273
+ selects vocabulary entries. ``row`` is absolute: when the value holds only the clock row
274
+ (``row`` given), the selector must name that row. Ranges are checked against the axis size
275
+ before they are expanded (``SelectionRange``).
276
+ """
277
+ if len(axes) != value.dim():
278
+ raise SelectionError(f"value has {value.dim()} dimensions, axes {axes}")
279
+ picks = plan(axes, list(value.shape), selector, head_dim=head_dim, row=row,
280
+ tokenizer=tokenizer)
281
+ out = value
282
+ coords = []
283
+ for at, pick in enumerate(picks):
284
+ if pick is None:
285
+ coords.append(list(range(value.shape[at])))
286
+ continue
287
+ pick = list(pick)
288
+ out = out.index_select(at, torch.tensor(pick, dtype=torch.long, device=out.device))
289
+ coords.append(pick)
290
+ return Selection(out, tuple(axes), coords)
291
+
292
+
293
+ def axis_sizes(adapter: Any, axes: tuple[str, ...]) -> list[int | None]:
294
+ """Axis sizes knowable without a value (None: depends on the row, e.g. ``src``)."""
295
+ heads, kv = getattr(adapter, "num_heads", None), getattr(adapter, "num_kv_heads", None)
296
+ head_dim = getattr(adapter, "head_dim", None)
297
+ inter = getattr(adapter, "intermediate_size", None)
298
+ if inter is None:
299
+ inter = getattr(getattr(getattr(adapter, "model", None), "config", None),
300
+ "intermediate_size", None)
301
+ known = {
302
+ "batch": 1, "d_model": getattr(adapter, "hidden_size", None), "head": heads,
303
+ "kv_head": kv, "head_dim": head_dim, "d_ff": inter,
304
+ "vocab": getattr(adapter, "vocab_size", None),
305
+ "head*head_dim": None if heads is None or head_dim is None else heads * head_dim,
306
+ "kv_head*head_dim": None if kv is None or head_dim is None else kv * head_dim,
307
+ }
308
+ return [known.get(name) for name in axes]
309
+
310
+
311
+ def _float(value: torch.Tensor) -> torch.Tensor:
312
+ return value.detach().to(torch.float64)
313
+
314
+
315
+ def nonfinite(value: torch.Tensor) -> dict[str, int]:
316
+ """Integer counts of NaN, +Inf and -Inf elements."""
317
+ flat = value.detach().reshape(-1)
318
+ if not flat.is_floating_point():
319
+ return {"nan": 0, "posinf": 0, "neginf": 0}
320
+ return {"nan": int(torch.isnan(flat).sum()), "posinf": int(torch.isposinf(flat).sum()),
321
+ "neginf": int(torch.isneginf(flat).sum())}
322
+
323
+
324
+ def reduce(selection: Selection) -> dict[str, Any]:
325
+ """Plain-float reductions of a selection (callers attach authority labels).
326
+
327
+ With NaN/Inf elements the statistics run over the finite elements (``over: "finite"``)
328
+ and ``nonfinite`` holds the integer counts; with no finite element there are no statistics
329
+ and ``unresolved`` says why.
330
+ """
331
+ value = selection.value
332
+ if value.numel() == 0:
333
+ raise SelectionError("the selection is empty")
334
+ flat = _float(value).reshape(-1)
335
+ finite = torch.isfinite(flat)
336
+ bad = int(flat.numel() - finite.sum())
337
+ out: dict[str, Any] = {"numel": int(value.numel())}
338
+ if bad:
339
+ out["over"] = "finite"
340
+ out["nonfinite"] = nonfinite(flat)
341
+ if bad == flat.numel():
342
+ out["unresolved"] = "no finite element"
343
+ return out
344
+ positions = finite.nonzero().reshape(-1)
345
+ work = flat[positions]
346
+ else:
347
+ positions, work = None, flat
348
+ at = int(torch.argmax(work))
349
+ argmax = at if positions is None else int(positions[at])
350
+ out.update({
351
+ "norm": float(torch.linalg.vector_norm(work)),
352
+ "min": float(work.min()),
353
+ "max": float(work.max()),
354
+ "mean": float(work.mean()),
355
+ "abs_max": float(work.abs().max()),
356
+ "argmax": argmax,
357
+ "argmax_index": selection.original(argmax),
358
+ })
359
+ return out
360
+
361
+
362
+ def top(selection: Selection, k: int, *, signed: bool = False) -> list[tuple[list[int], float]]:
363
+ """The ``k`` largest finite entries by absolute value, or by value with ``signed`` (logits:
364
+ the top tokens), stable: ties keep flat order; non-finite elements are not ranked
365
+ (``nonfinite`` counts them)."""
366
+ flat = _float(selection.value).reshape(-1)
367
+ key = flat if signed else flat.abs()
368
+ finite = torch.isfinite(flat)
369
+ if bool(finite.all()):
370
+ order = torch.sort(-key, stable=True).indices[:k].tolist()
371
+ else:
372
+ positions = finite.nonzero().reshape(-1)
373
+ ranked = torch.sort(-key[positions], stable=True).indices[:k]
374
+ order = positions[ranked].tolist()
375
+ return [(selection.original(i), float(flat[i])) for i in order]
376
+
377
+
378
+ # --------------------------------------------------------------------------- conditions
379
+
380
+ _COMPARE = {
381
+ ast.Lt: lambda a, b: a < b,
382
+ ast.LtE: lambda a, b: a <= b,
383
+ ast.Gt: lambda a, b: a > b,
384
+ ast.GtE: lambda a, b: a >= b,
385
+ ast.Eq: lambda a, b: a == b,
386
+ ast.NotEq: lambda a, b: a != b,
387
+ }
388
+ _BINARY = {
389
+ ast.Add: lambda a, b: a + b,
390
+ ast.Sub: lambda a, b: a - b,
391
+ ast.Mult: lambda a, b: a * b,
392
+ ast.Div: lambda a, b: a / b,
393
+ }
394
+
395
+
396
+ def parse_selector(text: str) -> addresses.Selector:
397
+ try:
398
+ return addresses.parse(f"t0.L0.h[{text}]").selector
399
+ except addresses.AddressError as error:
400
+ raise ConditionError(f"bad selector {text!r}: {error.reason}") from None
401
+
402
+
403
+ class Condition:
404
+ """A parsed, whitelisted condition over reductions of one port value.
405
+
406
+ ``sites`` (None for an ordinary condition) is the set of layers a MULTI-SITE condition
407
+ (``analysis.features.watch.FeatureCondition`` over several contexts) reads: the item only stops
408
+ at those layers, keeps one watch memory per layer (so an edge or change watch over L0..Ln is
409
+ the same as one watch per layer) and reports the stop it fired at (``site``, ``layer``)."""
410
+
411
+ sites: frozenset[int] | None = None
412
+
413
+ def __init__(self, text: str):
414
+ if not isinstance(text, str) or not text.strip():
415
+ raise ConditionError("a condition is non-empty text")
416
+ if len(text) > _MAX_CONDITION:
417
+ raise ConditionError(f"a condition is at most {_MAX_CONDITION} characters")
418
+ self.text = text.strip()
419
+ try:
420
+ tree = ast.parse(self.text, mode="eval")
421
+ except SyntaxError as error:
422
+ raise ConditionError(f"invalid condition: {error.msg}") from None
423
+ self._nodes = 0
424
+ self._check(tree.body)
425
+ self.tree = tree.body
426
+
427
+ # --- whitelist -----------------------------------------------------------------------
428
+
429
+ def _check(self, node: ast.AST, *, value_ok: bool = False) -> None:
430
+ self._nodes += 1
431
+ if self._nodes > _MAX_NODES:
432
+ raise ConditionError("condition is too complex")
433
+ if isinstance(node, ast.Constant):
434
+ if isinstance(node.value, bool) or not isinstance(node.value, (int, float)):
435
+ raise ConditionError("only numeric literals are allowed")
436
+ if not math.isfinite(node.value):
437
+ raise ConditionError("literals must be finite")
438
+ return
439
+ if isinstance(node, ast.Name):
440
+ if node.id in REDUCTIONS:
441
+ return
442
+ if node.id == "v" and value_ok:
443
+ return
444
+ raise ConditionError(
445
+ f"unknown name {node.id!r}; use {', '.join(REDUCTIONS)} or v[...]"
446
+ )
447
+ if isinstance(node, ast.BoolOp):
448
+ for item in node.values:
449
+ self._check(item)
450
+ return
451
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.Not, ast.USub, ast.UAdd)):
452
+ self._check(node.operand)
453
+ return
454
+ if isinstance(node, ast.BinOp) and type(node.op) in _BINARY:
455
+ self._check(node.left)
456
+ self._check(node.right)
457
+ return
458
+ if isinstance(node, ast.Compare) and all(type(op) in _COMPARE for op in node.ops):
459
+ self._check(node.left)
460
+ for item in node.comparators:
461
+ self._check(item)
462
+ return
463
+ if isinstance(node, ast.Subscript):
464
+ if not (isinstance(node.value, ast.Name) and node.value.id == "v"):
465
+ raise ConditionError("only v[...] may be subscripted")
466
+ self._check_index(node.slice)
467
+ return
468
+ if isinstance(node, ast.Call):
469
+ if not isinstance(node.func, ast.Name) or node.func.id not in REDUCTIONS:
470
+ raise ConditionError(f"only reductions may be called: {', '.join(REDUCTIONS)}")
471
+ if node.keywords or len(node.args) != 1:
472
+ raise ConditionError(f"{node.func.id}(...) takes one value")
473
+ self._check(node.args[0], value_ok=True)
474
+ return
475
+ raise ConditionError(f"syntax {type(node).__name__} is not allowed in a condition")
476
+
477
+ def _check_index(self, node: ast.AST) -> None:
478
+ items = node.elts if isinstance(node, ast.Tuple) else [node]
479
+ if len(items) == 1 and isinstance(items[0], ast.Constant) and isinstance(
480
+ items[0].value, str
481
+ ):
482
+ return
483
+ for item in items:
484
+ if isinstance(item, ast.UnaryOp) and isinstance(item.op, ast.USub):
485
+ item = item.operand
486
+ if not (isinstance(item, ast.Constant) and type(item.value) is int):
487
+ raise ConditionError('v[...] takes integers or one quoted selector, v["h0"]')
488
+
489
+ def selector_texts(self) -> list[str]:
490
+ """The quoted selector strings of ``v["..."]`` subscripts (checked at creation)."""
491
+ found = []
492
+ for node in ast.walk(self.tree):
493
+ if isinstance(node, ast.Subscript):
494
+ items = node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]
495
+ if len(items) == 1 and isinstance(items[0], ast.Constant) and isinstance(
496
+ items[0].value, str
497
+ ):
498
+ found.append(items[0].value)
499
+ return found
500
+
501
+ # --- evaluation ----------------------------------------------------------------------
502
+
503
+ def evaluate(self, env: ConditionEnv) -> bool:
504
+ return bool(self._eval(self.tree, env))
505
+
506
+ def _eval(self, node: ast.AST, env: ConditionEnv) -> Any:
507
+ if isinstance(node, ast.Constant):
508
+ return node.value
509
+ if isinstance(node, ast.Name):
510
+ if node.id == "v":
511
+ return env.selection
512
+ return env.reduction(node.id, env.selection)
513
+ if isinstance(node, ast.BoolOp):
514
+ if isinstance(node.op, ast.And):
515
+ return all(self._eval(item, env) for item in node.values)
516
+ return any(self._eval(item, env) for item in node.values)
517
+ if isinstance(node, ast.UnaryOp):
518
+ operand = _scalar(self._eval(node.operand, env))
519
+ if isinstance(node.op, ast.Not):
520
+ return not operand
521
+ return -operand if isinstance(node.op, ast.USub) else operand
522
+ if isinstance(node, ast.BinOp):
523
+ left = _scalar(self._eval(node.left, env))
524
+ right = _scalar(self._eval(node.right, env))
525
+ if isinstance(node.op, ast.Div) and right == 0:
526
+ raise ConditionError("division by zero in a condition")
527
+ return _BINARY[type(node.op)](left, right)
528
+ if isinstance(node, ast.Compare):
529
+ left = _scalar(self._eval(node.left, env))
530
+ for op, item in zip(node.ops, node.comparators):
531
+ right = _scalar(self._eval(item, env))
532
+ if not _COMPARE[type(op)](left, right):
533
+ return False
534
+ left = right
535
+ return True
536
+ if isinstance(node, ast.Subscript):
537
+ return env.subscript(node.slice)
538
+ if isinstance(node, ast.Call):
539
+ return env.reduction(node.func.id, self._eval(node.args[0], env))
540
+ raise ConditionError(f"cannot evaluate {type(node).__name__}")
541
+
542
+
543
+ def _scalar(value: Any) -> float:
544
+ if isinstance(value, Selection):
545
+ if value.value.numel() != 1:
546
+ raise ConditionError(
547
+ f"a value of {value.value.numel()} elements is not a number; reduce it"
548
+ )
549
+ return float(value.value.reshape(-1)[0].to(torch.float64))
550
+ return value
551
+
552
+
553
+ @dataclass
554
+ class ConditionEnv:
555
+ """What a condition sees at one stop: the full port value and the pattern's selection."""
556
+
557
+ full: torch.Tensor
558
+ selection: Selection
559
+ axes: tuple[str, ...]
560
+ head_dim: int | None = None
561
+ row: int | None = None
562
+ tokenizer: Any = None
563
+ run: Any = None # the run at the stop: predicates that read more than the port value
564
+ site: str | None = None # the stop's address (``t4.L1.h``): multi-site predicates pick by layer
565
+
566
+ def reduction(self, name: str, value: Any) -> Any:
567
+ if not isinstance(value, Selection):
568
+ raise ConditionError(f"{name}(...) needs a value, not a number")
569
+ result = reduce(value)
570
+ if "unresolved" in result and name != "numel":
571
+ raise ConditionError(f"{name}(...): {result['unresolved']}")
572
+ return result[name]
573
+
574
+ def subscript(self, node: ast.AST) -> Selection:
575
+ items = node.elts if isinstance(node, ast.Tuple) else [node]
576
+ if isinstance(items[0], ast.Constant) and isinstance(items[0].value, str):
577
+ selector = parse_selector(items[0].value)
578
+ return select(self.full, self.axes, selector, head_dim=self.head_dim, row=self.row,
579
+ tokenizer=self.tokenizer)
580
+ index = []
581
+ for item in items:
582
+ negative = isinstance(item, ast.UnaryOp)
583
+ raw = (item.operand if negative else item).value
584
+ index.append(-raw if negative else raw)
585
+ value = self.selection.value
586
+ if len(index) != value.dim():
587
+ raise ConditionError(f"v[...] needs {value.dim()} indices (dimensions are kept)")
588
+ try:
589
+ element = value[tuple(index)]
590
+ except IndexError as error:
591
+ raise ConditionError(f"v{index} is out of range: {error}") from None
592
+ flat = 0
593
+ for size, i in zip(value.shape, index):
594
+ flat = flat * size + (i % size)
595
+ coords = [[c] for c in self.selection.original(flat)]
596
+ return Selection(element.reshape([1] * value.dim()), self.selection.axes, coords)
597
+
598
+
599
+ # --------------------------------------------------------------------------- provenance
600
+
601
+ UNDER_SHOWN = 8
602
+
603
+
604
+ def _selected_mask(shape: tuple[int, ...] | None, selection: Selection | None) -> torch.Tensor | None:
605
+ """The selection as a bool mask over the port (None when it is the whole port or does not
606
+ fit the port's shape)."""
607
+ if selection is None or shape is None or len(selection.coords) != len(shape) or any(
608
+ len(c) and max(c) >= size for c, size in zip(selection.coords, shape)
609
+ ):
610
+ return None
611
+ chosen = torch.zeros(shape, dtype=torch.bool)
612
+ index = tuple(torch.tensor(c, dtype=torch.long).view(
613
+ [-1 if a == axis else 1 for a in range(len(shape))])
614
+ for axis, c in enumerate(selection.coords))
615
+ chosen[index] = True
616
+ return chosen
617
+
618
+
619
+ def _unedited(run: Any, port: str | None) -> bool:
620
+ """No edit anywhere in the run (the label is then measured without asking the engine).
621
+ ``s`` is a replica port: it is always labelled by the engine."""
622
+ return (port != "s" and not run.edits and not run.committed_edits()
623
+ and not getattr(run, "cells", None) and not _committed_cells(run))
624
+
625
+
626
+ def _committed_cells(run: Any) -> list[dict[str, Any]]:
627
+ found = getattr(run, "committed_cells", None)
628
+ return found() if found is not None else []
629
+
630
+
631
+ def provenance(run: Any, address: str, selection: Selection | None = None) -> dict[str, Any]:
632
+ """Where a (selected) value came from, from ``Run.read_info`` and ``Run.edit_mask``.
633
+
634
+ * ``authority`` ``measured | derived-exact | derived-local | supplied`` (None when the
635
+ engine refused to label it, with ``state``/``reason``) and ``kind``
636
+ (``native | edit | realisation | replica``);
637
+ * a selection of an edited port is labelled by the operations of the edits whose masks
638
+ cover the selected elements, staged or committed alike: every selected element's last
639
+ write a replace -> ``supplied``; some written -> ``derived-exact`` (``mixed`` counts when
640
+ some elements were not); none written -> the native label with ``same_port_edit``;
641
+ * ``under_edits``: edits that fired before this value in program order (it keeps its own
642
+ label, ``measured``), the first few as ``{address, op, staged}`` and ``under_edits_total``.
643
+ """
644
+ port = address.rsplit(".", 1)[-1] if "." in address else address
645
+ if _unedited(run, port):
646
+ return _with_origin(run, {
647
+ "authority": "measured", "edited": False, "kind": "native", "by": None,
648
+ "ops": [], "under_edits": [], "under_edits_total": 0, "replica_equal": None,
649
+ "max_abs_diff": None, "port": port, "state": "resolved", "reason": None})
650
+ wide = _selected_mask(run.address_shape(address), selection)
651
+ info = run.read_info(address, select=wide)
652
+ ups = info.get("upstream_edits") or []
653
+ out: dict[str, Any] = {
654
+ "authority": info["authority"], "edited": bool(info["edited"]), "kind": info["kind"],
655
+ "by": info["by"], "ops": list(info.get("ops") or []),
656
+ "under_edits": [{"address": u.get("cell") or f"t{u['row']}.L{u['layer']}.{u['port']}",
657
+ "op": u["op"], "staged": bool(u["staged"])} for u in ups[:UNDER_SHOWN]],
658
+ "under_edits_total": len(ups),
659
+ "replica_equal": info.get("replica_equal"), "max_abs_diff": info.get("max_abs_diff"),
660
+ "replica_checked": info.get("replica_checked"), "port": port, "state": info["state"], "reason": info["reason"],
661
+ }
662
+ for key in ("realisation_exact", "realisation_max_abs_error"):
663
+ if info.get(key) is not None:
664
+ out[key] = info[key]
665
+ if info["edited"]:
666
+ mask = run.edit_mask(address)
667
+ if mask is not None:
668
+ chosen = mask if wide is None or wide.shape != mask.shape else mask & wide
669
+ total = int(mask.numel() if wide is None or wide.shape != mask.shape else wide.sum())
670
+ written = int(chosen.sum())
671
+ if 0 < written < total:
672
+ out["mixed"] = {"written": written, "untouched": total - written}
673
+ if info.get("same_port_edit"):
674
+ out["same_port_edit"] = dict(info["same_port_edit"])
675
+ return _with_origin(run, out)
676
+
677
+
678
+ def _with_origin(run: Any, out: dict[str, Any]) -> dict[str, Any]:
679
+ """``out`` with ``from_checkpoint`` when ``run`` is rooted at a checkpoint (the label every
680
+ value of such a run carries until its path is verified: ``Run.from_checkpoint``)."""
681
+ origin = getattr(run, "from_checkpoint", None)
682
+ if origin is not None:
683
+ out["from_checkpoint"] = dict(origin)
684
+ return out
685
+
686
+
687
+ def _cell_rows(run: Any, selection: Selection | None) -> list[int]:
688
+ """The cache rows a cell selection covers (all rows written so far for no selection)."""
689
+ if selection is not None and len(selection.coords) == len(CELL_AXES):
690
+ return list(selection.coords[CELL_AXES.index("row")])
691
+ return list(range(run.read_cache(0, "k").shape[2]))
692
+
693
+
694
+ # The ports whose edit can change the key (value) row this transition writes into the cache,
695
+ # per tensor kind: the layer input, the normed input, and the projection itself.
696
+ _CELL_WRITERS = {"k": ("h", "a", "k", "kn"), "v": ("h", "a", "v")}
697
+
698
+
699
+ def cell_provenance(
700
+ run: Any, layer: int, selection: Selection | None = None, tensor: str | None = None
701
+ ) -> dict[str, Any]:
702
+ """A cache cell is read at the committed boundary: ``measured``, under the committed edits
703
+ that can have reached it. An edit at (row r, layer l) reaches the cell (cache row j, layer L)
704
+ when j == r and either L > l or (L == l and the edit is at a port that feeds this tensor's
705
+ cache write), or j > r and L > l (a later row reads the changed rows through attention, and
706
+ its own cache write at layer l is computed before that layer's attention)."""
707
+ rows = _cell_rows(run, selection)
708
+ writers = _CELL_WRITERS.get(tensor) if tensor else None
709
+
710
+ def reaches(e: dict[str, Any]) -> bool:
711
+ same_layer = layer == e["layer"] and (
712
+ writers is None or run.program.spec(e["port"]).name in writers
713
+ )
714
+ for j in rows:
715
+ if j == e["row"] and (layer > e["layer"] or same_layer):
716
+ return True
717
+ if j > e["row"] and layer > e["layer"]:
718
+ return True
719
+ return False
720
+
721
+ ups = [e for e in run.committed_edits() if reaches(e)]
722
+ out = {"authority": "measured", "edited": False, "kind": "native", "by": None, "ops": [],
723
+ "under_edits": [{"address": f"t{e['row']}.L{e['layer']}.{e['port']}",
724
+ "op": e["op"], "staged": False} for e in ups[:UNDER_SHOWN]],
725
+ "under_edits_total": len(ups), "replica_equal": None, "max_abs_diff": None,
726
+ "state": "resolved", "reason": None}
727
+ if tensor is not None:
728
+ out.update(_cell_writes(run, layer, tensor, selection))
729
+ return _with_origin(run, out)
730
+
731
+
732
+ def _cell_writes(run: Any, layer: int, tensor: str, selection: Selection | None
733
+ ) -> dict[str, Any]:
734
+ """The label of a cell read under the state-cell edits that wrote it (committed, then
735
+ staged, in order): ``supplied`` when every selected element's last write is an exact copy
736
+ of a supplied value (``replace``, ``mix 1``), ``derived-exact`` when any selected element
737
+ was written otherwise; nothing when no cell edit wrote a selected element."""
738
+ from .edits import CellEdit
739
+
740
+ staged = getattr(run, "staged_cells", None)
741
+ writes = [*_committed_cells(run), *(staged() if staged is not None else [])]
742
+ writes = [w for w in writes if (w["cell"]["layer"], w["cell"]["tensor"]) == (layer, tensor)]
743
+ if not writes:
744
+ return {}
745
+ shape = tuple(run.read_cache(layer, tensor).shape)
746
+ chosen = _selected_mask(shape, selection)
747
+ chosen = torch.ones(shape, dtype=torch.bool) if chosen is None else chosen
748
+ touched = torch.zeros(shape, dtype=torch.bool)
749
+ copied = torch.zeros(shape, dtype=torch.bool)
750
+ ops = []
751
+ for write in writes:
752
+ cell = write["cell"]
753
+ rows = [r for r in cell["rows"] if r < shape[2]]
754
+ if not rows:
755
+ continue
756
+ edit = CellEdit(layer, tensor, tuple(rows), 0.0, "add", kv=cell["kv"], d=cell["d"])
757
+ cover = edit.mask(shape)
758
+ if not bool((cover & chosen).any()):
759
+ continue
760
+ ops.append(write["op"])
761
+ touched |= cover
762
+ exact = write["op"] == "replace" or (write["op"] == "mix" and write.get("dose") == 1.0)
763
+ copied = (copied | cover) if exact else (copied & ~cover)
764
+ if not bool((touched & chosen).any()):
765
+ return {}
766
+ supplied = bool((copied | ~chosen).all())
767
+ out: dict[str, Any] = {"authority": "supplied" if supplied else "derived-exact",
768
+ "edited": True, "kind": "edit", "by": f"cache.L{layer}.{tensor}",
769
+ "ops": ops}
770
+ written, total = int((touched & chosen).sum()), int(chosen.sum())
771
+ if written < total:
772
+ out["mixed"] = {"written": written, "untouched": total - written}
773
+ return out
774
+
775
+
776
+ # --------------------------------------------------------------------------- table
777
+
778
+ HITS_SHOWN = 32
779
+
780
+
781
+ @dataclass
782
+ class Breakpoint:
783
+ id: int
784
+ pattern: str
785
+ parsed: Any
786
+ condition: Condition | None = None
787
+ temporary: bool = False
788
+ enabled: bool = True
789
+ hits: int = 0
790
+ kind: str = "break"
791
+ ignore: int = 0
792
+
793
+ def describe(self) -> dict[str, Any]:
794
+ return {
795
+ "id": self.id,
796
+ "kind": "tbreak" if self.temporary else "break",
797
+ "pattern": self.pattern,
798
+ "condition": None if self.condition is None else self.condition.text,
799
+ "enabled": self.enabled,
800
+ "hits": self.hits,
801
+ "ignore": self.ignore,
802
+ }
803
+
804
+
805
+ @dataclass
806
+ class Watch:
807
+ id: int
808
+ pattern: str
809
+ parsed: Any
810
+ predicate: Condition | None = None
811
+ mode: str = "change"
812
+ enabled: bool = True
813
+ hits: int = 0
814
+ kind: str = "watch"
815
+ state: dict[str, Any] = field(default_factory=dict)
816
+ ignore: int = 0
817
+
818
+ def describe(self) -> dict[str, Any]:
819
+ return {
820
+ "id": self.id,
821
+ "kind": "watch",
822
+ "pattern": self.pattern,
823
+ "predicate": None if self.predicate is None else self.predicate.text,
824
+ "mode": self.mode,
825
+ "enabled": self.enabled,
826
+ "hits": self.hits,
827
+ "ignore": self.ignore,
828
+ }
829
+
830
+
831
+ def validate_item(parsed: addresses.Pattern, conditions: Sequence[Condition | None],
832
+ program: Any, adapter: Any) -> None:
833
+ """Creation-time checks where the shape is knowable: a concrete layer inside the model,
834
+ the pattern's selector and every ``v["..."]`` selector of the conditions inside the axis
835
+ sizes of the stop's port. Never allocates (``plan`` only reads sizes)."""
836
+ layers = getattr(adapter, "layers", None)
837
+ if layers is not None and isinstance(parsed.layer, int) and parsed.layer >= layers:
838
+ raise SelectionRange(
839
+ f"no layer {parsed.layer} in a {layers}-layer model; valid layers are 0..{layers - 1}")
840
+ port = parsed.port
841
+ if parsed.kind == "cell":
842
+ axes = CELL_AXES
843
+ elif port in GLOBAL_AXES:
844
+ axes = GLOBAL_AXES[port]
845
+ elif port in getattr(program, "names", ()):
846
+ axes = program.spec(port).axes
847
+ else:
848
+ return
849
+ sizes = axis_sizes(adapter, axes)
850
+ head_dim = getattr(adapter, "head_dim", None)
851
+ row = None
852
+ plan(axes, sizes, parsed.selector, head_dim=head_dim, row=row, tokenizer=_NoTokens())
853
+ for condition in conditions:
854
+ if condition is None:
855
+ continue
856
+ for text in condition.selector_texts():
857
+ plan(axes, sizes, parse_selector(text), head_dim=head_dim, row=row,
858
+ tokenizer=_NoTokens())
859
+
860
+
861
+ class _NoTokens:
862
+ """Creation-time stand-in tokenizer: token text selectors are checked at evaluation."""
863
+
864
+ def encode(self, text: str, add_special_tokens: bool = False) -> list[int]:
865
+ return [0]
866
+
867
+
868
+ class Table:
869
+ """Breakpoints and watches sharing one id space (``delete`` removes either)."""
870
+
871
+ def __init__(self) -> None:
872
+ self.items: dict[int, Breakpoint | Watch] = {}
873
+ self._next = 1
874
+ self.last_stop: dict[str, Any] | None = None
875
+
876
+ def _id(self) -> int:
877
+ number, self._next = self._next, self._next + 1
878
+ return number
879
+
880
+ def add_break(
881
+ self, pattern: str, program: Any, *, condition: str | None = None,
882
+ temporary: bool = False, adapter: Any = None, compiled: Condition | None = None,
883
+ ) -> Breakpoint:
884
+ """``compiled``: a prebuilt ``Condition`` (e.g.
885
+ ``analysis.features.watch.FeatureCondition``) instead of ``condition`` text."""
886
+ parsed = parse_pattern(pattern, program)
887
+ if compiled is None:
888
+ compiled = None if condition is None else Condition(condition)
889
+ validate_item(parsed, [compiled], program, adapter)
890
+ item = Breakpoint(self._id(), addresses.format_pattern(parsed), parsed, compiled,
891
+ temporary)
892
+ self.items[item.id] = item
893
+ return item
894
+
895
+ def add_watch(
896
+ self, pattern: str, program: Any, *, predicate: str | None = None, mode: str = "change",
897
+ adapter: Any = None, compiled: Condition | None = None,
898
+ ) -> Watch:
899
+ """``compiled``: a prebuilt ``Condition`` (e.g.
900
+ ``analysis.features.watch.FeatureCondition``) instead of ``predicate`` text."""
901
+ if mode not in WATCH_MODES:
902
+ raise ValueError(f"watch mode is one of {', '.join(WATCH_MODES)}")
903
+ if mode != "change" and predicate is None and compiled is None:
904
+ raise ValueError(f"a {mode} watch needs a predicate")
905
+ parsed = parse_pattern(pattern, program)
906
+ if compiled is None:
907
+ compiled = None if predicate is None else Condition(predicate)
908
+ validate_item(parsed, [compiled], program, adapter)
909
+ item = Watch(self._id(), addresses.format_pattern(parsed), parsed, compiled, mode)
910
+ self.items[item.id] = item
911
+ return item
912
+
913
+ def _existing(self, ids: list[int]) -> list[Breakpoint | Watch]:
914
+ missing = [i for i in ids if i not in self.items]
915
+ if missing:
916
+ raise ValueError(f"no breakpoint or watch {missing[0]}")
917
+ return [self.items[i] for i in ids]
918
+
919
+ def delete(self, ids: list[int] | None = None) -> list[int]:
920
+ if ids is None:
921
+ gone = sorted(self.items)
922
+ self.items.clear()
923
+ return gone
924
+ self._existing(ids)
925
+ for i in ids:
926
+ self.items.pop(i, None)
927
+ return sorted(set(ids))
928
+
929
+ def set_enabled(self, ids: list[int] | None, enabled: bool) -> list[int]:
930
+ found = list(self.items.values()) if ids is None else self._existing(ids)
931
+ for item in found:
932
+ item.enabled = enabled
933
+ return sorted({item.id for item in found})
934
+
935
+ def set_condition(self, number: int, text: str | None, program: Any,
936
+ adapter: Any = None) -> Breakpoint | Watch:
937
+ """``condition N EXPR``; empty ``EXPR`` removes it (a watch's predicate)."""
938
+ (item,) = self._existing([number])
939
+ compiled = None if not text or not text.strip() else Condition(text)
940
+ if isinstance(item, Watch) and compiled is None and item.mode != "change":
941
+ raise ValueError(f"a {item.mode} watch needs a predicate")
942
+ validate_item(item.parsed, [compiled], program, adapter)
943
+ if isinstance(item, Watch):
944
+ item.predicate = compiled
945
+ else:
946
+ item.condition = compiled
947
+ return item
948
+
949
+ def set_ignore(self, number: int, count: int) -> Breakpoint | Watch:
950
+ (item,) = self._existing([number])
951
+ if type(count) is not int or count < 0:
952
+ raise ValueError("an ignore count is a nonnegative integer")
953
+ item.ignore = count
954
+ return item
955
+
956
+ def armed(self) -> list[Breakpoint | Watch]:
957
+ return [item for _, item in sorted(self.items.items()) if item.enabled]
958
+
959
+ def listed(self) -> list[Breakpoint | Watch]:
960
+ """Every breakpoint and watch, enabled or not, by id."""
961
+ return [item for _, item in sorted(self.items.items())]
962
+
963
+ def reset_watches(self) -> None:
964
+ for item in self.items.values():
965
+ if isinstance(item, Watch):
966
+ item.state = {}
967
+ self.last_stop = None
968
+
969
+
970
+ # --------------------------------------------------------------------------- continue
971
+
972
+
973
+ @dataclass
974
+ class _Probe:
975
+ """One evaluation at one stop."""
976
+
977
+ run: Any
978
+ row: int
979
+ label: str
980
+ tokenizer: Any
981
+ _value: torch.Tensor | None = None
982
+ _cells: dict | None = None
983
+
984
+ @property
985
+ def address(self) -> str:
986
+ return f"t{self.row}.{self.label}"
987
+
988
+ def value(self, pattern: Any = None) -> torch.Tensor:
989
+ if pattern is not None and pattern.kind == "cell":
990
+ # one read per (layer, tensor): watches on cache.L0.k and cache.L0.v at the same
991
+ # stop must not share a value
992
+ if self._cells is None:
993
+ self._cells = {}
994
+ key = (pattern.layer, pattern.port)
995
+ if key not in self._cells:
996
+ self._cells[key] = self.run.read_cache(pattern.layer, pattern.port)
997
+ return self._cells[key]
998
+ if self._value is None:
999
+ self._value = self.run.read(self.address)
1000
+ return self._value
1001
+
1002
+ def prov(self, pattern: Any, selection: Selection) -> dict[str, Any]:
1003
+ if pattern.kind == "cell":
1004
+ return cell_provenance(self.run, pattern.layer, selection, pattern.port)
1005
+ return provenance(self.run, self.address, selection)
1006
+
1007
+ def env(self, pattern: Any) -> ConditionEnv:
1008
+ if pattern.kind == "cell":
1009
+ full = self.value(pattern)
1010
+ selection = select(full, CELL_AXES, pattern.selector,
1011
+ head_dim=self.run.adapter.head_dim, row=None,
1012
+ tokenizer=self.tokenizer)
1013
+ return ConditionEnv(full, selection, CELL_AXES, self.run.adapter.head_dim, None,
1014
+ self.tokenizer, self.run, self.address)
1015
+ axes = stop_axes(self.run.program, self.label)
1016
+ full = self.value()
1017
+ row = None if self.label in ("start",) else self.row
1018
+ if "row" not in axes:
1019
+ row = None
1020
+ selection = select(full, axes, pattern.selector, head_dim=self.run.adapter.head_dim,
1021
+ row=row, tokenizer=self.tokenizer)
1022
+ return ConditionEnv(full, selection, axes, self.run.adapter.head_dim, row, self.tokenizer,
1023
+ self.run, self.address)
1024
+
1025
+
1026
+ def _evaluate(item: Breakpoint | Watch, probe: _Probe, state: dict[str, Any]) -> dict | None:
1027
+ """Whether ``item`` fires at this stop; watches update ``state`` (their memory)."""
1028
+ env = probe.env(item.parsed)
1029
+ sites = None if isinstance(item, Breakpoint) else getattr(item.predicate, "sites", None)
1030
+ if sites is not None:
1031
+ # a multi-site watch keeps one memory per layer (= one single-site watch per layer)
1032
+ state = state.setdefault("sites", {}).setdefault(int(probe.label[1:].split(".")[0]), {})
1033
+ if isinstance(item, Breakpoint):
1034
+ if item.condition is not None and not item.condition.evaluate(env):
1035
+ return None
1036
+ kind = "advance" if item.kind == "advance" else item.describe()["kind"]
1037
+ return {"id": item.id, "kind": kind, "pattern": item.pattern}
1038
+ holds = True if item.predicate is None else item.predicate.evaluate(env)
1039
+ digest = tensor_digest(env.selection.value.contiguous())
1040
+ stats = reduce(env.selection)
1041
+ previous = state.get("digest")
1042
+ was = state.get("active", False)
1043
+ old = state.get("stats")
1044
+ prov = probe.prov(item.parsed, env.selection)
1045
+ old_prov = state.get("prov")
1046
+ state.update(digest=digest, active=holds, stats=stats, where=probe.address, prov=prov)
1047
+ if item.mode == "change":
1048
+ fires = previous is not None and digest != previous and holds
1049
+ elif item.mode == "level":
1050
+ fires = holds
1051
+ else:
1052
+ fires = holds and not was
1053
+ if not fires:
1054
+ return None
1055
+ hit = {"id": item.id, "kind": "watch", "pattern": item.pattern, "mode": item.mode,
1056
+ "new": stats, "new_provenance": prov}
1057
+ if sites is not None:
1058
+ hit["site"] = probe.address
1059
+ hit["layer"] = int(probe.label[1:].split(".")[0])
1060
+ if old is not None:
1061
+ hit["old"] = old
1062
+ hit["old_provenance"] = old_prov
1063
+ return hit
1064
+
1065
+
1066
+ def prime(run: Any, item: Watch, *, tokenizer: Any = None) -> str | None:
1067
+ """Record a new watch's baseline as gdb does: the value at the time the watch is set.
1068
+
1069
+ That is the cursor's own stop when it matches the watch, else the latest stop of the cursor's
1070
+ row at or before the cursor that does (an address already computed on this row), so the
1071
+ first change after the cursor is not lost to a baseline taken from a later row. Returns
1072
+ the address the baseline was taken at (None when none was)."""
1073
+ row, index = run.parse(run.where)
1074
+ stops = run.stops()
1075
+ for earlier in range(index, -1, -1):
1076
+ label = stops[earlier]
1077
+ if not _stops(item, stop_occurrence(row, label)):
1078
+ continue
1079
+ if earlier != index:
1080
+ try:
1081
+ run.read(f"t{row}.{label}") # still held? (not for a stored cut's earlier stops)
1082
+ except Exception: # noqa: BLE001 - not readable: no baseline, as before
1083
+ return None
1084
+ _evaluate(item, _Probe(run, row, label, tokenizer), item.state)
1085
+ return f"t{row}.{label}"
1086
+ return None
1087
+
1088
+
1089
+ def _stops(item: Any, occurrence: addresses.Occurrence) -> bool:
1090
+ """Whether ``item`` stops at ``occurrence``: its pattern matches and, for a multi-site
1091
+ condition, the occurrence is one of its sites' layers."""
1092
+ if not stops_at(item.parsed, occurrence):
1093
+ return False
1094
+ condition = getattr(item, "predicate", None) if isinstance(item, Watch) else \
1095
+ getattr(item, "condition", None)
1096
+ sites = getattr(condition, "sites", None)
1097
+ return sites is None or occurrence.layer in sites
1098
+
1099
+
1100
+ def _matching(items: list, occurrence: addresses.Occurrence) -> list:
1101
+ return [item for item in items if _stops(item, occurrence)]
1102
+
1103
+
1104
+ def _at_stop(items: list, matched: list, probe: _Probe, states: dict | None,
1105
+ table: Table | None) -> tuple[list[dict], dict | None]:
1106
+ """Evaluate the matched items at one stop. Returns ``(fired hits, error)``: ``error`` is
1107
+ ``{id, pattern, message}`` for the first item whose condition could not be evaluated (the
1108
+ motion stops there); ignore counts consume hits (gdb: counted, not reported)."""
1109
+ hits: list[dict] = []
1110
+ error = None
1111
+ for item in matched:
1112
+ if isinstance(item, Watch):
1113
+ state = item.state if states is None else states.setdefault(item.id, {})
1114
+ else:
1115
+ state = {}
1116
+ try:
1117
+ hit = _evaluate(item, probe, state)
1118
+ except Exception as caught: # noqa: BLE001 - any evaluation failure stops the motion
1119
+ if error is None:
1120
+ error = {"id": item.id, "pattern": item.pattern,
1121
+ "message": f"{type(caught).__name__}: {caught}"
1122
+ if not isinstance(caught, ValueError) else str(caught)}
1123
+ continue
1124
+ if hit is None:
1125
+ continue
1126
+ live = None if table is None else table.items.get(item.id)
1127
+ if live is not None:
1128
+ live.hits += 1
1129
+ if live.ignore > 0:
1130
+ live.ignore -= 1
1131
+ continue
1132
+ if isinstance(live, Breakpoint) and live.temporary:
1133
+ del table.items[live.id]
1134
+ hits.append(hit)
1135
+ return hits, error
1136
+
1137
+
1138
+ def _stopped(table: Table | None, where: str, hits: list[dict]) -> None:
1139
+ if table is not None:
1140
+ table.last_stop = {"where": where, "ids": [h["id"] for h in hits if h["id"] > 0]}
1141
+
1142
+
1143
+ def stop_reason(kinds: set[str]) -> str:
1144
+ """The stop ``reason`` for the set of hit kinds at one stop: ``watch`` (only watches),
1145
+ ``advance`` (only advance items), ``watch+breakpoint`` (a watch and a break/tbreak/... hit at
1146
+ the same stop), else ``breakpoint``. ``hits[]`` still lists every item with its ``kind``."""
1147
+ if kinds == {"watch"}:
1148
+ return "watch"
1149
+ if kinds == {"advance"}:
1150
+ return "advance"
1151
+ if "watch" in kinds and kinds - {"watch", "advance"}:
1152
+ return "watch+breakpoint"
1153
+ return "breakpoint"
1154
+
1155
+
1156
+ def _reason(hits: list[dict]) -> str:
1157
+ return stop_reason({hit["kind"] for hit in hits})
1158
+
1159
+
1160
+ def _capacity(error: ValueError) -> bool:
1161
+ return "capacity" in str(error)
1162
+
1163
+
1164
+ def _end_of_context(run: Any, stops: tuple[str, ...], last_row: int) -> dict[str, Any]:
1165
+ """A normal stop at the last reachable stop: ``t<last>.logits`` (one row earlier when the
1166
+ engine cannot embed the final position), or where the cursor already is."""
1167
+ here = run.parse(run.where)
1168
+ at = stops.index("logits")
1169
+ for row in (last_row, last_row - 1):
1170
+ if row < 0 or (row, at) <= here:
1171
+ break
1172
+ try:
1173
+ run.until(f"t{row}.logits")
1174
+ break
1175
+ except ValueError as error:
1176
+ if not _capacity(error):
1177
+ raise
1178
+ return {"reason": "end-of-context", "where": run.where, "hits": []}
1179
+
1180
+
1181
+ def run_forward(
1182
+ run: Any,
1183
+ table: Table | None,
1184
+ *,
1185
+ budget: int = 8,
1186
+ extra: list | None = None,
1187
+ tokenizer: Any = None,
1188
+ max_positions: int | None = None,
1189
+ ) -> dict[str, Any]:
1190
+ """Run to the next hit of an armed breakpoint/watch (or ``extra`` items).
1191
+
1192
+ ``budget`` is the number of token rows the motion may ENTER (minimum 1): it stops at the
1193
+ ``start`` of row ``cursor row + budget`` with reason ``budget``. Per-item ignore counts
1194
+ pass hits (gdb ``ignore N COUNT``). Returns ``{reason, where, hits[, error]}`` where
1195
+ ``reason`` is ``breakpoint``, ``watch``, ``watch+breakpoint`` (both at one stop), ``advance``, ``budget``, ``end-of-context`` (the
1196
+ model's context limit: a normal stop) or ``error`` (a condition or watch could not be
1197
+ evaluated at ``where``: the motion stops there, ``error`` has the id and message).
1198
+ """
1199
+ if type(budget) is not int or budget < 0:
1200
+ raise ValueError("budget must be a nonnegative integer")
1201
+ budget = max(1, budget)
1202
+ items = (table.armed() if table is not None else []) + list(extra or ())
1203
+ stops = run.stops()
1204
+ start_row, index = run.parse(run.where)
1205
+ row = start_row
1206
+ last_row = None if max_positions is None else max_positions - 1
1207
+ while True:
1208
+ index += 1
1209
+ if index == len(stops):
1210
+ row, index = row + 1, 0
1211
+ if last_row is not None and row > last_row:
1212
+ return _end_of_context(run, stops, last_row)
1213
+ if index == 0 and row - start_row >= budget:
1214
+ try:
1215
+ run.until(f"t{row}.start")
1216
+ except ValueError as error:
1217
+ if not _capacity(error) or last_row is None:
1218
+ raise
1219
+ return _end_of_context(run, stops, last_row)
1220
+ return {"reason": "budget", "where": run.where, "hits": []}
1221
+ occurrence = stop_occurrence(row, stops[index])
1222
+ matched = _matching(items, occurrence)
1223
+ if not matched:
1224
+ continue
1225
+ try:
1226
+ run.until(f"t{row}.{stops[index]}")
1227
+ except ValueError as error:
1228
+ if not _capacity(error) or last_row is None:
1229
+ raise
1230
+ return _end_of_context(run, stops, last_row)
1231
+ probe = _Probe(run, row, stops[index], tokenizer)
1232
+ hits, error = _at_stop(items, matched, probe, None, table)
1233
+ if error is not None:
1234
+ _stopped(table, run.where, hits)
1235
+ return {"reason": "error", "where": run.where, "hits": hits, "error": error}
1236
+ if not hits:
1237
+ continue
1238
+ _stopped(table, run.where, hits)
1239
+ return {"reason": _reason(hits), "where": run.where, "hits": hits}
1240
+
1241
+
1242
+ _BOUNDARY_UNITS = ("start", "emb", "fn", "logits", "sample")
1243
+
1244
+
1245
+ def _boundary(label: str) -> bool:
1246
+ """Stops that are committed-cut marks: the globals and every layer's ``h_out``."""
1247
+ return label in _BOUNDARY_UNITS or label.endswith(".h_out")
1248
+
1249
+
1250
+ def jump_back(run: Any, target: tuple[int, int]) -> None:
1251
+ """Move the cursor back to ``target`` with boundary restores (no layer is executed) and
1252
+ at most one forward re-probe inside the layer that holds ``target``."""
1253
+ stops = run.stops()
1254
+ row, index = target
1255
+ while not _boundary(stops[index]): # the nearest committed boundary at or before it
1256
+ index -= 1
1257
+ boundary = (row, index)
1258
+ while True:
1259
+ here = run.parse(run.where)
1260
+ if here <= boundary:
1261
+ break
1262
+ previous_start = (here[0], 0) if here[1] > 0 else (here[0] - 1, 0)
1263
+ run.reverse_step("token" if previous_start >= boundary else "layer", 1)
1264
+ if boundary < target:
1265
+ run.until(f"t{target[0]}.{stops[target[1]]}")
1266
+
1267
+
1268
+ def run_reverse(run: Any, table: Table, *, tokenizer: Any = None) -> dict[str, Any]:
1269
+ """Walk back to the previous hit and jump there with one cursor move.
1270
+
1271
+ The hit is located by scanning the program's stops backwards, reading values only where a
1272
+ condition or watch needs them. Watches have their own memory on this backward walk,
1273
+ seeded with the value at the cursor when the cursor itself matches the watch, so a change
1274
+ between the previous matching stop and the cursor is found; their forward memory is left
1275
+ untouched.
1276
+ """
1277
+ stops = run.stops()
1278
+ here = run.parse(run.where)
1279
+ row, index = here
1280
+ root = run.parse(run.root) # the first stepped row's start (prefill=K), or a stored cut
1281
+ # Cache cells are read at the current boundary only: a past boundary's cells are gone, so
1282
+ # cell breakpoints/watches are not evaluated on the backward walk.
1283
+ items = [i for i in table.armed() if i.parsed.kind != "cell"]
1284
+ states: dict[int, dict[str, Any]] = {}
1285
+ seed = _matching([i for i in items if isinstance(i, Watch)],
1286
+ stop_occurrence(row, stops[index]))
1287
+ if seed:
1288
+ _at_stop(items, seed, _Probe(run, row, stops[index], tokenizer), states, None)
1289
+ while (row, index) > root:
1290
+ index -= 1
1291
+ if index < 0:
1292
+ row, index = row - 1, len(stops) - 1
1293
+ matched = _matching(items, stop_occurrence(row, stops[index]))
1294
+ if not matched:
1295
+ continue
1296
+ probe = _Probe(run, row, stops[index], tokenizer)
1297
+ hits, error = _at_stop(items, matched, probe, states, table)
1298
+ if hits or error is not None:
1299
+ jump_back(run, (row, index))
1300
+ if error is not None:
1301
+ _stopped(table, run.where, hits)
1302
+ return {"reason": "error", "where": run.where, "hits": hits, "error": error}
1303
+ _stopped(table, run.where, hits)
1304
+ return {"reason": _reason(hits), "where": run.where, "hits": hits}
1305
+ if (row, index) < here:
1306
+ jump_back(run, root)
1307
+ return {"reason": "start-of-run", "where": run.where, "hits": []}
1308
+
1309
+
1310
+ # --------------------------------------------------------------------------- trace watches
1311
+
1312
+ TRACE_SCALARS = ("margin", "step", "argmax_letter", "X", "R")
1313
+ TRACE_TABLES = ("share", "to_consumer", "mass", "ablated")
1314
+ TRACE_LETTERS = ("A", "B", "C", "D")
1315
+
1316
+
1317
+ class TraceCondition(Condition):
1318
+ """A watch predicate over one record of a sealed ``Trace`` (a logits-stop readout of a
1319
+ probe step), not over a port value. Names: ``margin step argmax_letter X R`` (``X`` the
1320
+ hinted letter, ``R`` the consumer's rival letter), the letters ``A B C D``, and string-keyed
1321
+ tables ``share["hint"] to_consumer["chain_so_far"] mass[...] ablated[...]``. Same literal,
1322
+ arithmetic, comparison and boolean whitelist as ``Condition``; letters compare with ``==``.
1323
+
1324
+ argmax_letter == X and ablated["hint"] < 0
1325
+ share["hint"] > share["chain_so_far"]
1326
+ """
1327
+
1328
+ def _check(self, node: ast.AST, *, value_ok: bool = False) -> None:
1329
+ if isinstance(node, ast.Name):
1330
+ self._nodes += 1
1331
+ if self._nodes > _MAX_NODES:
1332
+ raise ConditionError("condition is too complex")
1333
+ if node.id in TRACE_SCALARS or node.id in TRACE_LETTERS:
1334
+ return
1335
+ raise ConditionError(
1336
+ f"unknown trace name {node.id!r}; use {', '.join(TRACE_SCALARS)}, a letter, "
1337
+ f"or {', '.join(t + '[...]' for t in TRACE_TABLES)}")
1338
+ if isinstance(node, ast.Subscript):
1339
+ self._nodes += 1
1340
+ if not (isinstance(node.value, ast.Name) and node.value.id in TRACE_TABLES):
1341
+ raise ConditionError(f"only {', '.join(TRACE_TABLES)} may be subscripted")
1342
+ key = node.slice
1343
+ if not (isinstance(key, ast.Constant) and isinstance(key.value, str)):
1344
+ raise ConditionError(f'{node.value.id}[...] takes one quoted binding name')
1345
+ return
1346
+ if isinstance(node, ast.Call):
1347
+ raise ConditionError("no calls in a trace condition")
1348
+ super()._check(node, value_ok=value_ok)
1349
+
1350
+ def keys(self) -> list[tuple[str, str]]:
1351
+ """The ``(table, binding)`` pairs the predicate reads."""
1352
+ return [(n.value.id, n.slice.value) for n in ast.walk(self.tree)
1353
+ if isinstance(n, ast.Subscript)]
1354
+
1355
+ def _eval(self, node: ast.AST, env: Any) -> Any:
1356
+ if isinstance(node, ast.Name):
1357
+ return env.name(node.id)
1358
+ if isinstance(node, ast.Subscript):
1359
+ return env.table(node.value.id, node.slice.value)
1360
+ return super()._eval(node, env)
1361
+
1362
+
1363
+ @dataclass
1364
+ class TraceEnv:
1365
+ """One trace record as a condition sees it. ``record`` holds ``margin``, ``step``,
1366
+ ``argmax_letter`` and the tables (``share`` etc.: ``{binding: float}``); ``X``/``R`` are
1367
+ the item's fixed consumer letters."""
1368
+
1369
+ record: dict[str, Any]
1370
+ X: str
1371
+ R: str
1372
+
1373
+ def name(self, name: str) -> Any:
1374
+ if name in TRACE_LETTERS:
1375
+ return name
1376
+ if name == "X":
1377
+ return self.X
1378
+ if name == "R":
1379
+ return self.R
1380
+ if name not in self.record:
1381
+ raise ConditionError(f"the trace record has no {name!r}")
1382
+ return self.record[name]
1383
+
1384
+ def table(self, table: str, key: str) -> float:
1385
+ values = self.record.get(table)
1386
+ if values is None or key not in values:
1387
+ raise ConditionError(f"the trace record has no {table}[{key!r}]")
1388
+ value = values[key]
1389
+ if value is None or (isinstance(value, float) and not math.isfinite(value)):
1390
+ raise ConditionError(f"{table}[{key!r}] is undefined at step {self.record.get('step')}")
1391
+ return float(value)
1392
+
1393
+
1394
+ def replay(predicate: TraceCondition | str, steps: Any, *, X: str | None = None,
1395
+ R: str | None = None, mode: str = "edge", store: Any = None,
1396
+ project: Any = None, session_id: str | None = None) -> dict[str, Any]:
1397
+ """Evaluate a trace watch over a sealed ``Trace`` (record and replay: nothing runs).
1398
+
1399
+ ``steps``: the step records, a ``rows.Trace``, or a sealed ``trace`` record (a dict of kind
1400
+ ``trace``; its blob is read from ``store`` and checked against its sha256), or a record id
1401
+ indexed in ``project`` under ``session_id``. ``X``/``R`` default to the trace's ``meta``.
1402
+
1403
+ ``steps`` in probe order. ``level`` fires where the predicate holds; ``edge`` where it holds
1404
+ and did not at the previous step (before the first step counts as not holding); ``change``
1405
+ where its truth value differs from the previous step's (the first step is the baseline).
1406
+ A step whose predicate is undefined (a ``ConditionError``, e.g. a share at margin 0) counts
1407
+ as not holding and is listed in ``undefined``. Returns ``fired_at`` (step of the first
1408
+ hit, or None), ``fired_index``, ``hits`` (steps that fired), ``holds`` (per step),
1409
+ ``crossings`` (truth changes from step to step), ``fired_fraction`` (fraction of steps
1410
+ holding) and ``n``."""
1411
+ if mode not in WATCH_MODES:
1412
+ raise ConditionError(f"mode must be one of {', '.join(WATCH_MODES)}")
1413
+ condition = predicate if isinstance(predicate, TraceCondition) else TraceCondition(predicate)
1414
+ meta: dict[str, Any] = {}
1415
+ if isinstance(steps, str):
1416
+ if project is None or session_id is None:
1417
+ raise ConditionError("replay of a record id needs project= and session_id=")
1418
+ from mdb.core import index
1419
+
1420
+ steps = index.get_record(project, session_id, steps)
1421
+ store = project.store if store is None else store
1422
+ if isinstance(steps, dict) and steps.get("kind") == "trace":
1423
+ from mdb.core.bounded import load_json # the sealed trace's blob, sha256-checked
1424
+
1425
+ data = load_json(steps["body"]["payload"], store=getattr(store, "store", store))
1426
+ meta, steps = dict(data["meta"]), data["records"]
1427
+ if hasattr(steps, "records") and hasattr(steps, "meta"):
1428
+ meta, steps = dict(steps.meta), steps.records
1429
+ X = X if X is not None else meta.get("X")
1430
+ R = R if R is not None else meta.get("R")
1431
+ if X is None or R is None:
1432
+ raise ConditionError("replay needs X and R (the trace's meta has none)")
1433
+ holds: list[bool] = []
1434
+ undefined: list[Any] = []
1435
+ for record in steps:
1436
+ try:
1437
+ holds.append(condition.evaluate(TraceEnv(record, X, R)))
1438
+ except ConditionError:
1439
+ holds.append(False)
1440
+ undefined.append(record.get("step"))
1441
+ hits = []
1442
+ for index, value in enumerate(holds):
1443
+ was = holds[index - 1] if index else (None if mode == "change" else False)
1444
+ if mode == "level":
1445
+ fires = value
1446
+ elif mode == "edge":
1447
+ fires = value and not was
1448
+ else:
1449
+ fires = was is not None and value != was
1450
+ if fires:
1451
+ hits.append(index)
1452
+ crossings = sum(1 for a, b in zip(holds, holds[1:]) if a != b)
1453
+ first = hits[0] if hits else None
1454
+ return {
1455
+ "predicate": condition.text,
1456
+ "mode": mode,
1457
+ "n": len(holds),
1458
+ "holds": holds,
1459
+ "hits": [steps[i].get("step", i) for i in hits],
1460
+ "fired_index": first,
1461
+ "fired_at": None if first is None else steps[first].get("step", first),
1462
+ "crossings": crossings,
1463
+ "fired_fraction": (sum(holds) / len(holds)) if holds else None,
1464
+ "undefined": undefined,
1465
+ }