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,1516 @@
1
+ Metadata-Version: 2.5
2
+ Name: model-debugger
3
+ Version: 0.4.0
4
+ Summary: A gdb-style debugger for language models: step native decoder layers port by port, edit, checkpoint, rewind, and capture ports passively.
5
+ Project-URL: Homepage, https://github.com/JHollenb/saturn
6
+ Project-URL: Repository, https://github.com/JHollenb/saturn
7
+ Project-URL: Issues, https://github.com/JHollenb/saturn/issues
8
+ Project-URL: Changelog, https://github.com/JHollenb/saturn/blob/main/packages/mdb/CHANGELOG.md
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: model-runtime<0.6,>=0.5.0
14
+ Requires-Dist: tomli>=2; python_version < '3.11'
15
+ Provides-Extra: all
16
+ Requires-Dist: accelerate==1.14.0; extra == 'all'
17
+ Requires-Dist: diffusers==0.39.0; extra == 'all'
18
+ Requires-Dist: numpy>=2.0; extra == 'all'
19
+ Requires-Dist: pillow>=10.0; extra == 'all'
20
+ Requires-Dist: safetensors>=0.5; extra == 'all'
21
+ Requires-Dist: torch==2.13.0; extra == 'all'
22
+ Requires-Dist: transformers==5.14.1; extra == 'all'
23
+ Provides-Extra: autoregressive
24
+ Requires-Dist: accelerate==1.14.0; extra == 'autoregressive'
25
+ Requires-Dist: numpy>=2.0; extra == 'autoregressive'
26
+ Requires-Dist: safetensors>=0.5; extra == 'autoregressive'
27
+ Requires-Dist: torch==2.13.0; extra == 'autoregressive'
28
+ Requires-Dist: transformers==5.14.1; extra == 'autoregressive'
29
+ Provides-Extra: dev
30
+ Requires-Dist: hatchling>=1.25; extra == 'dev'
31
+ Requires-Dist: pytest>=8.0; extra == 'dev'
32
+ Requires-Dist: ruff>=0.5; extra == 'dev'
33
+ Requires-Dist: tomli>=2; (python_version < '3.11') and extra == 'dev'
34
+ Provides-Extra: diffusion
35
+ Requires-Dist: accelerate==1.14.0; extra == 'diffusion'
36
+ Requires-Dist: diffusers==0.39.0; extra == 'diffusion'
37
+ Requires-Dist: numpy>=2.0; extra == 'diffusion'
38
+ Requires-Dist: pillow>=10.0; extra == 'diffusion'
39
+ Requires-Dist: safetensors>=0.5; extra == 'diffusion'
40
+ Requires-Dist: torch==2.13.0; extra == 'diffusion'
41
+ Requires-Dist: transformers==5.14.1; extra == 'diffusion'
42
+ Provides-Extra: discovery
43
+ Requires-Dist: numpy>=2.0; extra == 'discovery'
44
+ Requires-Dist: safetensors>=0.5; extra == 'discovery'
45
+ Requires-Dist: torch==2.13.0; extra == 'discovery'
46
+ Provides-Extra: interop
47
+ Requires-Dist: nnsight==0.8.2; extra == 'interop'
48
+ Requires-Dist: transformer-lens==4.4.0; extra == 'interop'
49
+ Provides-Extra: s3
50
+ Requires-Dist: boto3>=1.28; extra == 's3'
51
+ Provides-Extra: saelens
52
+ Requires-Dist: sae-lens<7,>=6; extra == 'saelens'
53
+ Provides-Extra: serve
54
+ Requires-Dist: fastapi>=0.115; extra == 'serve'
55
+ Requires-Dist: numpy>=2.0; extra == 'serve'
56
+ Requires-Dist: pydantic>=2.7; extra == 'serve'
57
+ Requires-Dist: uvicorn>=0.30; extra == 'serve'
58
+ Requires-Dist: websockets>=12; extra == 'serve'
59
+ Provides-Extra: transformerlens
60
+ Requires-Dist: accelerate==1.14.0; extra == 'transformerlens'
61
+ Requires-Dist: numpy>=2.0; extra == 'transformerlens'
62
+ Requires-Dist: safetensors>=0.5; extra == 'transformerlens'
63
+ Requires-Dist: torch==2.13.0; extra == 'transformerlens'
64
+ Requires-Dist: transformer-lens==4.2.0; extra == 'transformerlens'
65
+ Requires-Dist: transformers==5.14.1; extra == 'transformerlens'
66
+ Description-Content-Type: text/markdown
67
+
68
+ # mdb
69
+
70
+ mdb is a debugger for language models, in the spirit of gdb. It drives a loaded Hugging Face
71
+ decoder (Qwen2, Qwen3, Llama or Mistral) one native operation at a time and stops inside each
72
+ layer at named values called ports (the attention weights, the MLP output, the residual stream,
73
+ ...). At a stop you can read a value, edit it, checkpoint and rewind, patch in a value from
74
+ another run, or seal a prediction of a later value and then check it against what the model
75
+ actually computed. Every number it prints carries a label that says how it was obtained
76
+ (`measured`, `derived-exact`, `bound`, ...). It runs one prompt at a time (batch 1), with eager
77
+ attention, on CPU or CUDA.
78
+
79
+ This directory is the `model-debugger` distribution (import name `mdb`). It depends on `model-runtime`,
80
+ whose `Session` runs the model.
81
+
82
+ ## Install
83
+
84
+ Available on PyPI from 0.4.0:
85
+
86
+ ```
87
+ pip install "model-debugger[autoregressive]"
88
+ ```
89
+
90
+ It brings `model-runtime` (import `saturn`) with it. Until 0.4.0 the distribution was
91
+ `mdb-runtime` (and Saturn's was `saturn-pub`), installed from Git; remove an old install first
92
+ with `pip uninstall saturn-pub mdb-runtime`.
93
+
94
+ From a checkout of the [saturn repository](https://github.com/JHollenb/saturn) (`main` is the
95
+ development branch; `git checkout mdb-vX.Y.Z` gives a release):
96
+
97
+ ```
98
+ git clone https://github.com/JHollenb/saturn
99
+ cd saturn
100
+ pip install . "./packages/mdb[autoregressive]"
101
+ ```
102
+
103
+ Release tags and branches: [docs/RELEASING.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/RELEASING.md).
104
+
105
+ To edit the code instead: `pip install -e . -e "./packages/mdb[autoregressive]"`. The
106
+ `autoregressive` extra brings torch 2.13.0, transformers 5.14.1 and accelerate; without it only
107
+ the framework-free commands work. `serve` adds the web viewer, `interop` adds TransformerLens and
108
+ nnsight. See [docs/INSTALL.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/INSTALL.md).
109
+
110
+ ## Hello world (laptop CPU, nothing downloaded)
111
+
112
+ `tiny:qwen2` is a random 2-layer Qwen2 built in memory (bf16, vocabulary 32, no tokenizer, so a
113
+ prompt is token ids). It shows the mechanics; its numbers mean nothing.
114
+
115
+ ```
116
+ $ mdb engine tiny:qwen2 --tokens "1 5 9 3"
117
+ (mdb) start 1 5 9 3
118
+ t3.L0.h h = layer input (residual stream) {P01}
119
+ (mdb) until L1.p
120
+ t3.L1.p p = softmax(s, float32).to(dtype) (native attention weights) {P05 P06 P07 P08 P09}
121
+ (mdb) print top=2
122
+ t3.L1.p bfloat16 [1, 2, 1, 4] (batch, head, row, src)
123
+ norm 0.70607 min 0.24902 max 0.25 mean 0.24963 abs_max 0.25 [measured]
124
+ top |v|: [0,0,0,0] 0.25, [0,0,0,3] 0.25 [measured]
125
+ pointer occurrence ~stepped sha256 a3a32de6269f57e6 cut 75d6b82e6573
126
+ (mdb) checkpoint pre
127
+ checkpoint pre at t3.L1.p (750 bytes)
128
+ (mdb) set L1.m = 0 scale
129
+ staged at t3.L1.m: m scale 0 [supplied] (not fired yet) (1 staged)
130
+ (mdb) until logits
131
+ t3.logits logits = lm_head(fn)
132
+ (mdb) print logits top=3
133
+ t3.logits bfloat16 [1, 32] (batch, vocab)
134
+ norm 0.39659 min -0.16699 max 0.13477 mean -0.0077629 abs_max 0.16699 [measured, under edit t3.L1.m]
135
+ top: [0,20] 0.13477, [0,22] 0.10352, [0,10] 0.10156 [measured, under edit t3.L1.m]
136
+ pointer occurrence ~stepped sha256 88df038247cb2036 cut 40ae8df24e5e
137
+ (mdb) restart pre
138
+ t3.L1.p p = softmax(s, float32).to(dtype) (native attention weights) {P05 P06 P07 P08 P09}
139
+ (mdb) info edits
140
+ staged at t3.L1.p: none
141
+ ```
142
+
143
+ The same in Python:
144
+
145
+ ```python
146
+ import mdb
147
+
148
+ dbg = mdb.open_tiny("qwen2") # random tiny Qwen2 on CPU; or mdb.attach(model, tokenizer)
149
+ run = dbg.run([1, 5, 9, 3]) # prefill 3 tokens; cursor at t3.L0.h
150
+ run.until("L1.p") # stop inside layer 1 at the attention weights
151
+ saved = run.checkpoint("pre")
152
+ run.set("L1.m", 0.0, "scale") # stage an edit further down the same layer
153
+ print(run.until("logits"), run.read()[0, :3], run.read_info()["upstream_edits"])
154
+ print(run.restore(saved), run.edits) # back at t3.L1.p, nothing staged
155
+ ```
156
+
157
+ ```
158
+ t3.logits tensor([-0.0233, 0.0430, 0.0220], dtype=torch.bfloat16) [{'row': 3, 'layer': 1, 'port': 'm', 'op': 'scale', 'staged': False, 'selection': None}]
159
+ t3.L1.p []
160
+ ```
161
+
162
+ Both were run in a fresh virtual environment after the install above (Python 3.12, macOS, CPU).
163
+ The `cut` fingerprints differ from run to run; everything else is fixed. A longer CPU walk
164
+ (step, set, watch, branch, symbols, forecast and verify) is
165
+ [examples/00-hello-tiny](https://github.com/JHollenb/saturn/tree/main/packages/mdb/examples/00-hello-tiny).
166
+
167
+ Except for [Measured on a real model](#measured-on-a-real-model) and the GPU examples, every
168
+ command and code block below was run on a random tiny model on a CPU, offline, and the output
169
+ shown is the real output. `...` marks a cut. Tags such as `{P05 P06}` name the mathematical
170
+ identities a port or a number relies on ([docs/PROOF-IDS.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/PROOF-IDS.md)). Terms are
171
+ defined in the [Glossary](#glossary).
172
+
173
+ Next, the same REPL on a small real model on CPU (Qwen3-0.6B, about 15 s and 3 GB measured on a
174
+ laptop): [docs/REAL-MODEL-CPU.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/REAL-MODEL-CPU.md).
175
+
176
+ ## Quick start
177
+
178
+ `mdb engine MODEL` (or `python -m mdb engine`, or `python -m mdb.repl`) opens the REPL; it reads
179
+ commands from the terminal or from `--script FILE`, and `--tokens "..."` issues the `start`
180
+ (`--prompt TEXT` or a `PROMPT` after `MODEL` starts on text, with the checkpoint's tokenizer).
181
+ `--tiny FAMILY` and `--model PATH|NAME` are the flag forms of `MODEL`, `--connect URL` drives a
182
+ running `mdb serve`, `--dtype bf16|fp32` and `--device` pick the numeric scope, `--seed` seeds a
183
+ tiny model and `--json` prints raw op results as JSON lines (`mdb engine --help` lists the rest).
184
+ `backtrace` shows the producer chain of the focused port:
185
+
186
+ ```
187
+ (mdb) backtrace
188
+ p <- s <- qr,kr <- q,k <- a <- h
189
+ #0 t3.L1.p p = softmax(s, float32).to(dtype) (native attention weights) {P05 P06 P07 P08 P09} <- s
190
+ ... (#1 to #5 cut: s, qr, kr, q, k, a, h)
191
+ ```
192
+
193
+ `start` prefills all tokens but the last; the last token (row 3) is the one you step through.
194
+ `start prefill=K` batches only the first K rows and steps the rest one row at a time, so their
195
+ ports are stops too (see [Prefill split and position patching](#prefill-split-and-position-patching)).
196
+ `mdb engine MODEL [PROMPT]` names what to debug, as `gdb PROGRAM` does. `MODEL` is a checkpoint
197
+ directory, the name of a model in the local Hugging Face cache (`mdb engine qwen2.5-1.5b
198
+ "Weather: freezing"`; the name lookup was run against a real cache, the model was not loaded
199
+ here), `tiny:qwen2`, `tiny:qwen3`, `tiny:llama` or `tiny:mistral` (the same four as `--tiny` of `mdb engine` and `mdb serve`), or the address of a running `mdb serve` (see
200
+ [Live and remote sessions](#live-and-remote-sessions-mdb-serve)). Nothing is ever downloaded; a
201
+ name that matches no cached model, or several, is refused with the candidates. `--project DIR`
202
+ attaches a project, which makes checkpoints durable.
203
+
204
+ Defaults such as `--dtype`, `--device`, `--project`, model directories and aliases, the record
205
+ sink and a REPL init file can live in `~/.config/mdb/config.toml` or a project's `mdb.toml`
206
+ (`mdb config init`, `mdb config show`). Settings that change a verdict (floors, `lookahead`,
207
+ `prefill`, `retain_rows`, branch options) are refused there and stay in the command. When a
208
+ config file sets a setting that reaches a record (model, dtype, device, session, kernel path,
209
+ SAE sources, init file, REPL defaults), every record names the file and its sha256. Python
210
+ calls (`mdb.open_tiny`, `mdb.attach`, `mdb.engine.models.load_local`, a debugger's
211
+ `records_to`) read the same settings for arguments
212
+ you leave out. See [docs/CONFIG.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/CONFIG.md).
213
+
214
+ ## Coming from TransformerLens or nnsight
215
+
216
+ mdb uses its own words for things you already know. Left: the usual term. Right: mdb's. Port names
217
+ are the Qwen2 ones in the [Ports](#ports) table; `L<L>` is the layer number. "Roughly" means the
218
+ tensor has another shape or sits at another position, so do not swap them blindly.
219
+
220
+ | TransformerLens / nnsight / pyvene | mdb |
221
+ |---|---|
222
+ | hook point, module hook | port: a named value inside one decoder layer, address `L<L>.<port>` |
223
+ | `blocks.L.hook_resid_pre` | `L<L>.h` (layer input) |
224
+ | `blocks.L.hook_resid_post` | `L<L>.h_out` (layer output) |
225
+ | `blocks.L.hook_resid_mid` | `L<L>.r` (`h + o`) |
226
+ | `blocks.L.attn.hook_pattern` | `L<L>.p` (per head, `p[h5]`; native attention weights) |
227
+ | `blocks.L.attn.hook_z` | roughly `L<L>.A`: `hook_z` is per head, before `W_O`; `A` is the heads concatenated, at the `o_proj` input (`A[h5]` selects one head's slice) |
228
+ | `blocks.L.hook_attn_out` | `L<L>.o` (after `o_proj`) |
229
+ | `blocks.L.attn.hook_q` / `hook_k` / `hook_v` | roughly `L<L>.q` / `k` / `v`: mdb's are flat, `[batch, row, head*head_dim]`, `q` and `k` before RoPE |
230
+ | `blocks.L.attn.hook_attn_scores` | `L<L>.s` (a replica checked against `p`, see Ports) |
231
+ | `blocks.L.mlp.hook_post` | `L<L>.f` (`down_proj` input) |
232
+ | `blocks.L.hook_mlp_out` | `L<L>.m` |
233
+ | activation cache (`run_with_cache`, `trace`) | reading ports with `print` / `x` at a stop, or `mdb.trace` in Python; one prompt, one row at a time |
234
+ | activation patching | `set ADDR = OTHERRUN:ADDR` for ports (`set L0.A[h1] = clean:L0.A[h1]`, see the example) and state cells; `whatif` and `compare` take the same value and measure the edit natively, then restore; at earlier positions after `start prefill=K`; the position x layer sweep is `sweep PORT = OTHERRUN --consumer C` |
235
+ | head or path ablation | `set L<L>.A[h5] *= 0` (selector `[h5]`); `whatif` for the effect without leaving the stop |
236
+ | direct logit attribution | `explain M[a,b]` (exact split of a margin, with a measured remainder) |
237
+ | KV cache | state cells `cache.L<L>.k` / `v[kv0,row=2]`; readable, editable, and takeable from another run |
238
+ | a dataset of prompts, `run_with_cache` over a batch | a prompt set: `each SET: OP LINE` runs any verb on every prompt, one run per prompt, with a summary (see [Prompt sets](#prompt-sets)); no batched forward (the engine is batch 1) |
239
+ | SAE features, dictionary units | `sae load` reads residual SAEs (and transcoders) from local files, `features` / `feature` split a value into features plus the error term (see [SAE feature bases](#sae-feature-bases-sae-features-feature)); mdb's own unit is a named symbol declared from a transplant (`symbol NAME = whatif`, see [Named symbols](#named-symbols-from-a-transplant)) |
240
+
241
+ Example: patch one head's output from a clean run into a corrupted run and read a logit
242
+ difference. TransformerLens style, not run (patched at the last position: an mdb port edit acts
243
+ on the cursor's row; by default the earlier prompt rows are prefilled and live in the cache
244
+ cells, and `start prefill=K` makes them stepped rows with ports, see below):
245
+
246
+ ```python
247
+ # pseudocode, not run
248
+ _, clean_cache = model.run_with_cache(clean_tokens)
249
+ def patch(z, hook): # z: [batch, pos, head, d_head]
250
+ z[:, -1, 1] = clean_cache[hook.name][:, -1, 1]
251
+ return z
252
+ patched = model.run_with_hooks(corrupt_tokens, fwd_hooks=[("blocks.0.attn.hook_z", patch)])
253
+ diff = patched[0, -1, 6] - patched[0, -1, 7]
254
+ ```
255
+
256
+ mdb, on the tiny Qwen2 (clean prompt `1 7 9 3`, corrupted `1 5 9 3`, only row 1 differs; the
257
+ logit difference is token 6 minus token 7 at the last row, bf16), real output with the long
258
+ lines cut:
259
+
260
+ ```
261
+ $ python -m mdb engine tiny:qwen2 --tokens "1 5 9 3" --script FILE
262
+ (mdb) start name=corrupt 1 5 9 3
263
+ (mdb) checkpoint s0
264
+ (mdb) run name=clean 1 7 9 3
265
+ (mdb) until logits
266
+ (mdb) x logits 2 6
267
+ t3.logits [6:8] of 32: -0.14355 -0.12451 [measured]
268
+ (mdb) frame corrupt:
269
+ (mdb) until logits
270
+ (mdb) x logits 2 6
271
+ t3.logits [6:8] of 32: -0.16699 -0.15332 [measured]
272
+ (mdb) restart s0
273
+ (mdb) set L0.A[h1] = clean:L0.A[h1]
274
+ staged at t3.L0.A[h1]: A replace tensor [1, 1, 16] bfloat16 sha256 f111ca510505 from clean:t3.L0.A[h1] (live) on [h1] (8 elements) (not fired yet) (1 staged)
275
+ value from clean:t3.L0.A[h1]
276
+ realised as one masked replace on the selected elements
277
+ (mdb) until logits
278
+ (mdb) x logits 2 6
279
+ t3.logits [6:8] of 32: -0.1709 -0.14844 [measured, under edit t3.L0.A]
280
+ (mdb) whatif L1.m = clean:L1.m --consumer M[6,7]
281
+ whatif t3.L1.m replace tensor 7b16b2586286 from clean:t3.L1.m -> t3.M[6,7] (mode rewind, ...)
282
+ sealed linear ΔM = -0.00021868 [derived-local P14] exact ΔM = -0.00021847 [derived-exact] ...
283
+ native ΔM = -0.00097656 [measured] (base -0.022461 [measured] -> edited -0.023438 [measured])
284
+ ...
285
+ (mdb) set L0.A[h1] = clean:L0.A[h0:2]
286
+ error (refused): clean:t3.L0.A[h=0:2] selects shape [1, 1, 16]; t3.L0.A[h1] selects [1, 1, 8]; select the same block on both sides (the same port kind, heads and row length)
287
+ ```
288
+
289
+ Logit difference (token 6 minus token 7, from the printed values): clean -0.0190, corrupted
290
+ -0.0137, head 1 of L0 patched -0.0225. The patch moves it away from the clean value here; this is
291
+ a random tiny model, so the numbers only show the mechanics. The value of another run can name
292
+ another row or layer (`set L0.m = clean:t3.L1.m`); a missing row is the cursor's row, as for an
293
+ address of this run. Both selections must have the same shape. The edit records where its value
294
+ came from (`origin`: run, address, payload sha256, the clean run's cut) in its manifest, the
295
+ receipt and `info edits`; fetching it leaves the clean run where it was. With a project attached
296
+ the value is stored as a blob with the edited run's recipe, so a pointer to a value read under
297
+ the patch still resolves after the clean run is gone; without one such a pointer is refused and
298
+ says to attach with `project=`. A whole-residual patch reproduces the clean run bit for bit:
299
+ when only the last row differs, `set L1.h = clean:L1.h` gives the clean logits; when an earlier
300
+ row differs, add its cache cells (`set cache.L<l>.k|v[row=0:3] = clean:cache.L<l>.k|v[row=0:3]`
301
+ for every layer), as `tests/test_ops_port_origin.py` checks.
302
+
303
+ ### Prefill split and position patching
304
+
305
+ `start prefill=K` (and `run prefill=K`, `Run(adapter, prompt, prefill=K)`) computes prompt rows
306
+ `0..K-1` in one batched call and steps rows `K..` one row at a time through the same transitions
307
+ a generated row takes, with the prompt's next token forced at `sample` instead of the argmax.
308
+ `prefill=0` steps every row; the default is all rows but the last. A stepped prompt row has
309
+ every port, so `until t1.L0.m`, `print`, `set tR.L.PORT = clean:tR.L.PORT`, `whatif` and
310
+ `compare` work there; on a row that was prefilled they are refused with a message that names
311
+ `start ... prefill=K` for a `K` no larger than the row.
312
+
313
+ The split is part of the procedure: a batched and a stepped row can differ in the
314
+ last bits of their cached K/V (measured on the tiny fp32 Qwen2: logits differ by 3e-8 between
315
+ `prefill=0` and the default; also seen on Qwen2.5-1.5B), so the checkpoint, the replay
316
+ recipe and every restore carry `prefill`; `where` and `info runs` show it when it is not the
317
+ default. A recipe written before the field existed reads as the default split.
318
+
319
+ `sweep PORT [rows=R0:R1] [layers=L0:L1] = ORIGIN --consumer C [top=K]` patches `PORT` from the
320
+ run `ORIGIN` at each (row, layer), runs natively to the consumer (a margin or one logit),
321
+ reads it and moves on; the session is restored once at the end and checked unchanged. The
322
+ result is one record: the layers x rows table of deltas (`measured`), the top cells by |Δ|,
323
+ and the native call counts. A table too large for the record is stored as a sha256-checked
324
+ blob with the top cells kept inline. Cells are visited from the latest layer entry back, each
325
+ from a trail mark below it, so no cell replays from row 0: a cell `(r, l)` with the consumer
326
+ in row `c` of an `L`-layer model costs `(L - l) + L(c - r)` layer calls; the edit is staged
327
+ without a probe and the return to the held trail is a snapshot rollback, which costs none.
328
+ Before running, `sweep` prints its plan (`sweep plan: N cells ..., P layer calls planned`) and
329
+ refuses a plan above 50000 layer calls (about 5 minutes on Qwen2.5-1.5B at 5.2 ms per layer)
330
+ unless `max_calls=N` raises the cap. With a project open the result is also stored as a
331
+ `sweep` record (the table as a checked blob pointer when it is large) and its id is printed.
332
+ In a prompt set, `each SET: sweep h rows=@last = @pair:h --consumer M[$answer,$foil]` takes the
333
+ origin from each item's pair; a pair of another length is a per-item refusal. `each SET
334
+ prefill=@ROLE: ...` (or `prefill=K`) starts every item, and its pair, with that split; `@ROLE`
335
+ binds to the item's own role row, and an item whose prompt is shorter than the split is
336
+ refused. Analysis records (`forecast`, `whatif`, `circuit`, `circuit test`, symbol tables,
337
+ `sweep`) carry the split as `procedure: {prefill, first_row, prompt_rows}`.
338
+
339
+ Tiny Qwen2 (bf16), clean `1 7 9 3 6 2`, corrupted `1 5 9 3 6 2` (row 1 differs), both stepped
340
+ from row 0, real output (`tests/repl_golden/prompt_rows.out`), cut:
341
+
342
+ ```
343
+ (mdb) start name=clean prefill=0 1 7 9 3 6 2
344
+ (mdb) until t5.logits
345
+ (mdb) start prefill=0 1 5 9 3 6 2
346
+ prefill=0: no row batched, rows 0..5 stepped (tokens forced)
347
+ t0.L0.h h = layer input (residual stream) {P01}
348
+ (mdb) until t2.L1.h
349
+ (mdb) print t1.L0.m
350
+ t1.L0.m bfloat16 [1, 1, 16] (batch, row, d_model)
351
+ norm 0.0017112 min -0.0005455 max 0.0007515 mean 0.00010715 abs_max 0.0007515 [measured]
352
+ (mdb) until t5.logits
353
+ (mdb) sweep h = clean --consumer t5.M[4,9]
354
+ sweep plan: 12 cells (6 rows x 2 layers), 78 layer calls planned (base 0, cells 78; cap 50000)
355
+ sweep h = clean:h -> t5.M[4,9] (12 cells; base -0.038208 [measured])
356
+ prefill=0: no row batched, rows 0..5 stepped (tokens forced)
357
+ t0 t1 t2 t3 t4 t5
358
+ L0 0 -8 0 0 0 0
359
+ L1 0 -9 -2 -1 -1 +5
360
+ cell: tenths of max |Δ| 0.014893 [measured] (9 caps); '.' < 1/20, '0' exact
361
+ top |Δ|: t1.L1 -0.014893 [measured], t1.L0 -0.011353 [measured], t5.L1 0.0081177 [measured], t2.L1 -0.0029297 [measured], t4.L1 -0.0020142 [measured], t3.L1 -0.0019531 [measured], t0.L0 0 [measured], t0.L1 0 [measured]
362
+ nulls: 6 cells no effect (1 donor; 0 informative)
363
+ cost: 78 layer calls (planned 78), 34 probes, 174 other transitions [measured] (wall time in the result: cost.seconds)
364
+ session unchanged at t5.logits
365
+ ```
366
+
367
+ Row 0 is the same token in both runs, so its cells are exactly 0; at `L0` only the differing
368
+ row 1 moves the margin (the other rows' layer inputs are the same embeddings). `whatif t1.L1.h
369
+ = clean:t1.L1.h --consumer t5.M[4,9]` measures the same -0.014893 natively, with an exact
370
+ prediction across rows. Patching the whole residual `tR.L2.h` from clean at every stepped row
371
+ of one layer gives the clean logits bit for bit when both runs use the same split
372
+ (`tests/test_engine_prefill.py`). Memory (measured, `Run.held_bytes()` at the last logits of a
373
+ 12-layer tiny Qwen2, 24-token prompt): 31480 bytes in 407 trail marks with every row stepped
374
+ against 19136 bytes in 16 marks with the default split; a sweep leaves it unchanged. Time
375
+ (measured, same model, laptop CPU): a sweep of 4 rows x 12 layers made 1224 layer calls in
376
+ 8.0 s; one row x 12 layers 20 rows before the consumer made 3210 in 18.8 s, so the cost is the
377
+ rows between the cell and the consumer. With the current planner (measured, 12-layer tiny
378
+ Qwen2, 8-token prompts): rows 4:8 x 12 layers 1176 layer calls and 0 run probes, rows 1:8 3570
379
+ and 0; the planned count equals the measured one.
380
+
381
+ A sealed `bound` is the worst-case interval of the dtype's rounding through the chain. Each
382
+ forecast stop between the cursor and the consumer widens it, and each RMSNorm scales an
383
+ interval by about `1/rms` of its input, so on the random tiny models (residual rms near
384
+ 0.016) a bound sealed a few layers before a cross-row consumer reaches 1e4 to 1e5 while the
385
+ native and emulated deltas agree bit for bit. When the bound is at least `|exact|` the line
386
+ says `(worst case, >= |exact|: no sign)`; the record keeps `bound_scope` and
387
+ `wider_than_value`.
388
+
389
+ ## Compared with other tools
390
+
391
+ What each tool is built for, where mdb adds something and where it is weaker. mdb is meant to be
392
+ used beside these tools: `mdb.interop` maps its ports to TransformerLens hooks and nnsight paths and
393
+ imports their values, and examples 02, 03, 06 and 07 hand work between them and mdb.
394
+
395
+ | Tool | What it covers | Where mdb adds | Where mdb is weaker |
396
+ |---|---|---|---|
397
+ | TransformerLens | Hook points and activation caches on its own model classes (and the `TransformerBridge` over Hugging Face models), many model families, batched runs, weight processing for analysis | Stops between native operations inside a layer, `reverse-step` and `restart` from small checkpoints, a sealed prediction checked against the native value, verdicts against a stated floor | Batch 1 only; four families (Qwen2, Qwen3, Llama, Mistral); no weight processing; slower per token |
398
+ | nnsight | Tracing and editing any PyTorch model, batched, with gradients and remote execution | A cursor with breakpoints and watches on named ports; checkpoint, rewind and replay; exact and emulated predictions with the gap split by cause | No gradients of its own (example 03 takes them from nnsight); no remote execution; eager attention only |
399
+ | SAELens | Training, loading and analysing sparse autoencoders, with a registry of pretrained SAEs | At a native value, the exact identity `x = b_dec + sum_f a_f d_f + e` with the error term always listed, and feature edits measured natively (`features`, `feature[ID]*X`) | Does not train SAEs; reads residual SAEs and transcoders from local files only |
400
+ | pyvene | Declarative interventions, interchange interventions and trainable subspace interventions (DAS), batched | One shared floor and built-in nulls for interchange arms (`Branches`), subspaces with provenance (`SubspaceBinding`); in the 64-pair run behind example 06, pyvene and mdb agreed on 63 of 64 flip verdicts (measured on the developers' GPU) | Trains no subspace (DAS bases come from pyvene; its own subspaces are training-free: readout spans, class means); batch 1 |
401
+ | circuit-tracer | Attribution graphs over transcoders, pruning and graph interventions | Measures a graph's edges natively: knock-out, keep-only and full margins (`circuit test`); frozen-attention and frozen-norm arms as holds (example 07) | Builds no attribution graph; its own `circuit` is an exact decomposition of one margin, not a transcoder graph |
402
+
403
+ The authority label on a number says how mdb obtained it (`measured`, `derived-exact`, ...); it
404
+ does not prove the number right. mdb runs one prompt at a time (prompt sets run one run per prompt;
405
+ `mdb.trace` watches a batched forward passively but cannot step or edit), needs eager attention and
406
+ eval mode, and is tested on CPU and CUDA (on MPS `whatif` fails: no float64).
407
+
408
+ ## Embedding
409
+
410
+ The Python [hello world](#hello-world-laptop-cpu-nothing-downloaded) is the embedding API:
411
+ `mdb.open_tiny(family)` builds a tiny random model, `mdb.attach(model, tokenizer)` takes a loaded
412
+ one, `dbg.run(tokens)` starts a run, and every REPL verb is also `dispatch(ctx, verb, args)` with
413
+ `ctx = dbg.ops(run)`, JSON in and out. `attach` refuses a model without eager attention or with modules in
414
+ training mode, and never changes the model. `dbg.repl(run)` opens the REPL on the same run.
415
+
416
+ Loader rule (`mdb.engine.models`): `load_local` passes the dtype to `from_pretrained` and moves
417
+ the module by device only; `cast_weights` (used by `tiny_model`) casts parameters, never buffers.
418
+ `module.to(dtype)` would round RoPE's float32 `inv_freq` to bf16, a different model from the one
419
+ Hugging Face runs (on Qwen2.5-1.5B one margin moved by a bf16 step).
420
+
421
+ The analysis library is `mdb.analysis`, in six sublayers: `numerics`, `predict`, `measure`,
422
+ `circuits`, `symbols`, `features`. 0.3.0 moved its modules there with no aliases, so a 0.2 path
423
+ such as `import mdb.analysis.forecast` fails with `ModuleNotFoundError`; the old to new map is
424
+ in [CHANGELOG.md, 0.3.0, "Changed: module paths"](https://github.com/JHollenb/saturn/blob/main/packages/mdb/CHANGELOG.md#changed-module-paths)
425
+ (`forecast` became `predict.consumers`, `predict.rowmodel`, `predict.verify` and
426
+ `predict.forecast`, `finite` became `numerics.finite`, ...).
427
+
428
+ ## Addresses
429
+
430
+ One string names a value everywhere: on the command line, in records and in the web viewer.
431
+
432
+ ```
433
+ [origin:] t<row>[.s<step>].L<layer>.<port>[selectors][~program] | cache.L<layer>.k|v[selectors]
434
+ ```
435
+
436
+ Selector keys are `h kv i src row d`; `a:b` is a half-open range and `a|b` a set. The stops of
437
+ one token row, in order: `start`, `emb`, `L<i>.<port>` for every layer and port, `fn`,
438
+ `logits`, `sample`. Five addresses:
439
+
440
+ | Address | Meaning |
441
+ |---|---|
442
+ | `L1.p` | port `p` of layer 1, in the cursor's row |
443
+ | `t3.L0.p[h1]` | head 1 of layer 0's attention weights, token row 3 |
444
+ | `cache.L0.k[kv0,row=2]` | key-cache cell of KV head 0 written by row 2, read now (`x cache.L0.k[kv0,row=2] 4`) |
445
+ | `logits` | the logits stop of the cursor's row |
446
+ | `L*.h_out` | a pattern (breakpoints, watches): the output of every layer |
447
+
448
+ An occurrence (`t2.L0.k`, the value written) and a cache cell (`cache.L0.k[row=2]`, read at
449
+ the current clock) are different types. An origin names another run: a live named run, a
450
+ checkpoint or a stored session (`boiling:cache.L0.v[kv0,row=1]`, `boiling:t3.L1.kr[kv0]`).
451
+
452
+ ## State cells and other runs
453
+
454
+ `set cache.L<l>.k|v[selectors] = VALUE [replace|add|scale|mix DOSE]` stages a write into the KV
455
+ cache; `+= -= *= /=` are shorthand for `add` and `scale`. Rows must already be in the cache; the
456
+ row the pending layer writes is refused until the layer commits. The cell is realised before its
457
+ reader (`kr` for keys, `A` for values) unless the cursor has passed that boundary (`kr`, `p`),
458
+ in which case it lands after the read; the reply says which. `mix DOSE` is
459
+ `cell + DOSE * (value - cell)` in float64 from the native bits, rounded once to the cell dtype
460
+ (`mix 1` is the exact copy, `mix 0` leaves the cell).
461
+ `run name=boiling 1 7 9 3` starts a second run (`start` takes `name=` too); `frame boiling:` and
462
+ `frame main:` switch; `info runs` lists them. `ORIGIN:ADDR` takes a value from another run, a
463
+ checkpoint or a stored session of the same model and numeric scope: into a cell, as `v` or `kr`
464
+ occurrences or cache cells (`k`/`kn` occurrences are refused, before RoPE); into a port, as any
465
+ occurrence of the same selected shape (the activation patching example above). `seek b:t3.L1.p`
466
+ makes run `b` current, as `frame b:` does, and moves it there (a run name needs the full
467
+ occurrence, `b:t3.L1.p`, not `b:L1.p`); a target without a row (`seek L20.p`) is on the cursor's row.
468
+
469
+ ```
470
+ (mdb) info runs
471
+ * main t3.L0.h 4 prompt tokens, staged 0
472
+ boiling t3.logits 4 prompt tokens, staged 0
473
+ (mdb) set cache.L0.v[kv0,row=1] = boiling:cache.L0.v[kv0,row=1] mix 0.5
474
+ staged cell cache.L0.v[kv0,row=1]: cache.L0.v mix 0.5 [supplied] tensor [1, 1, 1, 8] bfloat16 ...
475
+ realised before L0.A reads it (boundary L0.p); reads already made are not recomputed
476
+ value from boiling:cache.L0.v[kv0,row=1]
477
+ ```
478
+
479
+ `compare A_ADDR = V B_ADDR = V --consumer M[a,b]` and `whatif ADDR = V [mix D] --consumer ...`
480
+ take cell edits too (`tests/repl_golden/cells_cross_run.out`). Cell edits go into checkpoints,
481
+ restore, reverse and replay. Embedding: `run.set_cell(layer, "v", value, rows=[1], kv=[0])`;
482
+ `dbg.cell_value("boiling:cache.L0.v[kv0,row=1]", run=run)`. Reads of committed layers with no
483
+ edits come from one cached full-layer probe (64 layers kept), not a rebuild per port.
484
+
485
+ ## Glossary
486
+
487
+ In roughly the order you meet them.
488
+
489
+ - **Port**: a named value inside one decoder layer, in native execution order (`h`, `a`, `q`, ...,
490
+ `m`, `h_out`); see [Ports](#ports). **Address**: the string that names a value
491
+ (`t3.L1.p[h0]`: row 3, layer 1, port `p`, head 0); see [Addresses](#addresses). **Row**: a
492
+ token position (`t3`).
493
+ - **Run**: one prompt being debugged, with a cursor at one stop. **Stop**: a place the cursor can
494
+ be (`start`, `emb`, every port of every layer, `fn`, `logits`, `sample`).
495
+ - **Staged edit**: an edit (`set`) waiting at a port of the **pending layer**, the layer the cursor
496
+ is in; it fires when native code computes that port. **Commit** (`commit`, or moving past the
497
+ layer) runs the rest of the layer with its staged edits; `abort` drops them.
498
+ - **Checkpoint**: a named cursor position with its edits, about 1 KB of plain data; `restart`
499
+ returns to it. **Trail mark**: the state the run keeps after each step, so it can step backwards
500
+ without recomputing from row 0.
501
+ - **Cell**: a KV-cache entry, `cache.L<l>.k|v[kv<g>,row=r]`: what later rows read from row `r`.
502
+ Cells can be read, edited and taken from another run like ports.
503
+ - **Consumer**: the value an edit or prediction is judged on, usually a **margin**
504
+ `M[a,b] = logit[a] - logit[b]` at a row's logits (one logit `logits[i]` or a port also works).
505
+ - **Spacing**: the gap between adjacent values of a dtype at a magnitude (bf16 near 20: 0.125).
506
+ **Floor**: the smallest change mdb treats as real, in spacings; see
507
+ [Two floors](#two-floors).
508
+ - **Exact chain**: the float64 recomputation of the port program from captured operands
509
+ (`derived-exact`). **Emulated chain**: the same steps with the run's dtype rounding where eager
510
+ Hugging Face rounds, using the backend's own kernels; it predicts the native bits.
511
+ - **Verdict**: the word a check ends in: `confirmed` / `not confirmed` / `unresolved` for
512
+ `verify`, `effect` / `no effect` / `unresolved` for `whatif` and `reads`. It is decided on
513
+ native against emulated within the floor; see [Verdicts](#verdicts).
514
+ - **Authority label**: how a number was obtained: `measured`, `derived-exact`, `derived-local`,
515
+ `bound`, `supplied`; see [Authority labels](#authority-labels).
516
+ - **Record**: a JSON result with a content-addressed id (the sha256 of its stored form), at
517
+ most 1 MiB, every number labelled; a table of numbers with one label is a column (`nums`).
518
+ Format, bounds and migrating records of mdb 0.2.1 and earlier: [docs/RECORDS.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/RECORDS.md). **Sealed**: written as a record before the native value it
519
+ predicts exists (`forecast`, `whatif`), so the prediction cannot be adjusted afterwards.
520
+ - **Branch** (`dbg.branches`): named arms (edits) run from one checkpoint against one shared floor,
521
+ with built-in null arms. **Pool** (`dbg.pool`): a sealed set of donor values over prompts, with a
522
+ leave-one-out mean. **Hold** (`run.hold`): keep a port (attention weights, a norm scale, a cell)
523
+ at a reference run's values while the run continues.
524
+ - **Custody** (`dbg.custody`): the script, preregistration and library versions stamped into every
525
+ record sealed afterwards; a **sink** (`dbg.records_to`) writes those records to a file.
526
+ **Checkpoint** (`run.dump`, `dbg.checkpoint`): a run's state at any cut, a row in flight
527
+ included, saved once as content-addressed tensors and rehydrated as a steppable run with no
528
+ prefix recompute (the older name for the file form is core file).
529
+ - **Binding**: a named part of a value (a symbol, an SAE component). A **subspace binding**
530
+ (`SubspaceBinding`) names a `k`-dimensional subspace of one cell by an orthonormal basis and
531
+ says where the basis came from.
532
+ - **Carrier** (used in the examples): the cell that carries an entity to the answer row, chosen as
533
+ the span row the answer row's reader heads attend to most at the carrier layer (the
534
+ `R_argmax` rule); the **carrier cell** is its value cell `cache.L<l>.v[kv<g>,row=carrier]`.
535
+ - **Proof IDs** (`P01` to `P33`): the mathematical identities a port or a number relies on; see
536
+ [docs/PROOF-IDS.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/PROOF-IDS.md).
537
+
538
+ ## Ports
539
+
540
+ One line per port, in native execution order, generated from the port program
541
+ (`mdb.engine.ports.program_for`); `info ports` and `list` print the same. The tables here are kept by hand. The Proofs
542
+ column names the identities each operator relies on ([docs/PROOF-IDS.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/PROOF-IDS.md)). On Qwen3, `qr` and `kr` take `qn` and `kn`. Llama and Mistral have the Qwen2 list (`info program` on `tiny:llama`: `h a q k v qr kr s p A o r n g sg u f m h_out`); a projection without bias contributes no bias term, and a config outside a family's premises (a non-silu activation, Llama `mlp_bias`) is refused by `attach`, `trace` and `program_for`. The families come from one table, `mdb.engine.ports.FAMILIES`. RoPE runs inside the native attention. Llama accepts default and `llama3`-scaled RoPE (Llama-3.x); the other families accept default RoPE only, and other scaled types are refused at `attach`. `explain` and `forecast` model the llama3 frequencies too.
543
+ | Port | Read at | Operator | Proofs |
544
+ |---|---|---|---|
545
+ | `h` | decoder layer input | h = layer input (residual stream) | P01 |
546
+ | `a` | `input_layernorm` output | a = RMSNorm(h) * w_in | P02 P03 |
547
+ | `q` | `self_attn.q_proj` output | q = W_q a + b_q (pre-RoPE, flat) | P04 |
548
+ | `qn` (Qwen3) | `self_attn.q_norm` output | qn = RMSNorm_head(q) * w_q (per head, pre-RoPE) | P02 P04 |
549
+ | `k` | `self_attn.k_proj` output | k = W_k a + b_k (pre-RoPE, flat) | P04 |
550
+ | `kn` (Qwen3) | `self_attn.k_norm` output | kn = RMSNorm_head(k) * w_k (per kv head, pre-RoPE) | P02 P04 |
551
+ | `v` | `self_attn.v_proj` output | v = W_v a + b_v (flat) | P04 |
552
+ | `qr` | eager attention argument | qr = RoPE(q) (query argument of eager attention) | P04 |
553
+ | `kr` | eager attention argument | kr = [cache; RoPE(k)] (key argument of eager attention, cached rows included) | P04 |
554
+ | `s` | replica from `qr`, `kr` and the mask | s = scaling * qr repeat_kv(kr)^T + mask (replica of the native expression) | P05 P07 P08 P09 |
555
+ | `p` | eager attention weights | p = softmax(s, float32).to(dtype) (native attention weights) | P05 P06 P07 P08 P09 |
556
+ | `A` | `self_attn.o_proj` input | A = concat_heads(p repeat_kv([cache; v])) (o_proj input) | P06 P07 |
557
+ | `o` | `self_attn.o_proj` output | o = W_o A | P06 P07 |
558
+ | `r` | `post_attention_layernorm` input | r = h + o | P06 P07 P14 |
559
+ | `n` | `mlp` input | n = RMSNorm(r) * w_post (mlp input) | P02 P03 |
560
+ | `g` | `mlp.gate_proj` output | g = W_gate n | P10 P15 |
561
+ | `sg` | `mlp.act_fn` output | sg = silu(g) | P10 P15 |
562
+ | `u` | `mlp.up_proj` output | u = W_up n | P10 P15 |
563
+ | `f` | `mlp.down_proj` input | f = sg * u (down_proj input) | P10 P15 |
564
+ | `m` | `mlp.down_proj` output | m = W_down f | P14 |
565
+ | `h_out` | decoder layer output | h_out = r + m (layer output) | P14 |
566
+
567
+ `kr` is the only port that cannot be edited (it holds cached rows). `s` is not a native
568
+ intermediate: it is a replica of the native expression, checked against `p` bit for bit.
569
+
570
+ ## Verbs
571
+
572
+ Taken from the op registry (`mdb.ops.registry()`), by hand; `info` or the registry is the
573
+ authority if they differ. The REPL, `--json` mode, the server's `POST /api/v1/s/SID/op` and
574
+ `dispatch` all go through it.
575
+ | Verb | Usage | Effect | What it does |
576
+ |---|---|---|---|
577
+ | `abort` | `abort` | mutate | Drop the staged edits of the pending layer (and the staged cell edits) |
578
+ | `advance` | `advance ADDR [budget=ROWS]` | navigate | Run to an address, stopping earlier at an armed breakpoint or watch |
579
+ | `backtrace` | `backtrace [ADDR]` | read | Producer chain from the focus port back to the layer input |
580
+ | `break` | `break PATTERN [if CONDITION]` | mutate | Set a breakpoint on an address pattern (L*.p, t5.L1.o, logits, cache.L0.v[row=2]); cache cells are evaluated at boundary stops only |
581
+ | `candidates` | `candidates NAME = FILE\|W1,W2,...\|#ID,... [rule=first\|single] [paired=SET] \| candidates show\|delete NAME \| candidates list` | mutate | Declare a candidate set for content readouts (`symbols sets=`): token pieces, first-subword and collision flags, sha256 provenance |
582
+ | `checkpoint` | `checkpoint [NAME]` | mutate | Name the cursor position (about 1 KB of plain data) |
583
+ | `checkpoints` | `checkpoints [offset=N] [limit=N]` | read | List named checkpoints (paged: offset=, limit=) |
584
+ | `circuit` | `circuit CONSUMER [top=K] [depth=D] \| circuit test ID ref=NAME\|set:NAME \| circuit show ID [node=NODEID]` | mutate | Circuit records: build from the exact decomposition (nodes, edges, remainder), test by native patching from a reference run (knock-out and keep-only margins, two measured ratios; a `circuit-test` record), show as a walk (`node=` opens one stored page of a circuit that did not fit one record) |
585
+ | `commit` | `commit` | mutate | Commit the pending layer with its staged edits (cursor to its h_out) |
586
+ | `compare` | `compare A B [consumer=C] [path=true] (A, B: ADDR=VALUE [op] or a checkpoint name)` | navigate | Compare branches: base, A, B and A+B measured natively, effects and the interaction |
587
+ | `condition` | `condition N [EXPR]` | mutate | Set the condition of breakpoint N (a watch's predicate); no expression removes it |
588
+ | `continue` | `continue [N] [budget=ROWS]` | navigate | Run to the next armed breakpoint or watch hit (N: ignore the breakpoint stopped at N-1 more times, as gdb) |
589
+ | `delete` | `delete [ID ...]` | mutate | Delete breakpoints and watches (all when no ids are given) |
590
+ | `disable` | `disable [ID ...]` | mutate | Disable breakpoints and watches without deleting them (all when no ids) |
591
+ | `display` | `display [ADDR]` | mutate | Show an address after every stop (no address: list displays) |
592
+ | `down` | `down [N]` | navigate | Move the focus back toward its consumer, N times |
593
+ | `each` | `each SET [at=ADDR] [prefill=K\|@ROLE] [shard=K/N] [keep]: OP LINE [; OP LINE ...]` | native | Run one op line on every prompt of a set (one run per prompt): one result per prompt and a summary (n, mean, min, max, sign agreement, verdict counts) |
594
+ | `enable` | `enable [ID ...]` | mutate | Enable breakpoints and watches (all when no ids are given) |
595
+ | `explain` | `explain M[a,b]\|ADDR [units=K]` | read | Exact accounting of a margin M[a,b] or of one port, with proof IDs and the measured remainder (cursor at the row's logits/sample) |
596
+ | `export` | `export NAME to=DIR` | mutate | Write a durable checkpoint and the records that reference it to a new directory another project imports (start from=DIR) |
597
+ | `feature` | `feature ID layer=L [sae=NAME] [top=K]` | read | Life of one SAE feature along the cursor's row: its encoder probe at every residual port (h, r, h_out), where it first crosses the site's top-k threshold, and which attention/MLP (heads, neurons) write it |
598
+ | `features` | `features ADDR [top=K] [sae=NAME] [consumer=M[a,b]] [lens=N] [circuit=true] [match=UNIT] \| features L*.h_out consumer=M[a,b]` | navigate | SAE features at a residual port with the error row; with a consumer, each feature's, the bias's and the error's exact direct effect and the closure (L*.h_out: per-layer profile of what the SAE drops) |
599
+ | `feed` | `feed ID [ID ...]` | navigate | Forced tokens: run each row to sample with the given id in place of the greedy argmax, commit it, and stop at the next row's start |
600
+ | `finish` | `finish` | navigate | From a port inside a layer: run to that layer's h_out. From h_out or a token-level stop: run to this row's sample |
601
+ | `forecast` | `forecast [ADDR\|M[a,b]]` | mutate | Seal a prediction of the next stop (or a later stop of this row, or a margin M[a,b]) from values at the cursor, before native code runs |
602
+ | `frame` | `frame [ADDR \| cursor \| NAME:]` | navigate | Show or set the focus address (print/list/backtrace default to it); NAME: switches to the named run |
603
+ | `ignore` | `ignore N COUNT` | mutate | Ignore the next COUNT hits of breakpoint N (they are counted, not reported) |
604
+ | `info` | `info ports\|breakpoints\|watch\|display\|checkpoints\|edits\|program\|runs [offset=N] [limit=N]` | read | Show debugger tables or the program (lists are paged: offset=, limit=) |
605
+ | `list` | `list [LAYER]` | read | The layer's port program: operator text, proof IDs, cursor marked |
606
+ | `next` | `next [N]` | navigate | Step to the last port of the sublayer (r, then h_out) |
607
+ | `print` | `print [ADDR] [top=K] [slice=N]` | read | Reduce a value: shape, dtype, stats, top-k by \|value\| (logits: by value, `top:`), pointer; `print M[a,b]` (also `x`, `display`) is the measured logit difference, refused before the logits stop |
608
+ | `promptset` | `set load NAME FILE \| set define NAME ITEMS \| set show NAME \| promptset list \| promptset result ID [ITEM]` | mutate | Prompt sets: load a JSONL file (not from the web), define a set inline, show or list sets, read a stored each result (the REPL's set load / set show) |
609
+ | `reads` | `reads SOURCE [rows=R\|A:B\|all] [consumer=C] [top=K] [causal=false]` | navigate | Who reads a value: attention reads of a source row with mass, exact contribution and a native causal verdict |
610
+ | `restart` | `restart NAME` | navigate | Return to a named checkpoint (rewinds or replays) |
611
+ | `reverse-continue` | `reverse-continue` | navigate | Run backwards to the previous breakpoint or watch hit |
612
+ | `reverse-finish` | `reverse-finish` | navigate | Step back to the boundary before the pending layer (its input) |
613
+ | `reverse-next` | `reverse-next [N]` | navigate | Step back to the previous sublayer end |
614
+ | `reverse-step` | `reverse-step [N] [unit] [budget=ROWS]` | navigate | Step back one port (or N units; layer/token units enter at most `budget` rows) |
615
+ | `run` | `run [name=NAME] [prefill=K] [lookahead=MODE] [retain_rows=N] [TEXT \| ID ID ...] [budget=N]` | native | Like start, then continue to the first armed breakpoint or watch |
616
+ | `seek` | `seek ADDR \| seek ORIGIN:ADDR \| seek POINTER-JSON` | navigate | Move the session to an occurrence: forward, backward, or by replaying a stored recipe (ORIGIN:ADDR or an occurrence pointer) |
617
+ | `sae` | `sae load NAME [PATH] [layers=A:B] [k=K] [cache=N] [verify=true] \| sae list \| sae drop NAME` | mutate | Load, list or drop SAE feature bases (per-layer residual SAEs) |
618
+ | `set` | `set ADDR = VALUE\|ADDR\|ORIGIN:ADDR [replace\|add\|scale\|mix DOSE]` | mutate | Stage an edit at a port of the pending layer, or of a state cell (cache.L<i>.k\|v[kv,row,d]): set ADDR = VALUE [op] |
619
+ | `start` | `start [name=NAME] [prefill=K] [lookahead=none\|layer\|auto] [retain_rows=N] [TEXT \| ID ID ...] \| start from=ID\|PATH [name=NAME] [verify=true\|report] [lookahead=MODE]` | native | Prefill a prompt and stop at the first stepped row's first port (L0.h), or start from a checkpoint (from=ID\|PATH) at its cursor |
620
+ | `step` | `step [N] [port\|sublayer\|layer\|token] [budget=ROWS]` | navigate | Step one port (or N units; layer/token units enter at most `budget` rows) |
621
+ | `sweep` | `sweep PORT [rows=R0:R1] [layers=L0:L1] = ORIGIN --consumer C [top=K] [max_calls=N] [path=true]` | navigate | Patch PORT from another run at every (row, layer) of a range, measure the consumer natively for each, restore: one table of deltas (activation patching) |
622
+ | `symbol` | `symbol NAME = ADDR[,ADDR...] \| symbol NAME = whatif\|compare.a\|compare.b\|EACH:ITEM [role=R] [readers=K] [causal=false] \| symbol show\|delete NAME` | mutate | Declare a user symbol over cache rows, or a named symbol from a transplant result (role, source row, readers, measured effect), usable as an address |
623
+ | `symbols` | `symbols [consumer=C] [rows=R\|A:B\|all] [min_mass=X] [offset=N] [limit=N] [...]` (further options: [docs/SYMBOL-TABLE-SCHEMA.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/SYMBOL-TABLE-SCHEMA.md)) | mutate | Symbol table at the cursor: bindings with definition sites, lifetimes, readers, status and an Unbound row (stored as records with a project) |
624
+ | `tbreak` | `tbreak PATTERN [if CONDITION]` | mutate | Set a breakpoint that deletes itself after its first hit |
625
+ | `undisplay` | `undisplay [ID ...]` | mutate | Remove displays (all when no ids are given) |
626
+ | `until` | `until ADDR [budget=ROWS]` | navigate | Run to an address, stopping earlier at an armed breakpoint or watch |
627
+ | `up` | `up [N] [PORT]` | navigate | Move the focus to a producer (toward the layer input), N times; `up PORT` picks the producer by name, the result lists the alternatives |
628
+ | `verify` | `verify [ID ...]` | mutate | Compare open forecasts whose target the cursor has passed with the native values: native against the emulated prediction in dtype spacings, `confirmed` / `not confirmed` / `unresolved`, the rounding effect against exact, and the order proof; floor 1 dtype spacing |
629
+ | `watch` | `watch ADDR [change\|level\|edge] [if PREDICATE]` | mutate | Watch an address: stop when it changes (or a predicate holds: level/edge); cache cells (cache.L<i>.k\|v) are evaluated at boundary stops only |
630
+ | `whatif` | `whatif ADDR = VALUE [replace\|add\|scale\|mix DOSE] --consumer M[a,b]\|logits[i]\|ADDR [path=true] \| whatif ADDR donors=RUN,...\|PATTERN --consumer C [path=true]` | navigate | Predicted, then natively measured change of a consumer under one edit; the session is left exactly where it was |
631
+ | `where` | `where` | read | Show the cursor, its operator and the context tokens |
632
+ | `x` | `x [ADDR] [COUNT] [OFFSET]` | read | Examine raw values: a bounded slice of the selected, flattened value |
633
+
634
+ There is no `why` verb. To ask why an output came out as it did, start with `explain M[a,b]` at
635
+ the logits (the margin split exactly into its contributions), then `backtrace` (the producer
636
+ chain of a port), `reads SOURCE --consumer C` (the attention reads that carry a row into the
637
+ consumer) or `circuit C`.
638
+
639
+ The REPL's own commands, outside the registry: `help [VERB]` (list commands or describe one),
640
+ `source [-k] FILE` (run commands from a file; stops at the first error unless `-k`; nests at
641
+ most 16 deep), `record [append] FILE|stop` (write the executed commands to FILE; an existing file
642
+ is refused unless `append`; mode 0600; interactive only, refused inside `--script`, an init file
643
+ or `source`) and `quit`. Aliases: `s` step,
644
+ `n` next, `c` continue, `b` break, `p` print, `bt` backtrace, `u` until, `d` delete, `i` info,
645
+ `l` list, `r` run, `q`/`exit` quit, `h` help, `rs`/`rn`/`rc` reverse-step/-next/-continue. A
646
+ unique prefix resolves (`fin` is `finish`), and an empty line repeats the last motion command
647
+ (interactive only).
648
+
649
+ ## Authority labels
650
+
651
+ Every number shown or stored carries exactly one label, and a state.
652
+
653
+ | Label | Meaning | Example |
654
+ |---|---|---|
655
+ | `measured` | read from native execution | `print top=2` at `t3.L1.p` |
656
+ | `derived-exact` | an exact identity on captured operands | the replica `s`; a value written by an `add` or `scale` edit |
657
+ | `derived-local` | a linearisation or quadrature only | the linear term of `whatif` |
658
+ | `bound` | a theorem with stated premises | the rounding bound of a `forecast`; never decides a verdict |
659
+ | `supplied` | a value handed in by a user or a stored record | the edit request `m scale 0` |
660
+
661
+ State is `resolved`, `unresolved` (could not be computed: never shown as zero) or `refused`
662
+ (a premise failed: the label is empty and a reason is given). A value downstream of an edit
663
+ stays `measured` and lists the edits above it (`[measured, under edit t3.L1.m]`).
664
+
665
+ ## Passive capture: `mdb.trace`
666
+
667
+ `attach` drives the model. `trace` only watches a forward your experiment already runs (any
668
+ batch size, sdpa, `generate`, gradients on), with hooks at the stepper's sites, so a port name
669
+ means the same in both.
670
+
671
+ ```python
672
+ import torch, mdb
673
+
674
+ model = mdb.open_tiny("qwen2").model # any loaded Qwen2/Qwen3/Llama/Mistral causal LM
675
+ batch = torch.tensor([[1, 5, 9, 3], [2, 6, 10, 4]])
676
+ with mdb.trace(model, ports=["L1.p", "L1.s", "L1.m", "L0.h"]) as t, torch.no_grad():
677
+ model(batch) # the experiment's own forward
678
+ print(t.calls, tuple(t["L1.m"].shape), tuple(t["L1.p"].shape))
679
+ print({k: t.info("L1.s")[k] for k in ("state", "authority", "kind", "replica_equal")})
680
+ ```
681
+
682
+ ```
683
+ 1 (2, 4, 16) (2, 2, 4, 4)
684
+ {'state': 'resolved', 'authority': 'derived-exact', 'kind': 'replica', 'replica_equal': True}
685
+ ```
686
+
687
+ - Passive: logits are bitwise equal with and without the trace (tested for qwen2 and qwen3,
688
+ bf16 and fp32, eager and sdpa). On the stepper's native call every port is bitwise equal to
689
+ `Run.read` (tested).
690
+ - One call is one outermost forward of `model.model`; with several use `t["L1.m", i]`. Values
691
+ keep the batch dimension; the axes are in `t.info(address)["axes"]`.
692
+ - Refused, never wrong: `qr`, `kr`, `s`, `p` without eager attention (the reason is in
693
+ `t.info(address)["reason"]`) or under attention dropout; ports of a layer that did not run;
694
+ anything after the `max_bytes` cap (default 1 GiB).
695
+ - Hooks are removed when the block exits, also on error. A second active trace is refused.
696
+ `project=` is not supported yet.
697
+
698
+ ## Predictions: `forecast`, `verify`, `whatif`
699
+
700
+ `forecast` seals two predictions from values at the cursor, before native code runs, and
701
+ `verify` compares them with what native code then produced
702
+ (`tests/repl_golden/predict_forecast.out`):
703
+
704
+ - `exact`: the float64 chain of the port program's identities (`derived-exact`, real
705
+ arithmetic on the captured operands), with its per-element worst-case rounding `bound`;
706
+ - `emulated`: the same chain with the run's dtype rounding at every point where eager HF
707
+ rounds, each step run as eager HF writes it with the backend's own kernels at the native
708
+ call's batch-1 shapes (`derived-exact` under the premise "rounding points of eager HF
709
+ attention/MLP on this backend"; the premise list is in the record, `emulated.premises`).
710
+
711
+ Both sha256s are sealed (`digests`). The verdict is decided on native - emulated: `confirmed`
712
+ when every element is within the floor, `1 x spacing` (`supplied`), `spacing` being the dtype's
713
+ gap at the consumer's magnitude (a margin, a difference of two rounded logits: the sum of their
714
+ two spacings). The floor does not widen with depth. Measured: emulated equals native bit for bit
715
+ at every stop from the sealing stop to the logits on tiny Qwen2/Qwen3/Llama/Mistral (BF16 and
716
+ FP32, 2 to 28 layers) and, on the developers' GPU, on Qwen2.5-1.5B (CUDA, BF16 28 layers and an
717
+ FP32 2-layer cut, 3 prompts; see [Measured on a real model](#measured-on-a-real-model)). Above the floor `verify` says where emulation and native part: `not confirmed` when the
718
+ prediction is not the emulated chain of the sealed operands (an operand or the held prediction
719
+ differs from its sealed digest) or when a stage from that stop to the target does not reproduce
720
+ its native value from its native operands within the worst-case bound of its identity;
721
+ otherwise `unresolved` (rounding drift between stages, each stage being the native step), with
722
+ the parting stop and any native top-score tie the emulated softmax splits differently.
723
+ `rounding_effect` is native - exact (`measured`), and the sealed `rounding_origin` names the
724
+ first stop where exact and emulated part by more than a spacing; on Qwen2.5-1.5B BF16 (developers' GPU) that is
725
+ an L0 score (`t22.L0.s[h3]: score spacing 64 at |s| 1.51e+04`), and the exact chain is 35 to 78
726
+ spacings off at L0.m because rounded scores tie and the native softmax is not the softmax of the
727
+ real scores. The worst-case bound against `exact` is printed only when finite
728
+ (information).
729
+
730
+ Staged edits: by default a staged port edit between the cursor and the target refuses
731
+ the seal. `forecast.seal(run, target, staged="include")` applies the staged port edits of the
732
+ pending layer in both chains where they compute the edited stop (exact: the real-number edit
733
+ with the bound of its native write; emulated: the engine's own `PortEdit` on the dtype value), so
734
+ a forecast sealed before the edited layer computes covers the edit's own layer: a repair
735
+ forecast, not a fidelity check sealed after the edit. Staged cache-cell edits (`set_cell`) are
736
+ in the operands in either mode (the chain's cache reads see them). The record's `staged` block
737
+ names the mode, every staged edit included and their sha256, and `verify` decides a target an
738
+ included edit wrote (`staged_included`) instead of reporting it `edited`. Measured on the tiny
739
+ models (8 configs): `v`/`r`/`m`/`s` port edits at L1 and a cell edit at L1, sealed at the layer's
740
+ `h` or earlier, `confirmed` at M[5,9] (`tests/test_analysis_forecast.py`); residual 0 spacings
741
+ on tiny Qwen3 bf16/fp32 and Qwen2 bf16.
742
+
743
+ ```
744
+ (mdb) forecast L0.p
745
+ forecast 1 t3.L0.p sealed at t3.L0.h record 36d989749411e1ff
746
+ method 7 identities t3.L0.a .. t3.L0.p (last softmax P05); chain not stored (no project)
747
+ predicted exact max_abs 0.25152 [derived-exact] norm 0.70712 [derived-exact] sha256 a8cee3618668d88c emulated max_abs 0.25195 [derived-exact] norm 0.70781 [derived-exact] sha256 936e3888bea07b92
748
+ worst-case rounding interval 0.0026798 [bound] per element (information, not the verdict)
749
+ (mdb) forecast M[4,9]
750
+ forecast 2 t3.M[4,9] sealed at t3.L0.h record ddaab8bf58c63a20
751
+ method 39 identities t3.L0.a .. t3.logits (last readout_logits P19); chain not stored (no project)
752
+ predicted exact -0.11452 [derived-exact P19] emulated -0.11401 [derived-exact P19]
753
+ worst-case rounding interval not informative from t3.L0.m (interval 0.00118 >= |x| 0.000373); at the consumer t3.logits the bound is 16.8 >= |value| 0.115
754
+ (mdb) until t3.logits
755
+ t3.logits logits = lm_head(fn)
756
+ (mdb) verify
757
+ forecast 1 t3.L0.p: confirmed native max_abs 0.25195 [measured] norm 0.70781 [measured] residual vs emulated 0 [measured] = 0 spacings <= floor 0.0019531 [supplied P20] = 1 bfloat16 spacing (supplied) [P20, resolved]
758
+ rounding effect native - exact 0.00091062 [measured] = 0.466 spacings; worst-case bound 0.0026798 [bound] (holds, information)
759
+ stages [per-stage bound, not a chain bound]: each stage within its own rounding bound on native operands: 7/7 (worst |native - identity|/bound 0.926 at t3.L0.p)
760
+ rounding origin (sealed): exact and emulated agree within one spacing at every stop of the chain
761
+ order: sealed at t3.L0.h (stop 2) before the target (stop 10); cut descends through 4 receipts
762
+ forecast 2 t3.M[4,9]: confirmed native -0.11401 [measured] residual vs emulated 0 [measured] = 0 spacings <= floor 0.00073242 [supplied P20] = 1 bfloat16 spacing (supplied) [P20, resolved]
763
+ rounding effect native - exact 0.00050802 [measured] = 0.694 spacings; worst-case rounding interval not informative from t3.L0.m (interval 0.00118 >= |x| 0.000373); at the consumer t3.logits the bound is 16.8 >= |value| 0.115
764
+ stages [per-stage bound, not a chain bound]: each stage within its own rounding bound on native operands: 39/39 (worst |native - identity|/bound 0.946 at t3.L0.sg)
765
+ rounding origin (sealed): t3.L0.f: exact and emulated part by 1.83 spacings at |x| 0.00723
766
+ order: sealed at t3.L0.h (stop 2) before the target (stop 41); cut descends through 4 receipts
767
+ ```
768
+
769
+ `whatif` seals the predicted change of a consumer under one edit, measures it natively on a
770
+ private branch, and restores the session (`tests/repl_golden/predict_whatif.out`):
771
+
772
+ ```
773
+ (mdb) whatif L1.m = 0.5 add --consumer M[4,9]
774
+ whatif t3.L1.m add 0.5 [supplied] -> t3.M[4,9] (mode pending, record fd311c6679a8ad15)
775
+ sealed linear ΔM = 1.4572 [derived-local P14] exact ΔM = 0.16513 [derived-exact] bound 0.07029 [bound] (operands forecast from t3.L1.a) emulated ΔM = 0.16449 [derived-exact]
776
+ native ΔM = 0.16449 [measured] (base -0.11401 [measured] -> edited 0.050476 [measured])
777
+ error split (P20): linear 1.4572 [derived-local P14] + nonlinear -1.2921 [derived-exact P20] + operands 4.2358e-05 [derived-exact P20] + realisation -4.5182e-05 [derived-exact P20] + rounding effect -0.00063376 [derived-exact P20] (within bound 0.01905 [bound]) + residual 0 [measured P20]
778
+ verdict (P20): effect native ΔM 0.16449 [measured P20] = 3.4e+02 spacings, emulated ΔM 0.16449 [derived-exact P20], residual 0 [measured P20] = 0 spacings; exact ΔM (written value, measured operands) 0.16512 [derived-exact P20]; floor 0.00048828 [supplied P20] = 1 bfloat16 spacing (supplied)
779
+ edited run stages [per-stage bound, not a chain bound]: each stage within its own rounding bound on native operands: 18/18 (worst |native - identity|/bound 0.885 at t3.L1.sg); 1 not checked
780
+ base run stages [per-stage bound, not a chain bound]: each stage within its own rounding bound on native operands: 19/19 (worst |native - identity|/bound 0.885 at t3.L1.sg)
781
+ session unchanged at t3.L1.a (5 moves, restored)
782
+ ```
783
+
784
+ The exact change is `F(x1) - F(x0)` (P09): the base and the edited chains hold the
785
+ edited port at its value `x0` or write the edit there, and recompute the same stops (those the
786
+ edit reaches) in float64 from the same operands; the base is never the native value, which
787
+ would put the base run's rounding into the exact change (with a no-op edit `L1.m *= 1` the
788
+ exact change is 0, at any cursor). The sealed value uses the operands at the cursor. When the
789
+ consumer is ahead of the cursor, the stops past it exist only as the chain's own float64 values,
790
+ and the sealed line says `(operands forecast from t3.L1.a)` (`prediction.exact.operands` in the
791
+ result; the label stays `derived-exact`: an exact identity on the operands captured at the
792
+ cursor, not a linearisation). After the native run the chain is evaluated again at the consumer
793
+ on the measured operands of the unedited run (`exact` in the result, `requested` and `written`;
794
+ computed after the seal and never shown as sealed); the split gains `operands` (that value minus
795
+ the sealed one) and `realisation` is taken on the measured operands. That exact number is the
796
+ same wherever the cursor was (tested at three cursors for a port, a head-selected and a cross-run
797
+ edit, to `spacing / 2^20`). Beside the exact change the seal holds the emulated one (`emulated`:
798
+ the forecast's `EmulatedRowModel` chains, the dtype's rounding where eager HF rounds, the edit
799
+ written by the engine's own arithmetic), which predicts the native change itself: the split ends
800
+ in `rounding effect` (emulated - exact, `derived-exact` under the emulation premises) and
801
+ `residual` (native - emulated, `measured`), and the verdict holds native against emulated.
802
+ Measured on the tiny models: the residual is 0 bit for bit for port, cross-run, head-selected and
803
+ cache-cell edits at cursors ahead of the edit, between edit and consumer and past the consumer,
804
+ and on a model whose rounded L0 scores tie (where exact is tens of spacings off).
805
+
806
+ ### Verdicts
807
+
808
+ `whatif` and `reads` judge an effect from the P20 accounting (`mdb.analysis.numerics.verdict`):
809
+ native
810
+ change = exact change (float64 chain on the measured operands, written value) + rounding effect
811
+ (emulated - exact, both `derived-exact`) + residual (native - emulated, `measured`). The floor is
812
+ one spacing of the consumer's dtype at its magnitude (`supplied`, `FLOOR_SPACINGS = 1`, the same
813
+ constant `verify` uses). The rule, on the native and emulated changes:
814
+
815
+ - `effect`: native and emulated agree within the floor and the native change is not zero at the
816
+ dtype's resolution. When the exact change is 0 or has the other sign, a note says the native
817
+ change is the dtype's rounding.
818
+ - `no effect`: they agree and the native change is zero: the dtype cannot show the change. The
819
+ note gives the exact change the dtype cannot show (`no change at bfloat16 resolution (spacing
820
+ 0.125); exact Δ 0.33, which the dtype cannot show`); `reads` prints this as `not causal at this
821
+ dose` with that note as its reason.
822
+ - beyond the floor, `verify`'s rule: `not confirmed` when a stage of the edited or the base run
823
+ lies outside the bound of its identity on its native operands (the stop named), else
824
+ `unresolved` (rounding drift; a chain over several rows is not stage-checked and says so).
825
+
826
+ The exact change is reported beside the verdict and never decides it. With no emulated change
827
+ (the emulated chains refused, e.g. a staged edit ahead of the cursor, or `compare`, which has no
828
+ chain) the verdict is native only: `effect` when the native edited and base values differ, else
829
+ `no effect`, and the line says so. Worst-case rounding bounds are still shown where they are
830
+ finite (`bound` label) and never decide a verdict. `verify` holds native against the emulated
831
+ prediction the same way: `confirmed` within one spacing, else `not confirmed` or `unresolved` by
832
+ where emulation and native part.
833
+
834
+ ### Donor counts, path-diverged, gate-side units
835
+
836
+ Three lessons from the binary ground-truth experiment (2026-11-16), where an exact answer key
837
+ exists:
838
+
839
+ - **Every null names its donors** (`mdb.analysis.measure.donors`). On the binaries one resample
840
+ donor said "no effect" wrongly on 41-71% of live cells, almost always because the donor carried
841
+ the base's own value. Every verdict carries `donors = {n, informative}` (informative: the patched
842
+ value differs bitwise from the base's) and a `label`: `no effect (1 donor)`, `no effect (1
843
+ donor, not informative: the donor value equals the base)`, `no effect (16 donors, 12
844
+ informative)`. Multi-donor mode: `donors.whatif(run, ADDR, values, consumer)` (values from
845
+ `Pool.donors(item, n, seed=)` or `Run.ref`), `donors.compare`, `liveness(..., donors=[runs])`
846
+ (resample instead of zero), `reads(..., donors=[runs])` (the donor's `p` weight instead of
847
+ 0), `sweep PORT = A,B,C` (one sweep per origin; per cell `n_effect` / `n_informative` and
848
+ the single-origin nulls another origin overturns) and, in the REPL, `whatif ADDR
849
+ donors=A,B,C --consumer C` (each donor run's value at ADDR; a pattern such as `donors=set-*`
850
+ matches the runs `each ... keep` left; a cache cell `cache.L<l>.k|v[kv<g>,row=<r>]` goes to
851
+ `donors.whatif_cells`, with the cursor at the consumer row's first stop). Pooled: `effect`
852
+ when >= 1 donor has one.
853
+ - **`path-diverged`** (`mdb.analysis.measure.paths`, `path=true` on `whatif`, `compare` and
854
+ `sweep`): after an edit at row r, layer l, the argmax over sources of every downstream `p` row
855
+ (heads x rows >= r x layers the edit reaches) is compared with the base's; ties are not counted.
856
+ The paired effect is reported beside it: total (free) and frozen-selection (`hold t*.L>=k.p` at
857
+ the unedited reference). `compare ... path=true` reports it per edit side (A, B, A+B);
858
+ `sweep ... path=true` adds `path_diverged` and `frozen_delta` tables (three arms per cell, so
859
+ about 3x the cells' layer calls; one origin).
860
+ - **Selected but zero-valued units** (`mdb.analysis.numerics.units`, `explain M[a,b] units=K`): MLP
861
+ units
862
+ whose gate `sg` is active but whose contribution through `u` is ~0, which contribution ranking
863
+ never lists (`machines.x86.mlp.attribute` names them on the binary's dispatch).
864
+
865
+ Two library modules from the same work have no REPL verb. `mdb.analysis.measure.bridge` runs a
866
+ batched functional forward over a small Llama-family Hugging Face model (`Fwd(model, allow=None)`,
867
+ with `edit`/`hold`/`capture` at sites `t{r}.h{lev}` and `t{r}.L{l}.v{h}`) and the instruments built
868
+ on it: `transplant` (a donor's value at one site), `paired` (total against frozen-selection effect;
869
+ `channel` names the ratio), `class_swap`, `bridge_verdict` (not read / side by side / abstract /
870
+ joint answers for a row several answer rows read), `pairs` (base/donor pairs) and `attach_mask`.
871
+ `mdb.analysis.measure.novelty` asks whether a cell's value is new or a re-encoding of the input:
872
+ `bridge_share` (the part of a cell's cross-item variation a bridge label explains, family held
873
+ fixed), `novelty` (`novel`, `input re-encoding`, `no bridge code` or `undecidable` against a
874
+ reference representation of the input), `permutation_null`, `answer_separable` and `walk_back`
875
+ along a reads graph.
876
+
877
+ ### Two floors
878
+
879
+ mdb uses two floors, for two different questions. Both are `supplied` constants in
880
+ `mdb.analysis.numerics.verdict`, measured in spacings of the consumer's dtype.
881
+
882
+ | Floor | Value | Question | Used by |
883
+ |---|---|---|---|
884
+ | Verdict floor, `FLOOR_SPACINGS` | 1 spacing at the consumer's magnitude | Did native code produce what mdb's emulated chain predicted, from the same operands on the same run? | `verify`, `whatif`, `reads`, `forecast.verify` |
885
+ | Noise floor, `MARGIN_FLOOR_SPACINGS` (`margin_floor`) | 2 spacings at the larger `\|logit\|` of the margin, plus an optional measured `extra` | Is a margin change larger than what another realisation of the same forward (batched vs stepped, another library, another batch) could move it by? | `Branches` (`floor_spacings=2` by default), `supplied.judge`, `stability` |
886
+
887
+ The verdict floor can be one spacing because the emulated chain reproduces native rounding bit for
888
+ bit on the same run (measured, see [Predictions](#predictions-forecast-verify-whatif)). An effect
889
+ compared across realisations has no such shared rounding, so its floor is wider; examples 02 to
890
+ 07 use `Branches` and so quote the 2-spacing noise floor.
891
+
892
+ ### Verdict stability across realisations
893
+
894
+ The noise floor says whether one realisation of a forward moved the consumer, not whether the
895
+ verdict survives another realisation of the same forward. Measured on the developers' GPU (the run
896
+ behind [example 02](https://github.com/JHollenb/saturn/tree/main/packages/mdb/examples/02-tl-reparametrisation-floor)): mdb's patch effects on
897
+ Qwen3-0.6B-Base and Qwen2.5-0.5B (bf16), re-run through TransformerLens. Every verdict lost (sign
898
+ reversed, or fallen to the 2-spacing floor) was within 4 floors, and none above 4 floors was lost
899
+ on any path (0/110, 0/104). Any reordering moves 3-spacing verdicts: kernel path (TL batched vs mdb
900
+ stepped) 60/274 and 16/228, batch composition (TL batched vs batch-1) 72/286 and 19/241, processing
901
+ (processed vs unprocessed bridge) 46/257 and 82/249. On Qwen2.5, processing, not the kernel path,
902
+ dominates.
903
+
904
+ `mdb.analysis.numerics.stability` adds a margin rule beside the verdict (the verdict field is
905
+ unchanged): `stability` is `stable` when `|effect| > k` floors, else `kernel-sensitive`, and
906
+ every result names the `kernel_path` its native number came from (`mdb-stepped`, `batched`, or a
907
+ caller-declared string). `k` defaults to `STABLE_FLOORS = 4` (`supplied`, from that table);
908
+ `stability.calibrate(pairs, model=...)` measures it per model from `(reference, other, floor)`
909
+ effect pairs of two realisations (the smallest `k` above which no verdict is lost, with the
910
+ loss table by bin) as a `Calibration` saved to JSON. `supplied.judge(..., kernel_path=,
911
+ calibration=, stable_floors=)` and `forecast.verify(run, kernel_path="mdb-stepped",
912
+ calibration=, stable_floors=)` take it; `verify` marks margin forecasts (`|M|` against 2 spacings
913
+ at the larger logit). Calibrated on the same run (mdb stepped as reference): kernel path only
914
+ k = 2.125 (Qwen3-0.6B-Base) and 2.0 (Qwen2.5-0.5B); every path pooled (TL batched, processed,
915
+ batch-1) k = 2.125 and 3.75.
916
+
917
+ ## Following a value: `reads`, `symbols`, `circuit`, `compare`
918
+
919
+ `reads ADDR` lists who reads a source row: attention mass beside the exact contribution of
920
+ that read to a consumer, and a causal verdict measured by removing the read natively.
921
+ `symbols` prints the symbol table as bindings (where a value is defined, how long it lives,
922
+ who reads it), always with an `Unbound` row so the table sums to the whole. Cursor at
923
+ `t3.logits`; output cut at `...`:
924
+
925
+ ```
926
+ (mdb) reads t1 --consumer M[4,9] top=3
927
+ reads t1 at t3.logits rows t3 consumer t3.M[4,9] (4 reads)
928
+ t3.L1.h0 mass 0.24902 [measured] effect 0.011455 [derived-exact P19]
929
+ causal: Δ -0.015137 [measured], emulated -0.015137 [derived-exact], residual 0 [measured P20] = 0 spacings; exact -0.014201 [derived-exact]; floor 0.00048828 [supplied P20]
930
+ ...
931
+ (mdb) symbol ctx = t1, cache.L1.v[row=2]
932
+ symbol ctx = t1, cache.L1.v[row=2] (declared: ctx)
933
+ (mdb) symbols consumer=M[4,9]
934
+ symbols at t3.logits consumer t3.M[4,9] = -0.11401 [measured] min_mass 0.1 [supplied]
935
+ ... (two legend lines cut)
936
+ ctx read mass 1.4971 [derived-exact] over 4 reads (mean 0.37427 [derived-exact]) to_consumer 0.0020898 [derived-exact P19] life t3:## (t3.L0..t3.L1)
937
+ defined t1, cache.L1.v[row=2]
938
+ readers t3.L1.h0 mass 0.49805 [derived-exact] effect 0.013241 [derived-exact P19]; t3.L0.h1 mass 0.25 effect -0.0081352 [derived-exact P19]; ...
939
+ ...
940
+ Unbound mass 0 [derived-exact] readout -0.14463 [measured]
941
+ ```
942
+
943
+ Mass is summed over the heads and layers that read the binding, so it can exceed 1. Causal
944
+ verdicts follow the rule in [Verdicts](#verdicts).
945
+
946
+ ### Named symbols from a transplant
947
+
948
+ A transplant (`whatif` or `compare` writing another run's value, `ORIGIN:ADDR`, or another
949
+ address's value at one source occurrence) can be named: `symbol NAME = whatif` takes
950
+ the last `whatif` of the session, `symbol NAME = compare.a` (or `.b`) a side of the last
951
+ `compare`, `symbol NAME = each3:freezing` one item's `whatif` of an `each` result. The `symbol`
952
+ record (`core.kinds.SYMBOL`) is a schema plus bindings:
953
+
954
+ - role: the writer without its row (`L1.v[kv0]`: port, selector, layer; or a cache cell
955
+ `cache.L1.v[kv0,row=@]`) and its readers, the reads of the source at the consumer's row as
956
+ `reads` reports them (mass `measured`, effect `derived-exact P19`, causal verdict `measured`;
957
+ `readers=K`, `causal=false`); a port that attention does not read (`A`, `m`, ...) or a released
958
+ run gives readers `unresolved` with the reason;
959
+ - row: role-relative (`t@subject`) when the run's prompt is an item of a loaded prompt set with
960
+ a role at that row (`role=R` picks one, or supplies it), otherwise absolute, with the sha256 of
961
+ the prompt and of the tokens before the row;
962
+ - consumer and evidence: base, edited and delta `measured`, the verdict; origin: the donor value
963
+ (run, address, sha256, cut), the run, its prefill split and its edits.
964
+
965
+ Design choices (each is a choice, not a constraint of the engine, and can be reversed):
966
+
967
+ - A `no effect` or `unresolved` result is refused. It is not stored as an unbound symbol, so every
968
+ named symbol has a measured effect behind it.
969
+ - A role names one row. For a word of several tokens that is its first token; the other tokens
970
+ are not part of the symbol (measured: a weak effect on such words).
971
+ - On a plain run (outside `each`) a role symbol may bind by the same-tokens-before-the-row rule.
972
+ Inside `each` it binds by the item's role only.
973
+ - `break NAME` resolves the name once, when the breakpoint is set. It does not re-bind when the
974
+ run or the prompt changes.
975
+ - A `whatif` whose source is another address of the same run counts as a transplant and can be
976
+ named.
977
+ - Readers are measured at the consumer's row only. Reads of the source at other rows are not in
978
+ the record.
979
+ - "Last `whatif`" and "last `compare`" are tracked per context (per REPL or per server session),
980
+ not globally.
981
+ - `symbol show`, `symbol delete` and `symbols` work without a live run.
982
+ - A name lives in the session. The record is stored in the project, but reopening the project does
983
+ not bring the name back.
984
+ - Names are expanded by a generic before/after hook in `ops.registry.dispatch`
985
+ (`registry.hook`), so every verb that takes an address accepts a name without its own code.
986
+
987
+ Only a result with verdict `effect` is declared; `no effect`, `unresolved` or a scalar edit
988
+ (an ablation, not a transplant) is refused and no record is made. The name stands for its address
989
+ where an address is expected (`print`, `x`, `whatif`, `set`, `compare`, `break`, `reads`,
990
+ `until`, ...); the result lists each use under `symbol_uses`. On a run the row binds through the
991
+ declaring prompt, a set item with the same tokens and the role, or the same tokens before the row;
992
+ otherwise the use is refused with the reason. `break NAME` sets the breakpoint at the address
993
+ bound now. Inside `each`, a role symbol binds through each item's role and `@pair:NAME` through
994
+ the pair's; an item without the role is refused. `symbol show NAME` prints the record and its
995
+ binding here, `symbols` lists named symbols under its table (`named`), `symbol delete NAME`
996
+ removes it from the session (a record stored in a project stays). Tiny Qwen2
997
+ (`tests/repl_golden/symbol_named.out`), cut:
998
+
999
+ ```
1000
+ (mdb) whatif t1.L1.v[kv0] = clean:t1.L1.v[kv0] --consumer M[4,9]
1001
+ ...
1002
+ (mdb) symbol subj = whatif
1003
+ symbol subj = t@subject.L1.v[kv0] (record 079ace6f75cdd4a4)
1004
+ role writer L1.v[kv0] (occurrence, L1 v)
1005
+ row t1 (id 5): role @subject (set item pairs/a); prompt 6 rows sha256 6cc0862f50c8
1006
+ readers of cache.L1.v[kv0,row=1] at t5 (2 of 2 listed, at t5.logits):
1007
+ t5.L1.h0 mass 0.16699 [measured] effect 0.01116 [derived-exact P19] causal (Δ -0.011108 [measured])
1008
+ t5.L1.h1 mass 0.16602 [measured] effect -0.0017376 [derived-exact P19] causal (Δ 0.0024414 [measured])
1009
+ effect whatif t1.L1.v[kv0] = clean:t1.L1.v[kv0] -> t5.M[4,9]: base -0.038208 [measured] -> edited -0.052734 [measured], Δ -0.014526 [measured], verdict effect
1010
+ origin the last whatif; donor clean:t1.L1.v[kv0] sha256 e8298c9893e5; run main; prefill=0: no row batched, first stepped row t0
1011
+ (mdb) each pairs prefill=@subject: whatif subj = @pair:subj --consumer t@last.M[$answer,$foil]
1012
+ ...
1013
+ a -0.014526 -0.014033 effect
1014
+ b 0.013977 0.014417 effect
1015
+ c 0.0041504 0.0045585 effect
1016
+ d refused: no role 'subject' (roles: last)
1017
+ ```
1018
+
1019
+ `circuit CONSUMER` builds a record of exact contributions that closes on the consumer;
1020
+ whatever is not listed stays in the record as `+N more` and `remainder` nodes; a subtree that was
1021
+ dropped without expanding is recorded as not examined, and one that does not fit one record is a
1022
+ `paged` pointer to a sha256-checked child page (`circuit show ID node=NODEID`).
1023
+
1024
+ `circuit test ID ref=NAME` checks a circuit against a reference run NAME (another run of the
1025
+ debugger, e.g. the opposite-answer prompt; `ref=set:NAME` uses the per-component mean over a
1026
+ prompt set's items at their `@last` rows). Components are what the engine patches at the
1027
+ consumer's row: the row input `L0.h`, each head's block of `L<l>.A` and each layer's `m` (or each
1028
+ neuron of `f` where the circuit expanded that MLP); a source-row node counts as its head;
1029
+ `+N more` groups and their unexamined members are the complement. Earlier rows stay this run's.
1030
+ Each of these is one native pass from layer 0 with every edit staged, the session restored:
1031
+ `ko` patches only the circuit's components from the reference, `keep` every other component,
1032
+ `full` all of them (equal to the reference's own margin bit for bit). The result prints the
1033
+ margins `base`, `ref`, `ko`, `keep`, `full` and `faithfulness = (keep - ref) / (base - ref)`,
1034
+ `knock-out share = (base - ko) / (base - ref)`, all `measured`; the ratios are refused when
1035
+ `|base - ref|` is under one spacing of the consumer's dtype. There is no pass/fail bar; the only
1036
+ words are one-spacing comparisons. Zero-ablation is not offered (on Qwen2.5-1.5B zeroing the
1037
+ 26,924-node complement moved the margin by 27.75 against a circuit effect of 1.81). The result
1038
+ is a `circuit-test` record (stored with a project; the component list is a sha256-checked blob):
1039
+
1040
+ ```
1041
+ (mdb) circuit test 1 ref=clean
1042
+ circuit 1 test t3.M[4,9] ref clean (run, row t3)
1043
+ components [derived-exact] 7: circuit 3, complement 4 (4 from +N more groups, 4 of them never expanded); 4 source node(s) counted as their head
1044
+ the test is over the consumer row's components; earlier rows are this run's (they reach the consumer row only through the cache, which a fully patched A does not read)
1045
+ base -0.11401 [measured] this run, nothing patched
1046
+ ref -0.13965 [measured] the consumer read in the reference run at its @last row
1047
+ ko -0.14478 [measured] knock-out: only the circuit's components patched from the reference
1048
+ keep -0.10986 [measured] keep-only: every component outside the circuit patched from the reference; the circuit's components computed natively
1049
+ full -0.13965 [measured] every component patched from the reference (= ref bit for bit)
1050
+ faithfulness (keep - ref) / (base - ref) = 1.1619 [measured]: the share of base - ref that the circuit keeps when everything else takes the reference's values (1: all of it, 0: none)
1051
+ knock-out share (base - ko) / (base - ref) = 1.2 [measured]: the share of base - ref that patching only the circuit removes (1: all of it, 0: none)
1052
+ reading: knock-out measurable effect; keep differs from base; keep differs from ref (one spacing 0.00048828 [derived-exact] bfloat16)
1053
+ layer calls completed [measured] ko 4 keep 4 full 4; edits [derived-exact] ko 2 keep 3 full 5
1054
+ ```
1055
+
1056
+ `compare` measures two edits separately and together:
1057
+
1058
+ ```
1059
+ (mdb) circuit M[4,9] top=2 depth=3
1060
+ circuit 1 t3.M[4,9] top 2 depth 3 (16 nodes, record 48dd09c8ac8e3967)
1061
+ t3.M[4,9] -0.11401 [measured]
1062
+ embedding t3.L0.h -0.14578 [derived-exact P19]
1063
+ L1.attn t3.L1.o 0.03064 [derived-exact P19]
1064
+ ...
1065
+ +3 more t3.M[4,9] (unlisted) 0.00064862 [derived-exact] (not examined, 3 subtree(s) not expanded)
1066
+ remainder t3.M[4,9] 0.00047376 [measured] within 0.016137 [bound]
1067
+ closure 1.3878e-17 [derived-exact P19] within 2.0716e-15 [bound] (zero by construction: float64 summation only)
1068
+ remainders: 3 dropped subtree(s) not examined; no claim about their rounding bounds; 0 edit node(s)
1069
+ (mdb) compare L1.m=0.5 add L0.v = 0.25 add --consumer M[4,9]
1070
+ compare A: L1.m=0.5 add B: L0.v=0.25 add -> t3.M[4,9]
1071
+ base -0.11401 [measured] A 0.050476 [measured] B -0.068237 [measured] A+B 0.052124 [measured]
1072
+ effects A 0.16449 [measured] B 0.045776 [measured] A+B 0.16614 [measured]
1073
+ verdicts (native only, no exact or emulated chain: effect when edited and base differ): A effect B effect A+B effect
1074
+ interaction (A+B) - A - B + base = -0.044128 [measured]
1075
+ order: A+B stages both sides' edits layer by layer; at one port A's edit is applied before B's (where both edit one port, the ops commute)
1076
+ session unchanged at t3.logits
1077
+ ```
1078
+
1079
+ `seek ADDR` moves the session to an occurrence: forward, backward, or by replaying a stored
1080
+ recipe when a project is attached.
1081
+
1082
+ ## Prompt sets
1083
+
1084
+ Every verb above answers for one prompt. `each SET: OP LINE` runs one op line on every prompt of
1085
+ a set and adds a summary. The engine stays batch 1: each prompt gets its own run (`start`, then
1086
+ `until AT`, by default `t@last.logits`), the line goes through the same op registry as when you
1087
+ type it, and the run is released (`keep` holds the runs as `SET-ITEM`, for `frame recall-a:`).
1088
+ A set is a JSONL file of items (`tests/fixtures/prompt_set_tiny.jsonl`):
1089
+
1090
+ ```
1091
+ {"name": "a", "tokens": [1, 5, 9, 3], "roles": {"subject": 1}, "vars": {"answer": 4, "foil": 9}, "pair": "b"}
1092
+ ```
1093
+
1094
+ `prompt` (text, needs a tokenizer) or `tokens`; `roles` name rows (`@last` is always defined);
1095
+ `vars` name tokens (an id or a one-token text); `pair` names another item. A line uses them as a
1096
+ template, bound per item before dispatch, so each item's result holds plain addresses:
1097
+ `t@subject.L1.A[h1]` -> `t1.L1.A[h1]`, `[row=@subject]` and `rows=@subject` -> the row,
1098
+ `M[$answer,$foil]` -> `M[4,9]`, and `@pair:ADDR` -> the value at ADDR (roles of the paired item)
1099
+ in a clean run of the paired prompt at the same stop, the `ORIGIN:ADDR` of
1100
+ [State cells and other runs](#state-cells-and-other-runs). A pair address with no row
1101
+ (`@pair:L20.A[h5]`) means the paired item's last row whatever the two lengths, and the item's
1102
+ row names the donor address used (`donor`); `t@ROLE` names the pair's own role row. An item whose template does not bind
1103
+ (here `d` has no `subject`) or whose op is refused is listed with its reason and left out of the
1104
+ statistics; the others run. Real output on the tiny Qwen2 (`tests/repl_golden/prompt_set.out`):
1105
+
1106
+ ```
1107
+ (mdb) set load recall tests/fixtures/prompt_set_tiny.jsonl
1108
+ set recall: 4 items (tests/fixtures/prompt_set_tiny.jsonl)
1109
+ a 1 5 9 3 @subject=1 $answer=4 $foil=9 pair b
1110
+ ...
1111
+ (mdb) each recall: whatif L1.A[h1] *= 0 --consumer M[$answer,$foil]
1112
+ each recall: whatif L1.A[h1] *= 0 --consumer M[$answer,$foil]
1113
+ 4 items at t@last.logits; runs released; result each2
1114
+ item native exact verdict
1115
+ a -0.0083008 -0.0074347 effect
1116
+ b 0.0065918 0.0061747 effect
1117
+ c 0.034058 0.034368 effect
1118
+ d 0.024658 0.024872 effect
1119
+ labels: native measured, exact derived-exact
1120
+ summary: none refused; statistics over all 4 items
1121
+ measured.delta [measured]
1122
+ n 4 mean 0.014252 min -0.0083008 max 0.034058 sign + 3/4
1123
+ prediction.exact.value [derived-exact]
1124
+ n 4 mean 0.014495 min -0.0074347 max 0.034368 sign + 3/4
1125
+ effect.verdict: effect 4
1126
+ +41 more in the record (promptset result each2 [ITEM])
1127
+ (mdb) each recall: reads t@subject --consumer M[$answer,$foil] top=2
1128
+ ...
1129
+ item read mass effect causal verdict
1130
+ a t3.L1.h0 0.24902 0.011455 -0.015137 causal
1131
+ b t3.L1.h1 0.25195 -0.0082406 0.012207 causal
1132
+ c t4.L1.h1 0.19922 -0.0073077 0.0064697 causal
1133
+ d refused: no role 'subject' (roles: last)
1134
+ labels: mass measured, effect derived-exact, causal measured
1135
+ summary: 1 of 4 items refused (d) and excluded; statistics over the 3 others
1136
+ ...
1137
+ (mdb) each recall: whatif cache.L0.v[row=@subject] = @pair:cache.L0.v[row=@subject] --consumer M[$answer,$foil]
1138
+ ...
1139
+ a 0.0041504 0.0046219 effect
1140
+ ```
1141
+
1142
+ The result of `each` is one summary record (at most 1 MiB): a row per item (its key numbers,
1143
+ verdict, the sha256 of its result, the op's own record id when it seals one, the bytes its run
1144
+ held) and statistics for every labelled number found at the same result path in all items that
1145
+ ran: n, mean, min, max and how many share the most common sign, plus a count per value of every
1146
+ verdict and state field. A statistic keeps its inputs' label when all share it; inputs with
1147
+ different labels are summarised per label, never merged. The statistics are arithmetic on these
1148
+ items only. Each item's full result is kept in memory: `promptset result each2 a` prints it. With
1149
+ a writable project it is also a sha256-checked JSON blob in the project store (the item's row
1150
+ has its `blob` pointer; without a project the row says the result is held in memory only), so
1151
+ `promptset result RECORD a`, with RECORD the summary's `stored` id, reads it back in a new
1152
+ process and refuses a changed blob. `promptset load` reads a file on the server, so the web
1153
+ console and the `/op` route refuse it; send the set inline with `promptset define NAME ITEMS`
1154
+ (items as a JSON list or JSONL). A
1155
+ path such as `reads.0.mass` is "the first listed read", which can be a different head in each
1156
+ item. With a project attached the summary is also stored as a `prompt-set` record. After `each`
1157
+ the current run, its cursor, the run table and the session digest are what they were. From
1158
+ Python: `dbg.each("recall", "reads t@subject --consumer M[$answer,$foil]")` (a loaded set, a
1159
+ `.jsonl` path or a list of item dicts) returns `summary`, `results` (item -> result) and the
1160
+ uncapped `statistics`.
1161
+
1162
+ Measured on the tiny Qwen2 (CPU, one process): a run holds 600 to 872 bytes at its logits, 1.4
1163
+ to 1.8 KB after `whatif` and 1.8 to 2.1 KB after `reads` (`Run.held_bytes()`); one item takes
1164
+ about 0.07 s for `whatif` or `reads`, 0.016 s for `print`; 40 items of `reads` took 3.7 s and
1165
+ gave a 27.7 KB summary.
1166
+
1167
+ ## Durable checkpoints
1168
+
1169
+ ```python
1170
+ dbg = mdb.attach(model, tok, project="runs/t") # creates or reopens the project
1171
+ run = dbg.run(tokens); run.until("L1.sg"); run.set("L1.u", tensor, "add")
1172
+ info = dbg.checkpoint(run, "pre") # the state (tensor blobs) + replay recipe
1173
+ run = mdb.attach(model, tok, project="runs/t").restart("pre") # later, another process, same scope
1174
+ run = dbg.run_from(info["state"]) # the same by record id (or a file path)
1175
+ ```
1176
+
1177
+ `restart` rehydrates the stored state: no prefix is recomputed, and the run has the same cut
1178
+ fingerprints, edits and cursor (`restart(name, verify=True)` also replays the recipe once and
1179
+ records that it reaches the same fingerprint; `replay=True` replays instead). Projects written
1180
+ before checkpoints held state replay as before. See
1181
+ [Checkpoints](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/BRANCHES-POOLS-HOLDS.md#checkpoints-enginecheckpointpy-core-files).
1182
+ The REPL's `checkpoint NAME` / `restart NAME` do the same when a project is attached:
1183
+ `checkpoint NAME` prints the record id of the stored state, `checkpoints` (or `info
1184
+ checkpoints`) lists the project's checkpoints with their record ids in any later process, and
1185
+ `start from=NAME` (or `from=ID`) starts a new run there;
1186
+ `mdb.resolve(pointer, project=..., session=dbg)` turns an occurrence pointer into a tensor.
1187
+
1188
+ `export NAME to=DIR` (`dbg.export_bundle(name, dir)`) writes the checkpoint `NAME` (state record
1189
+ and tensor blobs, its `checkpoint` record and replay recipe) and every project record that names
1190
+ the state's record id (records about runs started from it, such as a stored `sweep`) to a new
1191
+ directory: `bundle.json`, `records/`, `recipes/`, `tensors/`, each blob and record checked by
1192
+ sha256 and seal. In another project `start from=DIR` imports it and starts there (bit-identical
1193
+ on the same model and execution; `verify=true` replays the recipe); afterwards `start from=NAME`,
1194
+ `restart NAME` and `checkpoints` find it (`dbg.import_bundle(dir)` imports without starting).
1195
+ Records that are sealed but not stored in the project index (a REPL `whatif`) are not included.
1196
+
1197
+ ## Branches, pools, holds, checkpoints, custody
1198
+
1199
+ Debugger objects for the loops an experiment script otherwise writes by hand (several branches from one checkpoint, sets of donor values, frozen attention, saved prefixes, provenance), all in [docs/BRANCHES-POOLS-HOLDS.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/BRANCHES-POOLS-HOLDS.md):
1200
+
1201
+ - `run.set("t5.L20.v[kv6]", donor.ref("t5.L20.v[kv6]"))` takes REPL selectors and cross-run values with their origin pointer.
1202
+ - `run.hold("t@last.L>20.p", source=base)` and `run.hold("t@last.L>20.norm_scale", source=base)` keep attention weights, norm scales or cells at a reference run's values.
1203
+ - `dbg.branches(run, Margin(...), at=...)` gives named arms from one checkpoint with one shared floor, built-in nulls (`random`, `self`, `answer`), stability band, kernel path and sealed record. `subspace.interchange` uses it.
1204
+ - `dbg.pool(items, "cache.L20.v[kv6,row=@carrier]")` gives sealed value sets with a leave-one-out mean (the item excluded by construction), donor rules and matched-norm random.
1205
+ - `run.dump(path)` / `dbg.checkpoint(run, name)` save the state at the cursor (a cut inside a row too) as content-addressed tensors in a file or the project store; `dbg.run_from(path or record id)` rehydrates it in any process with no prefix recompute, bit-identical, with the source's fingerprints, so checkpoints move between the runs and `Branches`, `Pool` and `each` (`core=`) run from it. Another dtype or weights loads only as a labelled replica (`replica=True`), null-checked on load.
1206
+ - `sae.open_transcoders` and `components.transcoder_binding` handle transcoders as MLP-write component bindings.
1207
+ - `dbg.custody(script=, prereg=)` and `dbg.records_to(path)` give every sealed record custody and a sink. With no path, a directory or `{run}` in the name the sink file is unique per process and mrun job; an existing file another run wrote is refused unless `append=True`; pointer payloads with no store (a compact branches record's `arms_payload`) are written into the sink too. Records are schema `mdb-record-v3` from 0.2.2; `mdb records migrate PATH` writes the v3 twin of an older sink file with an id map ([docs/RECORDS.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/RECORDS.md)).
1208
+ - `br.run(mode="batched")` batches whole-cell and native-port arms; the default `recheck="band"` re-measures stepped only arms within `1/k..k` floors. `Branches(..., probes={...})` reads named values on every stepped arm before restore; a branches record too large for one line is sealed compact with the full rows by pointer.
1209
+ - `analysis.symbols.subspace.SubspaceBinding` names a `k`-dimensional subspace of one value cell `cache.L<l>.v[kv<g>,row=r]` by an orthonormal basis with provenance and a basis authority (`derived-exact` from `readout_subspace`, `fitted` from `from_pyvene` DAS or `class_mean_subspace`, `supplied`); `decompose()` returns a `ComponentBinding`, and `subspace.interchange` (measured) rides on `Branches`.
1210
+ - `FeatureCondition(text, contexts)` watches several feature sites at once (`features.feature_sites({layer: basis}, row=r)`), one memory per layer, hits carrying site and layer.
1211
+ - `symbols.hop.gate_switch_forecast(run, edited, reader, cell_layer=L)` gives first-order forecasts of a cell edit's consumer change with and without exact SwiGLU gate switches, beside `hop_edge`.
1212
+
1213
+ The direct-effect vector `rho_F gamma (W_U[a] - W_U[b])` is `reads.readout(run, Margin(row, a, b)).vector`. Do not recompute it.
1214
+
1215
+ ## SAE feature bases: `sae`, `features`, `feature`
1216
+
1217
+ `sae load qs DIR` reads a per-layer residual SAE set (Qwen-Scope layout: `config.json` with `k`
1218
+ and `hook_point`, files `layer{L}.sae.pt` with `W_enc b_enc W_dec b_dec`); `resid_post` of layer
1219
+ `L` is the port `L<L>.h_out` (same value as `L<L+1>.h`). At a native value `x` the basis gives
1220
+ the exact identity `x = b_dec + sum_f a_f d_f + e`: the active set by the published rule (top-k
1221
+ of `relu(W_enc x + b_enc)` in float32), activations recomputed in float64 from the native bits,
1222
+ and the error `e` = native minus reconstruction, always listed. `features ADDR consumer=M[a,b]`
1223
+ splits the direct path `rho c.x` (P19) over the features, `b_dec` and `e` and closes on the
1224
+ native margin with the later layers' terms and the measured remainder; `features L*.h_out
1225
+ consumer=...` is the per-layer profile (`shift=` applies each SAE off its site, a site-alignment
1226
+ check: only the error fraction shows a misalignment); `circuit=true` stores a circuit record
1227
+ whose error node is never folded; `match=L22.f[i=5773]` (or `L20.A[h13]`, `L20.A[h13,src=11]`)
1228
+ names an mdb unit by the decoder directions closest to its write, with the fraction outside
1229
+ their span. Feature values ride the edit path (`set`, `whatif`, `compare`):
1230
+ `feature[ID]*X` (add `X d_ID`), `feature[ID,coef]*-1` (remove `a_ID d_ID`), `error*-1` (splice
1231
+ in the reconstruction), `recon`, `bias`, and `@RUN` for another run's value at the same site
1232
+ (`recon@rome-recon` swaps in the other run's feature part and keeps this run's error).
1233
+ Feature component tables can link to Neuronpedia without a hand-written id map: MDB reads
1234
+ layer-bound SAE metadata or the installed SAELens registry (`pip install '.[saelens]'` from
1235
+ this directory). Explicit mappings still override both. Missing mappings stay unresolved;
1236
+ MDB never guesses a source id. The browser draws saved component tables as feature → carrier
1237
+ → consumer graphs with clickable feature links. [Example 08](https://github.com/JHollenb/saturn/tree/main/packages/mdb/examples/08-neuronpedia-links)
1238
+ walks through a model-free preview and a local-model capture.
1239
+
1240
+ A worked example on Qwen3-1.7B-Base with Qwen-Scope SAEs: [docs/SAE-WORKED-EXAMPLE.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/SAE-WORKED-EXAMPLE.md)
1241
+ and [examples/01-sae-census-qwen3-1.7b](https://github.com/JHollenb/saturn/tree/main/packages/mdb/examples/01-sae-census-qwen3-1.7b).
1242
+
1243
+ ## Binaries: `mdb.machines.x86`
1244
+
1245
+ `mdb.machines` holds machines that are not Hugging Face decoders. `mdb.machines.x86` debugs an
1246
+ x86-64 binary executed by torchx86 in batched lanes. torchx86 and `isa_bench` are optional
1247
+ dependencies imported normally (install isa-bench, put `<isa-bench>/models/torchx86/src` on
1248
+ `PYTHONPATH`, `pip install capstone`); without them `torchx86()` raises an ImportError saying so.
1249
+
1250
+ ```python
1251
+ # not run here: needs torchx86 and an isa-bench program directory
1252
+ from mdb.machines import x86
1253
+ run = x86.attach("PROGRAM_DIR", donors=[b"...", b"..."]) # mem.bin, trace.npz (prog.elf optional)
1254
+ run.step(10); run.print("rax"); run.reverse_step() # a bare site is at the cursor
1255
+ run.whatif("rax", 0x2a) # sealed prediction, then native lanes: verdict, total and frozen effect
1256
+ cone = run.cone() # the answer's backward dependence cone (ticks, typed reads)
1257
+ run.interchange("init.mem[0x40300c:1]", donors) # a block from each donor run, pooled effect on y
1258
+ ```
1259
+
1260
+ `attach(program, input=None, *, device="cpu", donors=None, cap=None)` runs the binary once and
1261
+ returns a `BinRun` stopped at tick 0; motion moves a cursor over the recorded trace, and `set` or
1262
+ `hold` re-executes natively from the start with the edits applied. Its verbs: `step`, `next`,
1263
+ `finish`, `reverse_step`, `seek`, `cont`, `reverse_cont`, `break_at`, `watch`, `delete`,
1264
+ `print`, `x`, `read`, `reads`, `set`, `fork`, `compare`, `hold`, `checkpoint`, `restart`,
1265
+ `forecast` / `verify` (exact equality), `whatif` (verdicts `effect`, `no effect`,
1266
+ `path-diverged`, `fault`, `nonterminating`), `cone`, `interchange` (one lane per informative
1267
+ base/donor pair, pooled by `mdb.analysis.measure.donors`), `sweep` (a patch grid on lanes) and
1268
+ `symbols` (symbol-table recovery over the donors; `method_v2` is a post-hoc variant). Records:
1269
+ `machine-forecast`, `machine-verify`, `machine-whatif`, `machine-whatif-result`
1270
+ ([docs/RECORDS.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/RECORDS.md#machine-records-mdbmachinesx86)), and symbol tables and circuit
1271
+ maps ([docs/SYMBOL-TABLE-SCHEMA.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/SYMBOL-TABLE-SCHEMA.md#machine-bindings-mdbmachines-2026-11-16)).
1272
+ `mdb.machines.x86.mlp` reads torchx86's ALU dispatch as a gated MLP (`i<t>.mlp.up|gate|f|down`).
1273
+
1274
+ ## Live and remote sessions: `mdb serve`
1275
+
1276
+ `mdb serve --project DIR` serves a recorded project read-only on loopback, with no model and no
1277
+ torch (it needs the `serve` extra). The browser at `/` shows the project's sessions with an
1278
+ address bar and a command line, and these views: Timeline (token by layer, with a branch
1279
+ rail), Graph, Symbols, Records and an Inspector whose reductions (`POST /api/v1/s/SID/reduce`)
1280
+ never send a whole tensor. Every response is at most 64 KiB. The recorded browser reads lane-era
1281
+ projects and engine-native ones (circuit and symbol-table records, and the cuts kept by
1282
+ `checkpoint-state` records, so a session saved with `Debugger.checkpoint` has addressable cuts
1283
+ in the timeline; the fixture is built by `tests/test_serve_recorded.py`).
1284
+
1285
+ With `--tiny FAMILY` or `--model PATH|NAME` (the same forms as `mdb engine MODEL`) the server also holds one live debugger, attached with
1286
+ that project (`--dtype bf16|fp32`, `--device` and, for a tiny model, `--seed` as in `mdb engine`;
1287
+ `--host` defaults to 127.0.0.1 and `--port` to 8765). The page gets a Live view with four tabs and an architecture strip:
1288
+
1289
+ - Pipeline: the current layer's ports, motion controls, breakpoints, edits, checkpoints, console.
1290
+ - Symbols: one row per binding (definition sites, lifetime strip, readers with mass and exact
1291
+ effect, verdicts on request), an Unbound row, a consumer selector, a declare form and the
1292
+ named symbols (source, measured Δ, binding here).
1293
+ - Circuits: build, list and show circuits as a layered graph with `+N more` and remainder
1294
+ nodes, a keyboard walk and seek on Enter; `circuit test` with a reference-run picker (the
1295
+ debugger's other runs, or `set:NAME`) shows the five margins and the two ratios with labels.
1296
+ - Predict: a forecast column (hollow until verified), `whatif` with the sealed prediction and
1297
+ error split, and `compare`. Nothing stages an edit except an explicit button.
1298
+ - Arch strip (above the tabs): layers as rows with the current layer's ports, computed ports,
1299
+ edits, checkpoints and the selected circuit.
1300
+
1301
+ Every action is the registry op of the same name (`POST /api/v1/s/SID/op`), run on one worker
1302
+ thread in arrival order; `GET /api/v1/s/SID/live/ledger` lists the run's circuits, forecasts and
1303
+ symbols. Build the web app with `npm run build` in `web/` before building a wheel. `mdb engine
1304
+ http://HOST:PORT` is the same REPL prompt over the live session; the model stays in the server
1305
+ process and the client needs only the standard library. Run as two processes (the server from
1306
+ an environment with the `serve` extra):
1307
+
1308
+ ```
1309
+ $ python -m mdb serve --project runs/t --tiny qwen2 --port 8799
1310
+ mdb serve: http://127.0.0.1:8799/ (project runs/t; live session qwen2-6173365f545b)
1311
+ $ python -m mdb engine http://127.0.0.1:8799 --tokens "1 5 9 3" --script walk.mdb
1312
+ (mdb) start 1 5 9 3
1313
+ t3.L0.h h = layer input (residual stream) {P01}
1314
+ (mdb) until L1.p
1315
+ t3.L1.p p = softmax(s, float32).to(dtype) (native attention weights) {P05 P06 P07 P08 P09}
1316
+ (mdb) checkpoint pre
1317
+ checkpoint pre at t3.L1.p (750 bytes)
1318
+ $ echo "info checkpoints" | python -m mdb engine http://127.0.0.1:8799 # a second client
1319
+ (mdb) info checkpoints
1320
+ pre t3.L1.p staged 0, committed 0
1321
+ ```
1322
+
1323
+ (`walk.mdb` holds `until L1.p` and `checkpoint pre`; `--tokens` issues the `start`.) In the
1324
+ remote prompt `quit` ends the client and leaves the session as it is, `source FILE` reads the
1325
+ client's file, and Ctrl-C interrupts the op the server is running. From Python:
1326
+ `mdb.repl.remote.Remote(url).op("print", address="p")` returns the JSON that `--json` prints.
1327
+ The server has no authentication and binds loopback; use a tunnel (`ssh -L 8799:127.0.0.1:8799
1328
+ host`). `--allow-remote` and `--allow-host` exist but add no authentication. One SIGTERM ends `mdb serve`
1329
+ even with a browser's events socket open (`tests/test_serve_sigterm.py`). `--tiny` takes the same
1330
+ four families as `mdb engine`. The `/op` route refuses `promptset load` (it reads a file on the
1331
+ server); send a set with `promptset define`.
1332
+
1333
+ ## TransformerLens and nnsight
1334
+
1335
+ `mdb.interop` (extra `interop`) maps every port to its TransformerLens 4 bridge hook and nnsight path, imports a TL cache or nnsight saves as an origin (`tlrome:cache.L22.v[kv1,row=11]`, values labelled `supplied`), runs mdb edits batched over many prompts through nnsight, and re-measures another tool's claim with `whatif`. On Qwen2.5-1.5B every mapped port was bitwise equal across `mdb.trace`, the unprocessed bridge and nnsight (measured on the developers' GPU). See [docs/INTEROP.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/INTEROP.md).
1336
+
1337
+ ## Lanes
1338
+
1339
+ The older lane-era tool is the separate `mdb-lanes` distribution (`mdb_lanes`); the engine never imports it.
1340
+ It plugs in through the entry-point groups `mdb.lanes` (verbs: `mdb lanes VERB`, and a bare
1341
+ `mdb VERB` after a notice on stderr) and `mdb.lanes.exports` (names such as `mdb.BenchSession`).
1342
+ The plug-in and its documents live in the separate saturn-lab research repository
1343
+ (`packages/mdb-lanes`), which is not published, not in this package.
1344
+ Without the plug-in `python -m mdb lanes` exits 2 with "mdb lanes has no commands: the mdb-lanes
1345
+ plug-in is not installed". The plug-in is not published (not on PyPI and not in a public
1346
+ repository), so outside the developers' own research checkout these commands are unavailable;
1347
+ where it is installed, `python -m mdb lanes` prints its verbs and `mdb.BenchSession.__module__`
1348
+ is `mdb_lanes.bench`.
1349
+
1350
+ ## Tests
1351
+
1352
+ With `W` the repository root:
1353
+
1354
+ ```
1355
+ cd $W/packages/mdb && env PYTHONPATH=$W/src:$W/packages/mdb/src OMP_NUM_THREADS=1 \
1356
+ HF_HUB_OFFLINE=1 python -m pytest -q -p no:cacheprovider tests/test_engine_trace.py
1357
+ ```
1358
+
1359
+ `tests/test_import_contract.py` checks that the engine imports no lane module and that its
1360
+ layers (`core`, `engine`, `analysis`, `ops`, `interop`, `repl`, `serve`, `machines`) import only
1361
+ downward; `import mdb`
1362
+ loads no torch. Every automated test uses a random tiny CPU model.
1363
+
1364
+ Run the test files of the module you touched, not the whole suite (it is large and loads many
1365
+ tiny models; on a small laptop keep to one Python process at a time). Examples:
1366
+ `tests/test_ops_registry.py` (the op table), `tests/test_engine_run.py` (the stepper),
1367
+ `tests/test_analysis_whatif_modes.py` (whatif at any cursor), `tests/test_repl_golden.py` (the
1368
+ transcripts in `tests/repl_golden/`; after an intended change regenerate one with
1369
+ `MDB_UPDATE_GOLDEN=1 ... pytest tests/test_repl_golden.py -k NAME` and read the diff).
1370
+ `tests/test_deep_models.py` runs every analysis op on a 40-layer and a 70-layer tiny model (no op
1371
+ result may exceed the record bound). The serve tests (`tests/test_serve_*.py`) need the
1372
+ `serve` extra and `httpx` and skip with `importorskip` elsewhere,
1373
+ so a pass in the plain venv says nothing about the server. The tests of `saturn` live in
1374
+ `$W/tests` (run them from `$W` with `PYTHONPATH=$W/src`).
1375
+
1376
+ ## Contributing
1377
+
1378
+ The repository rules are in [CONTRIBUTING.md](https://github.com/JHollenb/saturn/blob/main/CONTRIBUTING.md): what ships, versioning and releases, testing and bit-identity, the invariants a change must keep, adding a model family or a machine, and how to file a bug, a model port request or a feature request (GitHub Issues).
1379
+
1380
+ ## Measured on a real model
1381
+
1382
+ **Measured on the developers' machine, not reproducible from this package alone.** Qwen2.5-1.5B,
1383
+ bf16, CUDA, eager attention, one RTX 4080, torch 2.13.0+cu130, transformers 5.13.1, run through
1384
+ our job scheduler, single runs. The raw logs and job records are internal and not shipped; these
1385
+ numbers show orders of magnitude, not guarantees. One prompt family (`Description: icy /
1386
+ Temperature: cold / ... / Temperature:`, 22 tokens, margin `M[" hot"," cold"]`); every number is
1387
+ `measured`. To check them on your own GPU, point `mdb engine` at a local Qwen2.5-1.5B and run the
1388
+ same verbs.
1389
+
1390
+ Cost and size:
1391
+
1392
+ - port step 2.8 ms; layer commit 5.2 ms; restore 4.8 ms; checkpoint 739 bytes; token 189 ms
1393
+ plain, 213 ms stepped; peak host memory 3.9 GB (the model load)
1394
+ - `explain` 0.28 s; `symbols` 0.40 s; `whatif` 1.9 s; `circuit` depth 2 / 3: 0.61 s / 0.46 s;
1395
+ `reads` 0.20 s, or 5.4 s with causal verdicts (measured before the causal verdicts were made to
1396
+ share one excursion; the faster path was measured on a tiny model only)
1397
+ - a later session: load + attach 3.74 s, `checkpoint` 0.29 s, `restart` 0.01 s, `explain M[a,b]`
1398
+ 0.26 s, `reads t18 ... causal=false` 0.52 s, `whatif` of a cache cell 2.25 s (2.19 s with
1399
+ `mix 0.5`); `verify` 0.00 to 0.01 s per forecast
1400
+
1401
+ Rounding: exact math is not what the dtype computes (3 prompts, `forecast` sealed at `L0.h` and at
1402
+ `L14.h`, then `verify`; bf16 28 layers and an fp32 2-layer cut of the same model):
1403
+
1404
+ - the emulated prediction is bit-equal to native at every stop checked: 0.0 spacings in every
1405
+ seal/verify pair (all `confirmed`), bf16 and fp32
1406
+ - the exact (float64) chain of the same operands is far off at `L0.m`: bf16 34.7, 48.4 and 78.0
1407
+ spacings for the three prompts (fp32 cut: 30.9 to 39.4); at the logits 1.4 to 1.6 spacings (bf16,
1408
+ sealed at `L0.h`)
1409
+ - origin, bf16 prompt 0 (t21): `t21.L0.s[h3]`, a score of spacing 64 at |s| 1.51e+04; rounding ties
1410
+ the top scores, so the native softmax is not the softmax of the real scores. Prompt 1 names
1411
+ `t11.L0.p[h1]` (spacing 64 at |s| 9.47e+03)
1412
+ - a float64 chain rounded once per sum is not enough (0 to 8 spacings off in bf16, 1 to 35 in fp32)
1413
+
1414
+ Cross-run head patch: `whatif L20.A[h5] = clean:L20.A[h5] --consumer M[" hot"," cold"]`, with the
1415
+ clean run on `boiling` and the edited run on `freezing`, moves the margin from -4.75 to -0.375
1416
+ (native dM 4.375, exact 4.2303, residual 0.14467, floor 0.25, `effect`).
1417
+
1418
+ Whatif exact is the same at both cursors: `whatif L20.m = clean:L20.m` sealed at `L0.h` (mode
1419
+ ahead) and again after `until logits` (mode rewind) both give exact dM 0.5074 on measured operands
1420
+ (0.50742 in the verdict line of each) and `whatif L20.A[h5] = clean:L20.A[h5]` gives 4.2145 at
1421
+ both; a no-op `L20.m *= 1` gives exact 0, native 0.
1422
+
1423
+ Prompt set: six temperature prompts (freezing, boiling, frosty, scorching, chilly, burning), margin
1424
+ `M[$answer,$foil]` 3.75 to 6.375, mean 4.7708, 6/6 positive. `each temp: whatif L20.A[h5] *= 0`
1425
+ gives a mean delta of -1.6042 (min -2, max -0.9375), 6/6 negative, all six `effect`. `each temp:
1426
+ whatif L20.A[h5] = @pair:L20.A[h5]` (head output from the opposite prompt) gives a mean delta of
1427
+ -4.6719 (min -5.1875, max -4.375), 4/4 negative; the other two items (prompts of 23 and 24 tokens)
1428
+ were refused because the pair address then named a prompt row. A pair address without a row now
1429
+ means the paired item's last row; that was not rerun on the real model.
1430
+
1431
+ Emulated verdicts: the three what-ifs above at both cursors (ahead and rewind) give emulated dM
1432
+ equal to native dM, residual 0 spacings: `L20.m = clean:L20.m` native 0.625, emulated 0.625, exact
1433
+ 0.50742 (rounding effect 0.11758), `effect`; `L20.A[h5] = clean:L20.A[h5]` native 4.375, emulated
1434
+ 4.375, exact 4.2145, `effect`; `L20.m *= 1` native 0, emulated 0, exact 0, `no effect`. `each temp:
1435
+ reads t@last --consumer M[$answer,$foil] top=3`: the top read of every prompt is `causal` (6/6;
1436
+ native deltas -0.25, 0.25, -0.3125, 0.125, -0.25, 0.25, each agreeing with the emulated delta
1437
+ within one spacing); the second reads are `causal` 6/6. Cost (medians): a what-if 6.90 s with the
1438
+ emulated chains vs 6.95 s without at `L0.h` and 2.43 s vs 2.40 s at `logits`; `reads t21 top=3`
1439
+ 6.39 s vs 6.12 s (within the run-to-run spread of about 0.5 s).
1440
+
1441
+ Other models: SmolLM2-360M (Llama family), bf16 CUDA: the selfcheck passed with 576 stop probes
1442
+ and 0 mismatches, port step 3.0 ms, stepped against the full forward max |dlogit| 0.28.
1443
+ Llama-3.2-1B (Llama family with `llama3`-scaled RoPE; torch 2.13.0+cu130, transformers 5.13.1):
1444
+ the selfcheck passed in fp32 and in bf16, each with 288 stop probes and 0 mismatches; port step
1445
+ 1.5 ms (fp32) and 1.6 ms (bf16). Stepped against the full forward, max |dlogit| was 1.3e-5 in fp32 and 0.125 in bf16. On
1446
+ the qr/kr ports of layers 0, 8 and 15, the fp32 `explain` remainder (float64 identity with the
1447
+ llama3 frequencies vs native) was at most 3.2e-7 relative. A real Mistral checkpoint was not
1448
+ run.
1449
+
1450
+ The stepped run is bitwise equal to Hugging Face's incremental program (prefill plus one token).
1451
+ Against one full forward over the whole prompt the largest logit difference is 0.25.
1452
+
1453
+ ## Performance
1454
+
1455
+ What a stepped row costs and how that changed in 0.2.1 (measured on a laptop CPU and on
1456
+ Qwen2.5-1.5B on an RTX 4080), the opt-in `lookahead="auto"`, the cost of foreign forward hooks,
1457
+ and the known remaining costs with the planned fixes: [docs/PERFORMANCE.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/PERFORMANCE.md).
1458
+
1459
+ ## Known limits
1460
+
1461
+ Open issues are listed in [CHANGELOG.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/CHANGELOG.md) under "Known issues" (the latest list is
1462
+ in the 0.2.0 section; later releases add none).
1463
+
1464
+ - `attach` needs eager attention, one sequence (batch 1) and frozen weights in eval mode;
1465
+ `trace` has none of these limits but cannot step or edit. Port programs exist for Qwen2,
1466
+ Qwen3, Llama and Mistral (`mdb.engine.ports.FAMILIES`); not gemma or gemma2. Real models run so
1467
+ far: Qwen2.5-1.5B, SmolLM2-360M and Llama-3.2-1B (Llama) and, in the examples, Qwen3-0.6B/1.7B-Base and
1468
+ Qwen2.5-0.5B. A real Mistral checkpoint has not been run.
1469
+ - A checkpoint is bound to its numeric scope (thread count, determinism flag, matmul
1470
+ precision, CUDA reduced-precision reduction flags); restoring under another scope is refused.
1471
+ - Memory: trail marks share the state a step did not change, so a mark costs about what its step
1472
+ wrote (one layer's new K/V row, the hidden state, the logits); `Run.held_bytes()` measures it,
1473
+ and `retain_rows` bounds it further.
1474
+ - Port stepping re-runs the layer from its input for every port. On the tiny qwen2, one layer
1475
+ stepped from `h` to `h_out` made 145 calls against 13 for a plain call; `lookahead="layer"`
1476
+ makes 26, but native code then has computed ports past the cursor
1477
+ (`run.status()["computed_past_cursor"]`); `lookahead="auto"` does that only while nothing is
1478
+ staged for the layer (see [docs/PERFORMANCE.md](https://github.com/JHollenb/saturn/blob/main/packages/mdb/docs/PERFORMANCE.md)).
1479
+ - A stepped run equals Hugging Face's incremental program, not one full forward.
1480
+ - `circuit test` patches components at the consumer's row only: earlier rows (the cache) stay this
1481
+ run's, there is no `rows=all`, a source-row node counts as its head (`p` is not patched), and a
1482
+ vector consumer is refused (the ratios need a scalar).
1483
+ - Running on mrun's native kernels is not supported; Hugging Face models are the supported path.
1484
+ - A port edit acts on the cursor's row only, and prompt rows prefilled in one call have no ports;
1485
+ a replayed (batched-prefill) and a token-by-token run of the same prompt can differ by one bf16
1486
+ step. `prefill=K` and `sweep` address these, see
1487
+ [Prefill split and position patching](#prefill-split-and-position-patching).
1488
+ - After `prefill=K`, `until logits` stops at the logits of the first stepped row, not the last
1489
+ row; name the row (`until t5.logits`).
1490
+ - A cell `whatif` is refused (prediction only; the native measurement runs) when the first
1491
+ affected row has not started at the cursor.
1492
+ - Verdicts: `whatif` and `reads` hold native against the emulated change; the emulated chains are
1493
+ refused when a staged edit lies ahead of the cursor (the verdict is then native only), and a
1494
+ what-if whose chain spans several rows is not stage-checked when native and emulated part
1495
+ (`unresolved`, said so). The accumulation premise is conservative: on bf16 CUDA every bound for
1496
+ sums of 256 or more terms is `bound refused`, although a measurement on an RTX 4080 found the
1497
+ linear stages bitwise equal with the flag on and off. Bounds never decide a verdict.
1498
+ - On MPS (no float64) `whatif` fails with `a numeric claim needs a finite number`; CPU and CUDA are
1499
+ the tested devices.
1500
+ - No dictionary unit of its own (by choice); the unit is a named symbol declared from a transplant
1501
+ result (see [Named symbols](#named-symbols-from-a-transplant)), and SAE features are read from
1502
+ loaded SAE files. Named symbols live in the session: a record stored in a project is not loaded
1503
+ back by name in a new process. A role names the first token of a multi-token word.
1504
+ - With the `mdb-lanes` plug-in installed there are two circuit systems, the lane-era
1505
+ `discover_circuit` (ranks by write norm, picks the attention sink) and the engine's `circuit`;
1506
+ use the engine's.
1507
+ - Every automated test uses a tiny random CPU model; real-model behaviour is checked by hand on the
1508
+ developers' GPU (see [Measured on a real model](#measured-on-a-real-model)).
1509
+
1510
+ ## Not built yet
1511
+
1512
+ - `trace(project=)`.
1513
+ - `mdb serve --model` on a remote GPU machine with the REPL connected through a tunnel has not been
1514
+ run end to end; no port program for FLUX.2 Klein.
1515
+ - gemma and gemma2 port programs; loading a stored named symbol into a new session.
1516
+ - No edits at earlier rows' ports after a batched prefill (use `start prefill=K`).