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
mdb/ops/sets.py ADDED
@@ -0,0 +1,988 @@
1
+ """Prompt sets and ``each``: one op line run on every prompt of a set, plus a summary.
2
+
3
+ The engine stays batch 1: ``each`` makes one run per prompt (``start`` then ``until AT``
4
+ through the registry, exactly what a user would type), runs the op line on it through the
5
+ same ``dispatch`` a single-prompt call uses, and releases the run (``keep`` holds them as
6
+ named runs ``SET-ITEM``). Runs are made one after the other, not held together.
7
+
8
+ A prompt set is a list of items, from a JSONL file (``promptset load NAME FILE``, the REPL's
9
+ ``set load NAME FILE``) or given inline (``define``):
10
+
11
+ {"name": "paris", "tokens": [1, 5, 9, 3], "roles": {"subject": 1},
12
+ "vars": {"answer": 4, "foil": 9}, "pair": "rome"}
13
+
14
+ ``prompt`` (text, needs a tokenizer) or ``tokens``; ``roles`` name rows (``last`` is always the
15
+ last row); ``vars`` name tokens (an id, or a text that is one token); ``pair`` names another
16
+ item of the set. An op line addresses them as a template, bound per item before dispatch, so
17
+ every per-item result holds ordinary canonical addresses:
18
+
19
+ * ``t@ROLE`` -> ``t<row>`` (``t@subject.L1.A[h1]``, ``t@last.logits``); ``=@ROLE`` -> ``=<row>``
20
+ (``[row=@subject]``, ``rows=@subject``); an argument that is exactly ``@ROLE`` -> ``<row>``;
21
+ * ``$NAME`` -> the token id (``M[$answer,$foil]``);
22
+ * ``@pair:ADDR`` -> ``pair-SET-PAIR:ADDR``: the value at ADDR (roles bound to the paired item)
23
+ of the paired item's run, a clean run of that prompt at the same stop (``AT``), started once
24
+ per ``each`` and released with the item runs. It is the cross-run value of ``set``/``whatif``
25
+ /``compare`` (``ORIGIN:ADDR``), so it reaches what those reach: a port of the run's last row
26
+ or a cache cell. An address with no row (``L20.A[h5]``) means the paired item's last row,
27
+ ``pair-SET-PAIR:t<its last>.L20.A[h5]``, whatever length the two prompts are; the item row's
28
+ ``donor`` lists the donor addresses used.
29
+
30
+ ``prefill=K`` or ``prefill=@ROLE`` starts each item's run, and its pair's clean run,
31
+ under that split, bound per item (``@ROLE``: that item's own role row), so the rows from it on
32
+ are stepped with ports (``sweep``, cross-row ``set``/``whatif`` at earlier rows); the item's row
33
+ in the summary holds the bound value (``prefill``).
34
+
35
+ An item whose template does not bind (an undefined role or variable, a role past its prompt,
36
+ no pair, a split past its prompt) or whose op is refused is a per-item refusal with its
37
+ reason; the other items run.
38
+
39
+ Output: the ``each`` op returns ONE summary record (bounded: per-item rows hold key numbers, the
40
+ item result's digest and a pointer to it, never the result itself); the per-item results are the
41
+ ops' ordinary results, kept in memory under the summary id (``promptset result ID ITEM``). With
42
+ a writable project attached each result is also a sha256-checked JSON blob in the project store
43
+ (``core.bounded.put_json``; the row's ``blob`` is its pointer) and the summary is stored as a
44
+ ``prompt-set`` record, so ``promptset result RECORD ITEM`` (RECORD = the summary's ``stored``
45
+ id) reads the result back in a new process, verifying the blob; without a project the row says
46
+ the result is held in memory only.
47
+ Statistics: ``mdb.analysis.numerics.summary``.
48
+
49
+ State: the caller's context (run, cursor, focus, tables, checkpoints) and the debugger's live
50
+ run, run table, circuit carry and declared symbols are what they were before; each item runs
51
+ in a fresh context (no breakpoints, displays, checkpoints or focus of the caller's).
52
+ """
53
+
54
+ from __future__ import annotations
55
+
56
+ import json
57
+ import re
58
+ import weakref
59
+ from dataclasses import dataclass, field
60
+ from pathlib import Path
61
+ from typing import Any
62
+
63
+ from mdb.core.pointers import RecordError, check_bounded, seal_digest
64
+
65
+ from . import lines
66
+ from .context import Context
67
+ from .errors import BadArgs, OpError, Refused
68
+ from .registry import Arg, Op, dispatch, register, registry, validate
69
+
70
+ MAX_ITEMS = 64 # summary rows kept inline (a record list holds at most 64 items); a set
71
+ # may be any size: past 64 the full rows are a blob (``items_blob``)
72
+ MAX_NUMERIC = 40 # statistics listed in the summary record (the rest are counted)
73
+ MAX_VERDICTS = 16
74
+ MAX_RESULTS = 16 # summaries (with their item results) kept in memory per debugger
75
+ DEFAULT_AT = "t@last.logits"
76
+ _FORBIDDEN = ("each", "promptset")
77
+ _ROLE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
78
+ _ITEM_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
79
+ _SET_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
80
+
81
+ _PAIR = re.compile(r"@pair:(?P<addr>\S+)")
82
+ _T_ROLE = re.compile(r"(?<![A-Za-z0-9_])t@(?P<role>[A-Za-z_]\w*)")
83
+ _EQ_ROLE = re.compile(r"=@(?P<role>[A-Za-z_]\w*)")
84
+ _BARE_ROLE = re.compile(r"@(?P<role>[A-Za-z_]\w*)")
85
+ _VAR = re.compile(r"\$(?P<var>[A-Za-z_]\w*)")
86
+
87
+ _SETS: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary() # debugger -> {name: set}
88
+ _RESULTS: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary() # debugger -> {id: entry}
89
+ _OWNED: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary() # debugger -> run names
90
+
91
+
92
+ # --------------------------------------------------------------------------- sets
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class Item:
97
+ name: str
98
+ prompt: Any # text or a list of token ids
99
+ roles: dict[str, int] = field(default_factory=dict)
100
+ vars: dict[str, Any] = field(default_factory=dict)
101
+ pair: str | None = None
102
+ core: Any = None # a checkpoint the item's run is rehydrated from
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class PromptSet:
107
+ name: str
108
+ items: tuple[Item, ...]
109
+ source: str = "inline"
110
+
111
+ def item(self, name: str) -> Item:
112
+ return next(item for item in self.items if item.name == name)
113
+
114
+
115
+ def roles_from_text(tokenizer: Any, text: str, spans: dict[str, Any], *,
116
+ ids: list[int] | None = None) -> dict[str, list[int]]:
117
+ """Token rows of named text spans (what chain-of-thought drivers each wrote as ``spans_for``):
118
+ ``spans`` maps a role to a substring (its first occurrence), ``(substring, after)`` (the first
119
+ occurrence at or after character ``after``, or after the end of the role named ``after``)
120
+ or ``(start, end)`` character offsets. A row belongs to a role when its token's character
121
+ span overlaps the role's (tokens with an empty span, e.g. special tokens, never do).
122
+ ``ids``: the item's token ids, checked against the tokenizer's encoding of ``text``.
123
+ Returns ``{role: [rows]}`` for ``roles`` of a prompt-set item."""
124
+ encoded = tokenizer(text, return_offsets_mapping=True, add_special_tokens=False)
125
+ if ids is not None and list(encoded["input_ids"]) != list(ids):
126
+ raise Refused("the tokenizer's encoding of text differs from the item's ids")
127
+ found: dict[str, tuple[int, int]] = {}
128
+ for role, spec in spans.items():
129
+ if isinstance(spec, str):
130
+ start = text.find(spec)
131
+ if start < 0:
132
+ raise Refused(f"role {role}: {spec!r} is not in the text")
133
+ found[role] = (start, start + len(spec))
134
+ continue
135
+ first, second = spec
136
+ if isinstance(first, int) and isinstance(second, int):
137
+ found[role] = (first, second)
138
+ continue
139
+ after = found[second][1] if isinstance(second, str) else int(second)
140
+ start = text.find(first, after)
141
+ if start < 0:
142
+ raise Refused(f"role {role}: {first!r} is not in the text after {after}")
143
+ found[role] = (start, start + len(first))
144
+ out: dict[str, list[int]] = {role: [] for role in spans}
145
+ for row, (a, b) in enumerate(encoded["offset_mapping"]):
146
+ if a >= b:
147
+ continue
148
+ for role, (lo, hi) in found.items():
149
+ if a < hi and b > lo:
150
+ out[role].append(row)
151
+ return out
152
+
153
+
154
+ def _item(raw: Any, where: str) -> Item:
155
+ if not isinstance(raw, dict):
156
+ raise BadArgs(f"{where}: an item is a JSON object")
157
+ known = {"name", "prompt", "tokens", "roles", "vars", "pair", "core", "from"}
158
+ extra = sorted(set(raw) - known)
159
+ if extra:
160
+ raise BadArgs(f"{where}: unknown key {extra[0]!r} (keys: {', '.join(sorted(known))})")
161
+ name = raw.get("name")
162
+ if not isinstance(name, str) or not _ITEM_NAME.fullmatch(name):
163
+ raise BadArgs(f"{where}: name must be a word ([A-Za-z_][A-Za-z0-9_]*)")
164
+ where = f"{where} ({name})"
165
+ if "core" in raw and "from" in raw:
166
+ raise BadArgs(f"{where}: give core or from (the same key), not both")
167
+ core = raw.get("core", raw.get("from"))
168
+ if core is not None and isinstance(core, str) and not core.strip():
169
+ raise BadArgs(f"{where}: core is a checkpoint path or record id")
170
+ if "prompt" in raw and "tokens" in raw:
171
+ raise BadArgs(f"{where}: give prompt (text) or tokens (ids), one of them")
172
+ if core is None and "prompt" not in raw and "tokens" not in raw:
173
+ raise BadArgs(f"{where}: give prompt (text) or tokens (ids), one of them (or core, a "
174
+ "checkpoint)")
175
+ if core is not None and "prompt" not in raw and "tokens" not in raw:
176
+ prompt: Any = None
177
+ elif "tokens" in raw:
178
+ tokens = raw["tokens"]
179
+ if (not isinstance(tokens, list) or not tokens
180
+ or any(type(t) is not int or t < 0 for t in tokens)):
181
+ raise BadArgs(f"{where}: tokens is a non-empty list of token ids")
182
+ prompt: Any = list(tokens)
183
+ else:
184
+ prompt = raw["prompt"]
185
+ if not isinstance(prompt, str) or not prompt:
186
+ raise BadArgs(f"{where}: prompt is non-empty text")
187
+ roles = raw.get("roles") or {}
188
+ if not isinstance(roles, dict):
189
+ raise BadArgs(f"{where}: roles is an object ROLE: row")
190
+ for role, row in roles.items():
191
+ if not _ROLE_NAME.fullmatch(role) or role in ("last", "pair"):
192
+ raise BadArgs(f"{where}: role {role!r} is not a word, or is reserved (last, pair)")
193
+ if type(row) is not int or row < 0:
194
+ raise BadArgs(f"{where}: role {role} must be a row number >= 0")
195
+ variables = raw.get("vars") or {}
196
+ if not isinstance(variables, dict):
197
+ raise BadArgs(f"{where}: vars is an object NAME: token id or token text")
198
+ for key, value in variables.items():
199
+ if not _ROLE_NAME.fullmatch(key):
200
+ raise BadArgs(f"{where}: variable {key!r} is not a word")
201
+ if not ((type(value) is int and value >= 0) or (isinstance(value, str) and value)):
202
+ raise BadArgs(f"{where}: variable {key} is a token id or a token text")
203
+ pair = raw.get("pair")
204
+ if pair is not None and (not isinstance(pair, str) or pair == name):
205
+ raise BadArgs(f"{where}: pair names another item of the set")
206
+ return Item(name, prompt, dict(roles), dict(variables), pair, core)
207
+
208
+
209
+ def make_set(name: str, rows: list[Any], source: str = "inline") -> PromptSet:
210
+ """A checked prompt set (``BadArgs`` names the item and the key that is wrong)."""
211
+ if not isinstance(name, str) or not _SET_NAME.fullmatch(name):
212
+ raise BadArgs(f"set name {name!r} must be a word ([A-Za-z_][A-Za-z0-9_]*)")
213
+ if not isinstance(rows, list) or not rows:
214
+ raise BadArgs(f"set {name}: no items")
215
+ items = tuple(_item(raw, f"item {i + 1}") for i, raw in enumerate(rows))
216
+ names = [item.name for item in items]
217
+ repeated = sorted({n for n in names if names.count(n) > 1})
218
+ if repeated:
219
+ raise BadArgs(f"set {name}: item name {repeated[0]!r} repeats")
220
+ for item in items:
221
+ if item.pair is not None and item.pair not in names:
222
+ raise BadArgs(f"set {name}: item {item.name} pairs with {item.pair!r}, "
223
+ "which is not in the set")
224
+ return PromptSet(name, items, source)
225
+
226
+
227
+ def read_jsonl(path: str) -> list[Any]:
228
+ """The JSON objects of a JSONL file (blank lines and ``#`` lines skipped). Errors name
229
+ the line, never its content."""
230
+ try:
231
+ text = Path(path).expanduser().read_text()
232
+ except OSError as error:
233
+ raise BadArgs(f"cannot read {path}: {error.strerror or type(error).__name__}") from None
234
+ rows = []
235
+ for number, line in enumerate(text.splitlines(), 1):
236
+ if not line.strip() or line.lstrip().startswith("#"):
237
+ continue
238
+ try:
239
+ rows.append(json.loads(line))
240
+ except json.JSONDecodeError as error:
241
+ raise BadArgs(f"{path} line {number}: not JSON ({error.msg})") from None
242
+ return rows
243
+
244
+
245
+ def _inline_rows(text: str) -> list[Any]:
246
+ """Items given inline: a JSON list of item objects, or JSONL (one object per line)."""
247
+ try:
248
+ value = json.loads(text)
249
+ except json.JSONDecodeError:
250
+ rows = []
251
+ for number, line in enumerate(text.splitlines(), 1):
252
+ if not line.strip():
253
+ continue
254
+ try:
255
+ rows.append(json.loads(line))
256
+ except json.JSONDecodeError as error:
257
+ raise BadArgs(f"inline items line {number}: not JSON ({error.msg})") from None
258
+ return rows
259
+ return value if isinstance(value, list) else [value]
260
+
261
+
262
+ def sets_of(debugger: Any) -> dict[str, PromptSet]:
263
+ if debugger not in _SETS:
264
+ _SETS[debugger] = {}
265
+ return _SETS[debugger]
266
+
267
+
268
+ def define(debugger: Any, name: str, rows: list[Any], source: str = "inline") -> PromptSet:
269
+ """Keep a prompt set under ``name`` on this debugger (replacing one of that name)."""
270
+ found = make_set(name, rows, source)
271
+ sets_of(debugger)[name] = found
272
+ return found
273
+
274
+
275
+ def load(debugger: Any, name: str, path: str) -> PromptSet:
276
+ return define(debugger, name, read_jsonl(path), source=str(path))
277
+
278
+
279
+ # --------------------------------------------------------------------------- binding
280
+
281
+
282
+ class Unbound(Exception):
283
+ """A template that does not bind for one item: the item is refused, the set goes on."""
284
+
285
+
286
+ class Bound:
287
+ """An item with its tokens: rows of its roles (``last`` included) and lazily its vars."""
288
+
289
+ def __init__(self, debugger: Any, item: Item, core: Any = None):
290
+ self.item = item
291
+ self.debugger = debugger
292
+ # a set-level checkpoint is for the items that bring no prompt or tokens of their own:
293
+ # an item with its own starts from them
294
+ self.core = item.core if item.core is not None else (
295
+ core if item.prompt is None else None)
296
+ if self.core is not None:
297
+ try:
298
+ self.checkpoint = debugger.load_checkpoint(self.core)
299
+ except (Refused, ValueError) as error:
300
+ raise Unbound(f"core: {error}") from None
301
+ self.tokens = list(self.checkpoint.prompt)
302
+ if item.prompt is not None:
303
+ try:
304
+ given = debugger.tokens(item.prompt)
305
+ except Refused as error:
306
+ raise Unbound(f"prompt: {error}") from None
307
+ if given != self.tokens:
308
+ raise Unbound("the item's prompt differs from its checkpoint's prompt")
309
+ else:
310
+ try:
311
+ self.tokens = debugger.tokens(item.prompt)
312
+ except Refused as error:
313
+ raise Unbound(f"prompt: {error}") from None
314
+ self.roles = {**item.roles, "last": len(self.tokens) - 1}
315
+
316
+ def row(self, role: str) -> int:
317
+ if role not in self.roles:
318
+ raise Unbound(f"no role {role!r} (roles: {', '.join(sorted(self.roles))})")
319
+ row = self.roles[role]
320
+ if row >= len(self.tokens):
321
+ raise Unbound(f"role {role} = row {row} is past the prompt ({len(self.tokens)} "
322
+ "tokens)")
323
+ return row
324
+
325
+ def var(self, name: str) -> int:
326
+ if name not in self.item.vars:
327
+ raise Unbound(f"no variable {name!r} (vars: {', '.join(sorted(self.item.vars))})")
328
+ value = self.item.vars[name]
329
+ if isinstance(value, int):
330
+ return value
331
+ tokenizer = self.debugger.tokenizer
332
+ if tokenizer is None:
333
+ raise Unbound(f"variable {name} is text ({value!r}); this model has no tokenizer, "
334
+ "give a token id")
335
+ ids = tokenizer.encode(value, add_special_tokens=False)
336
+ if len(ids) != 1:
337
+ raise Unbound(f"variable {name} = {value!r} is {len(ids)} tokens, not one")
338
+ return int(ids[0])
339
+
340
+
341
+ def _bind_plain(text: str, item: Bound) -> str:
342
+ whole = _BARE_ROLE.fullmatch(text)
343
+ if whole is not None:
344
+ return str(item.row(whole["role"]))
345
+ text = _T_ROLE.sub(lambda m: f"t{item.row(m['role'])}", text)
346
+ text = _EQ_ROLE.sub(lambda m: f"={item.row(m['role'])}", text)
347
+ return _VAR.sub(lambda m: str(item.var(m["var"])), text)
348
+
349
+
350
+ _ROWED = re.compile(r"(?:t-?\d+(?![\w]))|cache\.")
351
+
352
+
353
+ def _pair_address(addr: str, pair: Bound) -> str:
354
+ """``addr`` bound for the paired item. A port address with no row (``L20.A[h5]``) names
355
+ the paired item's own last row (``t<last>.L20.A[h5]``), not whatever row the asking item's
356
+ cursor is at; ``t@ROLE`` and a cache cell (it carries ``row=``) already name theirs."""
357
+ bound = _bind_plain(addr, pair)
358
+ if _ROWED.match(bound) or bound.isdigit():
359
+ return bound
360
+ return f"t{pair.row('last')}.{bound}"
361
+
362
+
363
+ def bind_text(text: str, item: Bound, pair: Bound | None = None,
364
+ pair_run: str | None = None) -> str:
365
+ """The template ``text`` with ``@pair:ADDR``, ``t@ROLE``, ``=@ROLE``, ``@ROLE`` and
366
+ ``$NAME`` replaced for ``item`` (``Unbound`` when one does not resolve)."""
367
+ out, last = [], 0
368
+ for match in _PAIR.finditer(text):
369
+ out.append(_bind_plain(_named(text[last:match.start()], item), item))
370
+ if pair is None or pair_run is None:
371
+ raise Unbound(f"@pair: item {item.item.name} has no pair")
372
+ out.append(f"{pair_run}:{_pair_address(_named(match['addr'], pair), pair)}")
373
+ last = match.end()
374
+ out.append(_bind_plain(_named(text[last:], item), item))
375
+ return "".join(out)
376
+
377
+
378
+ def _named(text: str, item: Bound) -> str:
379
+ """Named symbols in ``text`` for ``item``: a role symbol becomes ``t@ROLE...`` (bound
380
+ by the item's roles next), an absolute one its row when the item's prefix matches."""
381
+ from . import named
382
+
383
+ try:
384
+ return named.expand_for_item(item.debugger, text, item.tokens)
385
+ except Refused as error:
386
+ raise Unbound(_reason(error)) from None
387
+
388
+
389
+ def bind_prefill(text: str | None, item: Bound) -> int | None:
390
+ """``each ... prefill=K|@ROLE`` for one item: ``K``, or the row of the item's role ``ROLE``
391
+ (``@last`` steps only the last row, as the default does); ``Unbound`` when the role is
392
+ missing or the split is past the item's prompt. None: the default split."""
393
+ if text is None:
394
+ return None
395
+ text = str(text).strip()
396
+ if re.fullmatch(r"\d+", text):
397
+ prefill = int(text)
398
+ elif _BARE_ROLE.fullmatch(text):
399
+ prefill = item.row(text[1:])
400
+ else:
401
+ raise BadArgs(f"prefill is a row count K or @ROLE (a role of each item), not {text!r}")
402
+ if prefill > len(item.tokens) - 1:
403
+ raise Unbound(f"prefill={prefill} is past the prompt ({len(item.tokens)} tokens: "
404
+ f"prefill is 0..{len(item.tokens) - 1})")
405
+ return prefill
406
+
407
+
408
+ def _bind_args(name: str, args: dict[str, Any], item: Bound, pair: Bound | None,
409
+ pair_run: str | None) -> dict[str, Any]:
410
+ kinds = {arg.name: arg.type for arg in registry()[name].args}
411
+ out = {}
412
+ for key, value in args.items():
413
+ if isinstance(value, str):
414
+ bound = bind_text(value, item, pair, pair_run)
415
+ if bound != value and kinds.get(key) == "value":
416
+ try:
417
+ bound = float(bound)
418
+ except ValueError:
419
+ pass
420
+ value = bound
421
+ out[key] = value
422
+ return out
423
+
424
+
425
+ @dataclass(frozen=True)
426
+ class Step:
427
+ name: str
428
+ args: dict[str, Any]
429
+ text: str
430
+
431
+
432
+ def template(line: str) -> list[Step]:
433
+ """The op line(s) of ``each`` (``;`` separates lines), parsed and checked once with the
434
+ placeholders as text; ``BadArgs`` for the whole set when a line does not parse."""
435
+ steps = []
436
+ for part in (p.strip() for p in line.split(";")):
437
+ if not part:
438
+ continue
439
+ verb, _, rest = part.partition(" ")
440
+ name, rest = lines.route(lines.resolve_verb(verb), rest)
441
+ found = registry()[name]
442
+ if name in _FORBIDDEN or found.effect == "native":
443
+ raise BadArgs(f"each runs an op on each item's own run; {name} cannot be one of "
444
+ "its lines")
445
+ args = lines.parse(name, rest)
446
+ validate(found, args)
447
+ steps.append(Step(name, args, part))
448
+ if not steps:
449
+ raise BadArgs("each needs an op line: each SET: OP LINE")
450
+ return steps
451
+
452
+
453
+ # --------------------------------------------------------------------------- running
454
+
455
+
456
+ @dataclass
457
+ class EachResult:
458
+ """``summary``: the bounded summary record (what the ``each`` op returns); ``results``: item
459
+ name -> the op's ordinary result (refused items absent); ``statistics``: the full
460
+ ``analysis.numerics.summary.summarize`` output (not capped)."""
461
+
462
+ summary: dict[str, Any]
463
+ results: dict[str, dict[str, Any]]
464
+ statistics: dict[str, Any]
465
+
466
+
467
+ def _run_name(set_name: str, item: str) -> str:
468
+ return f"{set_name}-{item}"
469
+
470
+
471
+ def _pair_name(set_name: str, item: str) -> str:
472
+ return f"pair-{set_name}-{item}"
473
+
474
+
475
+ def _reason(error: BaseException) -> str:
476
+ return getattr(error, "message", None) or str(error) or type(error).__name__
477
+
478
+
479
+ def _goto(ctx: Context, at: str) -> None:
480
+ run = ctx.run
481
+ try:
482
+ here = run.parse(run.where) == run.parse(at)
483
+ except ValueError:
484
+ here = False
485
+ if not here:
486
+ dispatch(ctx, "until", {"target": at})
487
+
488
+
489
+ def _snapshot(ctx: Any, debugger: Any) -> dict[str, Any]:
490
+ from .inspect import _symbol_store
491
+ from .predict import session_digest
492
+
493
+ return {
494
+ "live": debugger.live, "runs": dict(debugger.runs),
495
+ "run_checkpoints": dict(getattr(debugger, "run_checkpoints", {}) or {}),
496
+ "carried": dict(getattr(debugger, "carried_circuits", {}) or {}),
497
+ "symbols": dict(_symbol_store(Context(debugger))),
498
+ "digest": session_digest(ctx) if getattr(ctx, "run", None) is not None else None,
499
+ "run": getattr(ctx, "run", None),
500
+ }
501
+
502
+
503
+ def _restore(debugger: Any, saved: dict[str, Any], kept: dict[str, Any]) -> None:
504
+ from .inspect import _symbol_store
505
+
506
+ debugger.runs.clear()
507
+ debugger.runs.update(saved["runs"])
508
+ debugger.runs.update(kept)
509
+ debugger.live = saved["live"]
510
+ if hasattr(debugger, "run_checkpoints"):
511
+ debugger.run_checkpoints.clear()
512
+ debugger.run_checkpoints.update(saved["run_checkpoints"])
513
+ if hasattr(debugger, "carried_circuits"):
514
+ debugger.carried_circuits.clear()
515
+ debugger.carried_circuits.update(saved["carried"])
516
+ store = _symbol_store(Context(debugger))
517
+ store.clear()
518
+ store.update(saved["symbols"])
519
+
520
+
521
+ def _check_names(debugger: Any, ctx: Any, names: list[str]) -> None:
522
+ owned = _OWNED.setdefault(debugger, set())
523
+ for name in names:
524
+ held = debugger.runs.get(name)
525
+ if held is None:
526
+ continue
527
+ if held is getattr(ctx, "run", None):
528
+ raise Refused(f"each would replace run {name}, the current run; frame another "
529
+ "run first")
530
+ if name not in owned:
531
+ raise Refused(f"each would replace run {name}, which it did not make; rename the "
532
+ "set or that run")
533
+
534
+
535
+ def parse_shard(text: str | None) -> tuple[int, int] | None:
536
+ """``shard=K/N`` -> ``(K, N)`` (1-based K): the K-th of N contiguous parts of the set."""
537
+ if text is None:
538
+ return None
539
+ match = re.fullmatch(r"\s*(\d+)\s*/\s*(\d+)\s*", str(text))
540
+ if not match or not 1 <= int(match[1]) <= int(match[2]):
541
+ raise BadArgs(f"shard is K/N with 1 <= K <= N, not {text!r}")
542
+ return int(match[1]), int(match[2])
543
+
544
+
545
+ def shard_items(items: tuple[Item, ...], shard: tuple[int, int] | None) -> tuple[Item, ...]:
546
+ if shard is None:
547
+ return items
548
+ k, n = shard
549
+ size = -(-len(items) // n)
550
+ return items[(k - 1) * size:k * size]
551
+
552
+
553
+ def run_each(ctx: Any, set_name: str, line: str, *, at: str | None = None,
554
+ keep: bool = False, prefill: str | None = None,
555
+ shard: str | None = None, core: Any = None) -> EachResult:
556
+ """Run ``line`` on every item of the set ``set_name`` (see the module docstring).
557
+ ``prefill`` (``K`` or ``@ROLE``): each item's run, and its pair's clean run, is started
558
+ with that split, bound per item (``bind_prefill``); None is the default split. ``shard``
559
+ (``K/N``): only the K-th of N contiguous parts of the set (so an mrun shard stays short);
560
+ the summary says which. ``core`` (Python): a checkpoint the items with no ``core``,
561
+ ``prompt`` or ``tokens`` of their own run from (rehydrated, no prefix recompute); an item
562
+ with its own prompt starts from it, and a pair donor is rehydrated only from its own
563
+ ``core``."""
564
+ from mdb.analysis.numerics import summary as stats
565
+
566
+ debugger = getattr(ctx, "debugger", None)
567
+ if debugger is None:
568
+ raise Refused("each needs an attached model")
569
+ found = sets_of(debugger).get(set_name)
570
+ if found is None:
571
+ known = ", ".join(sorted(sets_of(debugger))) or "none; set load NAME FILE"
572
+ raise Refused(f"no prompt set {set_name!r} (sets: {known})")
573
+ if prefill is not None:
574
+ prefill = str(prefill).strip()
575
+ if not (re.fullmatch(r"\d+", prefill) or _BARE_ROLE.fullmatch(prefill)):
576
+ raise BadArgs(f"prefill is a row count K or @ROLE (a role of each item), not "
577
+ f"{prefill!r}")
578
+ at = (at or DEFAULT_AT).strip()
579
+ steps = template(line)
580
+ uses_pair = "@pair:" in line
581
+ part = parse_shard(shard)
582
+ chosen = shard_items(found.items, part)
583
+ names = [_run_name(found.name, item.name) for item in chosen]
584
+ donors_needed = sorted({item.pair for item in chosen if item.pair} if uses_pair
585
+ else set())
586
+ _check_names(debugger, ctx, names + [_pair_name(found.name, p) for p in donors_needed])
587
+ saved = _snapshot(ctx, debugger)
588
+ made: dict[str, Any] = {}
589
+ donors: dict[str, tuple[Any, str | None]] = {}
590
+ rows, results = [], {}
591
+ try:
592
+ for item in chosen:
593
+ row, result = _one(debugger, saved, found, item, steps, at, uses_pair, made,
594
+ donors, prefill, core)
595
+ if keep and _run_name(found.name, item.name) in made:
596
+ row["run"] = _run_name(found.name, item.name)
597
+ rows.append(row)
598
+ if result is not None:
599
+ results[item.name] = result
600
+ if not keep: # released now: one item run is held at a time (donors aside)
601
+ released = made.pop(_run_name(found.name, item.name), None)
602
+ if released is not None and debugger.runs.get(released.name) is released:
603
+ debugger.runs.pop(released.name)
604
+ debugger.live = saved["live"]
605
+ finally:
606
+ kept = made if keep else {}
607
+ _OWNED.setdefault(debugger, set()).update(kept)
608
+ _restore(debugger, saved, kept)
609
+ if saved["run"] is not None:
610
+ from .predict import session_digest
611
+
612
+ if getattr(ctx, "run", None) is not saved["run"] or session_digest(ctx) != saved["digest"]:
613
+ raise RuntimeError("each changed the caller's session")
614
+ _put_blobs(debugger, rows, results)
615
+ full = stats.summarize([results[name] for name in results])
616
+ summary = _summary(found, line, steps, at, keep, rows, full, saved["digest"])
617
+ if part is not None:
618
+ summary["shard"] = {"k": part[0], "n": part[1], "items": len(chosen),
619
+ "set_total": len(found.items)}
620
+ if len(rows) > MAX_ITEMS:
621
+ from mdb.core.bounded import put_json
622
+
623
+ project = _writable(debugger)
624
+ summary["items_blob"] = put_json(rows, store=None if project is None else project.store,
625
+ run=debugger)
626
+ summary["items"] = rows[:MAX_ITEMS]
627
+ summary["items_omitted"] = len(rows) - MAX_ITEMS
628
+ if prefill is not None:
629
+ summary["prefill"] = prefill # the template; each item's row holds its bound split
630
+ entry_id = _remember(debugger, summary, results)
631
+ summary["id"] = entry_id
632
+ _store(debugger, summary)
633
+ return EachResult(summary, results, full)
634
+
635
+
636
+ def _one(debugger: Any, saved: dict[str, Any], found: PromptSet, item: Item,
637
+ steps: list[Step], at: str, uses_pair: bool, made: dict[str, Any],
638
+ donors: dict[str, tuple[Any, str | None]],
639
+ prefill: str | None = None, core: Any = None) -> tuple[dict[str, Any], Any]:
640
+ """One item: bind, make its run, run the steps. Returns its summary row and its result."""
641
+ from mdb.analysis.numerics import summary as stats
642
+
643
+ row: dict[str, Any] = {"name": item.name}
644
+ try:
645
+ bound = Bound(debugger, item, core)
646
+ split = bind_prefill(prefill, bound)
647
+ if split is not None and bound.core is not None:
648
+ raise Unbound("prefill does not apply to an item run from a checkpoint (its split "
649
+ "is the checkpoint's)")
650
+ pair = pair_run = None
651
+ if uses_pair and item.pair is not None:
652
+ pair = Bound(debugger, found.item(item.pair)) # its own core only, never the set's
653
+ pair_run = _pair_name(found.name, item.pair)
654
+ calls = [(step, _bind_args(step.name, step.args, bound, pair, pair_run))
655
+ for step in steps]
656
+ target = bind_text(at, bound)
657
+ except Unbound as error:
658
+ return {**row, "state": "refused", "reason": str(error)}, None
659
+ if split is not None:
660
+ row["prefill"] = split
661
+ if pair is not None:
662
+ reason = _donor(debugger, saved, found, pair, pair_run, at, made, donors,
663
+ None if pair.core is not None else prefill)
664
+ if reason is not None:
665
+ return {**row, "state": "refused", "reason": f"pair {item.pair}: {reason}"}, None
666
+ name = _run_name(found.name, item.name)
667
+ debugger.live = saved["live"] # each item run carries what a fresh start would
668
+ local = Context(debugger)
669
+ try:
670
+ _start_item(debugger, local, bound, name, split)
671
+ made[name] = local.run
672
+ _goto(local, target)
673
+ result = None
674
+ for number, (step, args) in enumerate(calls, 1):
675
+ try:
676
+ result = dispatch(local, step.name, args)
677
+ except OpError as error:
678
+ where = f"line {number} ({step.name})" if len(calls) > 1 else step.name
679
+ return {**row, "state": "refused", "reason": f"{where}: {_reason(error)}"}, None
680
+ except OpError as error:
681
+ return {**row, "state": "refused", "reason": f"at {target}: {_reason(error)}"}, None
682
+ row["state"] = result.get("state", "resolved")
683
+ row["result"] = seal_digest(result)
684
+ if isinstance(result.get("record"), str):
685
+ row["record"] = result["record"]
686
+ row["key"] = stats.key_columns(steps[-1].name, result)
687
+ row["bytes"] = int(local.run.held_total())
688
+ bound_args = {k: str(v) for k, v in calls[-1][1].items() if v != steps[-1].args.get(k)}
689
+ if bound_args:
690
+ row["bound"] = bound_args
691
+ if pair is not None:
692
+ found_at = sorted({m[0] for _, args in calls for v in args.values()
693
+ if isinstance(v, str)
694
+ for m in re.finditer(re.escape(pair_run) + r":[^\s,;=]+(?:\[[^\]]*\])?",
695
+ v)})
696
+ if found_at:
697
+ row["donor"] = found_at
698
+ return row, result
699
+
700
+
701
+ def _start_item(debugger: Any, local: Context, bound: Bound, name: str,
702
+ split: int | None) -> None:
703
+ """The item's run: ``start`` of its tokens, or rehydrated from its checkpoint (``core``)."""
704
+ if bound.core is None:
705
+ dispatch(local, "start", {"prompt": bound.tokens, "name": name,
706
+ **({} if split is None else {"prefill": split})})
707
+ return
708
+ try:
709
+ run = debugger.run_from(bound.checkpoint, name=name, check=False)
710
+ except ValueError as error:
711
+ raise Refused(f"core: {error}") from None
712
+ getattr(debugger, "run_checkpoints", {}).pop(run.name, None)
713
+ local.set_run(run)
714
+
715
+
716
+ def _donor(debugger: Any, saved: dict[str, Any], found: PromptSet, pair: Bound,
717
+ run_name: str, at: str, made: dict[str, Any],
718
+ donors: dict[str, tuple[Any, str | None]], prefill: str | None = None) -> str | None:
719
+ """Make (once) the clean run of the paired item at its ``at`` stop, under ``prefill``
720
+ bound for the paired item (its own role row); the refusal reason."""
721
+ if pair.item.name in donors:
722
+ return donors[pair.item.name][1]
723
+ reason = None
724
+ debugger.live = saved["live"]
725
+ local = Context(debugger)
726
+ try:
727
+ target = bind_text(at, pair)
728
+ split = bind_prefill(prefill, pair)
729
+ _start_item(debugger, local, pair, run_name, split)
730
+ made[run_name] = local.run
731
+ _goto(local, target)
732
+ except Unbound as error:
733
+ reason = str(error)
734
+ except OpError as error:
735
+ reason = _reason(error)
736
+ donors[pair.item.name] = (local.run, reason)
737
+ return reason
738
+
739
+
740
+ # --------------------------------------------------------------------------- the record
741
+
742
+
743
+ def _summary(found: PromptSet, line: str, steps: list[Step], at: str, keep: bool,
744
+ rows: list[dict[str, Any]], full: dict[str, Any], digest: str | None
745
+ ) -> dict[str, Any]:
746
+ refused = [row for row in rows if row["state"] == "refused"]
747
+ ran = len(rows) - len(refused)
748
+ if refused:
749
+ names = ", ".join(row["name"] for row in refused[:8])
750
+ more = f" +{len(refused) - 8} more" if len(refused) > 8 else ""
751
+ exclusion = (f"{len(refused)} of {len(rows)} items refused ({names}{more}) and "
752
+ f"excluded; statistics over the {ran} others")
753
+ else:
754
+ exclusion = f"none refused; statistics over all {ran} items"
755
+ key_paths = [path for row in rows if "key" in row for path in row["key"]["paths"]]
756
+ numeric = sorted(full["numeric"],
757
+ key=lambda s: key_paths.index(s["path"]) if s["path"] in key_paths
758
+ else len(key_paths))
759
+ for row in rows:
760
+ if "key" in row:
761
+ row["key"].pop("paths", None)
762
+ out: dict[str, Any] = {
763
+ "set": found.name, "line": line, "verb": steps[-1].name, "at": at,
764
+ "total": len(rows), "items": rows,
765
+ "statistics": {
766
+ "n": full["n"], "exclusion": exclusion,
767
+ "numeric": numeric[:MAX_NUMERIC],
768
+ "verdicts": full["verdicts"][:MAX_VERDICTS],
769
+ "omitted": {"count": max(0, len(numeric) - MAX_NUMERIC)
770
+ + max(0, len(full["verdicts"]) - MAX_VERDICTS)},
771
+ "partial": {"count": full["partial"],
772
+ "meaning": "paths present in some items only: not summarised"},
773
+ },
774
+ "runs": "kept as named runs SET-ITEM (frame NAME:)" if keep else "released",
775
+ }
776
+ if digest is not None:
777
+ out["session"] = {"unchanged": True, "debugger": digest}
778
+ return out
779
+
780
+
781
+ def _remember(debugger: Any, summary: dict[str, Any], results: dict[str, Any]) -> str:
782
+ ledger = _RESULTS.setdefault(debugger, {})
783
+ number = 1 + max((int(k[4:]) for k in ledger), default=0)
784
+ key = f"each{number}"
785
+ ledger[key] = {"summary": summary, "results": results}
786
+ while len(ledger) > MAX_RESULTS:
787
+ ledger.pop(next(iter(ledger)))
788
+ return key
789
+
790
+
791
+ def _writable(debugger: Any) -> Any:
792
+ project = getattr(debugger, "project", None)
793
+ return None if project is None or project.read_only else project
794
+
795
+
796
+ def _put_blobs(debugger: Any, rows: list[dict[str, Any]], results: dict[str, Any]) -> None:
797
+ """Each item's result as a sha256-checked JSON blob (an op result is not a valid record
798
+ body, so it cannot be a record); the row's ``blob`` is the pointer. No writable project:
799
+ the row says the result is held in memory only."""
800
+ from mdb.core.bounded import put_json
801
+
802
+ project = _writable(debugger)
803
+ for row in rows:
804
+ if row["name"] not in results:
805
+ continue
806
+ if project is None:
807
+ row["blob"] = {"state": "absent",
808
+ "reason": "held in memory only (no writable project)"}
809
+ else:
810
+ row["blob"] = put_json(results[row["name"]], store=project.store)
811
+
812
+
813
+ def _stored_entry(debugger: Any, record_id: str) -> dict[str, Any] | None:
814
+ """The stored ``prompt-set`` summary named ``record_id`` (a summary's ``stored``), or None."""
815
+ project = getattr(debugger, "project", None)
816
+ if project is None:
817
+ return None
818
+ from mdb.core import index
819
+ from mdb.core.pointers import RecordError
820
+
821
+ try:
822
+ record = index.get_record(project, debugger.session_id, record_id)
823
+ except (RecordError, LookupError, KeyError, OSError):
824
+ return None
825
+ return record["body"] if record.get("kind") == "prompt-set" else None
826
+
827
+
828
+ def load_item_result(debugger: Any, summary: dict[str, Any], item: str) -> dict[str, Any]:
829
+ """The item's result from its blob (checked against the blob's sha256 and the row's result
830
+ digest); ``Refused`` when the row has no stored blob or the blob fails a check."""
831
+ from mdb.core.bounded import load_json
832
+ from mdb.core.pointers import Unresolved
833
+
834
+ row = next((r for r in summary["items"] if r["name"] == item), None)
835
+ if row is None and "items_blob" in summary:
836
+ from mdb.core.bounded import load_json
837
+
838
+ try:
839
+ rows = load_json(summary["items_blob"], store=debugger.project.store
840
+ if getattr(debugger, "project", None) else None, run=debugger)
841
+ except ValueError:
842
+ rows = []
843
+ row = next((r for r in rows if r["name"] == item), None)
844
+ blob = None if row is None else row.get("blob")
845
+ if blob is None or blob.get("state") != "stored":
846
+ raise Refused(f"{item!r} has no stored result: "
847
+ + ("not in the set or refused" if row is None or "result" not in row
848
+ else (blob or {}).get("reason", "held in memory only")))
849
+ try:
850
+ result = load_json(blob, store=debugger.project.store)
851
+ except (ValueError, Unresolved) as error:
852
+ raise Refused(f"stored result of {item!r} refused: "
853
+ f"{getattr(error, 'reason', None) or error}") from None
854
+ if seal_digest(result) != row["result"]:
855
+ raise Refused(f"stored result of {item!r} refused: it differs from the row's digest")
856
+ return result
857
+
858
+
859
+ def _store(debugger: Any, summary: dict[str, Any]) -> None:
860
+ """With a writable project: the summary as one ``prompt-set`` record. Item results are
861
+ referenced by digest and by blob pointer (and by the op's own record id where the op seals
862
+ one, as ``whatif`` does); an op result is not a record body (its pointers and bounds are not
863
+ ``num`` claims), so the results themselves are the blobs ``_put_blobs`` stored."""
864
+ project = _writable(debugger)
865
+ if project is None:
866
+ return
867
+ from mdb.core import index
868
+ from mdb.core.kinds import PROMPT_SET # noqa: F401 (declares the kind)
869
+ from mdb.core.records import seal_record
870
+
871
+ try:
872
+ record = seal_record(session_id=debugger.session_id, kind="prompt-set",
873
+ model_identity=debugger.adapter.model_identity,
874
+ execution=dict(debugger.adapter.execution),
875
+ authority="derived-exact",
876
+ body={k: v for k, v in summary.items() if k != "session"})
877
+ summary["stored"] = index.put_record(project, record)
878
+ except RecordError as error:
879
+ summary["stored"] = {"state": "unresolved", "reason": f"not stored: {error}"}
880
+
881
+
882
+ # --------------------------------------------------------------------------- ops
883
+
884
+
885
+ def _op_each(ctx, set, line, at, keep, prefill=None, shard=None): # noqa: A002 - wire name
886
+ return run_each(ctx, set, line, at=at, keep=keep, prefill=prefill, shard=shard).summary
887
+
888
+
889
+ def _item_view(item: Item) -> dict[str, Any]:
890
+ out: dict[str, Any] = {"name": item.name}
891
+ if item.core is not None:
892
+ out["core"] = item.core if isinstance(item.core, str) else getattr(item.core, "id", "?")
893
+ if item.prompt is None:
894
+ pass
895
+ elif isinstance(item.prompt, str):
896
+ out["prompt"] = item.prompt if len(item.prompt) <= 200 else item.prompt[:200] + "..."
897
+ else:
898
+ out["prompt_tokens"] = len(item.prompt)
899
+ out["ids"] = list(item.prompt[:16])
900
+ out["roles"] = [{"name": k, "row": v} for k, v in item.roles.items()]
901
+ out["vars"] = [{"name": k, "token": v} if isinstance(v, int) else {"name": k, "text": v}
902
+ for k, v in item.vars.items()]
903
+ if item.pair is not None:
904
+ out["pair"] = item.pair
905
+ return out
906
+
907
+
908
+ def _op_promptset(ctx, action, name, arg):
909
+ debugger = getattr(ctx, "debugger", None)
910
+ if debugger is None:
911
+ raise Refused("prompt sets need an attached model")
912
+ known = sets_of(debugger)
913
+ if action == "list":
914
+ return {"action": "list", "sets": [{"set": n, "total": len(s.items), "source": s.source}
915
+ for n, s in sorted(known.items())][:64]}
916
+ if not name:
917
+ raise BadArgs(f"promptset {action} needs a name")
918
+ if action == "load":
919
+ if not arg:
920
+ raise BadArgs("write set load NAME FILE")
921
+ found = load(debugger, name, arg)
922
+ elif action == "define":
923
+ if not arg:
924
+ raise BadArgs("promptset define NAME ITEMS: ITEMS is a JSON list of items (or "
925
+ "JSONL, one item per line)")
926
+ found = define(debugger, name, _inline_rows(arg))
927
+ elif action == "show":
928
+ if name not in known:
929
+ raise Refused(f"no prompt set {name!r} (sets: {', '.join(sorted(known)) or 'none'})")
930
+ found = known[name]
931
+ else: # result
932
+ entry = _RESULTS.get(debugger, {}).get(name)
933
+ if entry is None:
934
+ stored = _stored_entry(debugger, name)
935
+ if stored is None:
936
+ held = ", ".join(_RESULTS.get(debugger, {})) or "none"
937
+ raise Refused(f"no each result {name!r} in memory (held: {held}) and no stored "
938
+ "summary of that record id in the project")
939
+ if not arg:
940
+ return {"action": "result", "id": name, "summary": stored}
941
+ return {"action": "result", "id": name, "item": arg,
942
+ "result": load_item_result(debugger, stored, arg), "from": "stored blob"}
943
+ if not arg:
944
+ return {"action": "result", "id": name, "summary": entry["summary"]}
945
+ if arg not in entry["results"]:
946
+ raise Refused(f"{name} holds no result for item {arg!r} (refused, or not in the "
947
+ "set)")
948
+ return {"action": "result", "id": name, "item": arg, "result": entry["results"][arg]}
949
+ out = {"action": action, "set": found.name, "source": found.source,
950
+ "total": len(found.items),
951
+ "items": [_item_view(item) for item in found.items[:MAX_ITEMS]]}
952
+ if len(found.items) > MAX_ITEMS:
953
+ out["items_omitted"] = len(found.items) - MAX_ITEMS
954
+ return out
955
+
956
+
957
+ register(Op("each", "Run one op line on every prompt of a set (one run per prompt): one result "
958
+ "per prompt and a summary (n, mean, min, max, sign agreement, verdict counts)",
959
+ (Arg("set", "str", required=True, help="a prompt set (set load NAME FILE)"),
960
+ Arg("line", "str", required=True, positional=False,
961
+ help="the op line(s); t@ROLE, =@ROLE, $VAR and @pair:ADDR bind per item"),
962
+ Arg("at", "str", default=DEFAULT_AT, positional=False,
963
+ help="where each item's run stops before the line runs"),
964
+ Arg("keep", "bool", default=False, positional=False,
965
+ help="keep the item runs as named runs SET-ITEM"),
966
+ Arg("prefill", "str", positional=False,
967
+ help="each item's prefill split: K, or @ROLE (that role's row of each item; "
968
+ "the pair's clean run takes its own role row); default all but the last"),
969
+ Arg("shard", "str", positional=False,
970
+ help="K/N: run only the K-th of N contiguous parts of the set")),
971
+ "native", False, _op_each,
972
+ usage="each SET [at=ADDR] [prefill=K|@ROLE] [shard=K/N] [keep]: OP LINE "
973
+ "[; OP LINE ...]"))
974
+ register(Op("promptset", "Prompt sets: load a JSONL file, show or list sets, read a stored each "
975
+ "result (the REPL's set load / set show)",
976
+ (Arg("action", "choice", required=True, choices=("load", "define", "show", "list", "result")),
977
+ Arg("name", "str", help="the set (load, show) or the each result id (result)"),
978
+ Arg("arg", "str", help="load: the JSONL file (not served: send the set inline); "
979
+ "define: the items as JSON; result: an item name")),
980
+ "mutate", False, _op_promptset,
981
+ usage="set load NAME FILE | set define NAME ITEMS | set show NAME | "
982
+ "promptset list | "
983
+ "promptset result ID [ITEM]"))
984
+
985
+
986
+ def check_summary(summary: dict[str, Any]) -> dict[str, Any]:
987
+ """The summary record under the pointer rule (64 KiB, no arrays); raises ``RecordError``."""
988
+ return check_bounded(summary, "each summary")