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,1110 @@
1
+ """The symbol table at the cursor: one row per binding, with definition sites, lifetime, named
2
+ readers and status, and an ``Unbound`` row so the table sums to the whole.
3
+
4
+ A binding is a set of cache cells ``(row, layer, KV head, k|v)``. The engine-native binding is
5
+ a token row ``t<s>``: its value enters the cache at every layer (``t<s>.L*.k``,
6
+ ``t<s>.L*.v``). A user symbol (``declare(run, name, addresses)``) is any set of cells (``t2``,
7
+ ``t2.L0.v``, ``cache.L1.v[kv0,row=2]``); declared symbols must not overlap, and a token row
8
+ holds exactly the cells no declared symbol holds (an explicit cell set), so the bindings
9
+ partition the cells. A read ``(reader row, layer, head, source)`` belongs to the binding that
10
+ holds its value cell ``v``: the value is what the read carries into the head (P06). ``k``
11
+ cells set the weights; a binding of ``k`` cells only receives no read.
12
+
13
+ At the reader rows (the cursor's row by default) each binding gets, from the exact value mix
14
+ (P06/P07, ``analysis.measure.reads``):
15
+
16
+ * ``mass``: the attention weight its reads receive, summed over heads and layers (``count``
17
+ reads, ``mean_mass`` per read); each weight is labelled as ``Run.read_info`` labels it
18
+ (``supplied`` under a ``p``/``s`` edit), the sum ``derived-exact`` (``supplied`` if any part
19
+ is);
20
+ * ``to_consumer``: its exact contribution to the consumer (``derived-exact``): a margin or logit
21
+ (default at ``logits``/``sample``: the margin between the row's two largest logits), a
22
+ residual port, or with no consumer mid-row the norm of each read's share of its layer's ``o``.
23
+ A head whose block of ``A`` (or whose ``o``) an edit wrote does not reach the consumer through
24
+ its value mix: those reads are ``refused`` and so is the binding's total;
25
+ * ``readers``: the top few (row, layer, head) reads by contribution, each with mass and effect;
26
+ * ``lifetime``: a strip per reader row, one mark per layer (``legend``): ``#`` read with mass at
27
+ or above ``min_mass`` (default 0.1, stated), ``.`` read below it, ``-`` the binding holds no
28
+ value cell at that layer, ``?`` not computed;
29
+ * ``status``: ``edited`` (``Run.read_info`` of its ``k``/``v`` says an edit wrote it or an edit
30
+ of its row lies upstream), else ``read`` (some read at or above ``min_mass``), ``live`` (none
31
+ yet and some layer of the reader row has not computed its ``p``), ``unread``.
32
+
33
+ Content (optional, ``sets=``): each binding's write into the reader row, summed over its reads
34
+ (``w_B = sum p[h,s] W_o,h v[kappa(h),s]``, P06/P07), is read through the final-norm readout
35
+ ``rho * gamma * W_U[t]`` (P19, ``rho`` at the native final state of the cursor's row) over
36
+ declared candidate sets (``Candidates``: e.g. countries, capitals, entities): per set the best
37
+ token, its margin over the runner-up and the rank of a declared true token (derived-exact,
38
+ float64), plus the vocabulary top 5 (derived-local, ``sae.logit_lens`` in float32). With
39
+ ``content_layers=True`` a content-lifetime strip per set: per layer of the reader row, ``C``
40
+ when that layer's write names the binding's overall best token, ``c`` when it is in that
41
+ layer's top 3, ``.`` read but naming another, ``-`` no value cell of the binding at that layer.
42
+ ``hops=`` (binding name -> ``{"native_delta", "direct_delta"}``) adds a ``hop`` field: the
43
+ measured native change of the consumer under a replacement of the binding, the change of its
44
+ direct path under the same replacement (derived-exact, from a table on the edited run) and the
45
+ indirect share ``1 - direct_delta / native_delta`` (the part routed through later layers).
46
+
47
+ ``Unbound`` holds, per head, the mass of the bindings not on this page, and the part of the
48
+ consumer no listed binding's reads carry, split into its parts: the embedding, MLP (and head
49
+ bias) terms (``derived-exact``, P19), the attention not listed (the layers' native ``o`` read
50
+ exactly, minus the listed reads), any edit of the residual stream, and the measured remainder
51
+ with its rounding bound (``analysis.circuits.build``). ``accounting`` checks that the bindings
52
+ partition every head's mass (the sum over all bindings equals ``sum_s p``); a broken partition
53
+ is ``refused`` and so is ``Unbound``. With a project the table is sealed as ``symbol-table``
54
+ records, one per page of at most ``PAGE`` bindings.
55
+ """
56
+
57
+ from __future__ import annotations
58
+
59
+ import math
60
+ from dataclasses import dataclass, field
61
+ from typing import Any
62
+
63
+ from mdb.core.kinds import SYMBOL_TABLE, procedure
64
+ from mdb.core.records import RecordError, seal_record
65
+
66
+ from ..measure.readout import (
67
+ claim,
68
+ edited_block,
69
+ first_row,
70
+ head_mix,
71
+ readout,
72
+ refused,
73
+ size,
74
+ unit_roundoff,
75
+ )
76
+ from ..measure.reads import Source, source_label
77
+ from ..numerics.labels import BOUND, EXACT, MEASURED, SUPPLIED, f64, num
78
+ from ..predict.consumers import Margin, Refusal, run_session_id
79
+ from .binding import _PORTS, Binding, Candidates, declared
80
+
81
+ SCHEMA = "mdb-symbol-table-v1"
82
+ PAGE = 16
83
+ STATUSES = ("live", "read", "unread", "edited", "unresolved")
84
+ LEGEND = {"#": "read with mass at or above min_mass", ".": "read below min_mass",
85
+ "-": "no value cell of this binding at that layer", "?": "not computed"}
86
+ _U32 = 2.0 ** -24
87
+ # one line per added column (the full reference: docs/SYMBOL-TABLE-SCHEMA.md)
88
+ COLUMN_NOTES = {
89
+ "contrast": "sum over its reads of p (c.W_O v_s - c.W_O vbar_h): the effect against the "
90
+ "head's own mean value (derived-exact P19)",
91
+ "mask_delta": "sum over its reads of -contrast/(1-p): each read masked alone with "
92
+ "renormalisation, DIRECT path only, every other input held (derived-exact)",
93
+ "share": "to_consumer / consumer_total; share_of_abs divides by |consumer_total|",
94
+ "mass_nonsink": "mass renormalised per head over the non-sink sources (sink rows: "
95
+ "report.sink); mass and to_consumer stay exact",
96
+ "sink_ratio": "t0 only: its value-vector norm over the median row's, median over layers",
97
+ "causal": ("status unknown (observed only) or a measured liveness result "
98
+ "(analysis.symbols.liveness)"),
99
+ "finite": "finite split under an edit of the binding's cells (analysis.symbols.symbol_finite): "
100
+ "routing / payload / interaction credit at each attention output (P07) and the "
101
+ "indirect parts (attention rest, MLP gate / up / interaction, norm, rounding)",
102
+ }
103
+
104
+
105
+ def readout_basis(run: Any, row: int) -> tuple[float, Any]:
106
+ """``(rho, gamma)`` of the final-norm readout at ``row`` (P19): ``rho`` from the native
107
+ final state ``t<row>.L<last>.h_out``, ``gamma`` the final norm gain in float64."""
108
+ adapter = run.adapter
109
+ last = adapter.layers - 1
110
+ h_last = f64(run.read(f"t{row}.L{last}.h_out")).reshape(-1)
111
+ norm = getattr(adapter.backbone, adapter.spec.final_norm)
112
+ rho = float((h_last.pow(2).mean() + float(norm.variance_epsilon)) ** -0.5)
113
+ return rho, f64(norm.weight).reshape(-1)
114
+
115
+
116
+ def _scores(run: Any, write: Any, tokens: tuple[int, ...], basis: tuple[float, Any]) -> Any:
117
+ """``rho * gamma . (W_U[t] * write)`` for the tokens (rows sliced, then cast; float64)."""
118
+ torch = _torch()
119
+ rho, gamma = basis
120
+ weight = run.adapter.model.lm_head.weight
121
+ index = torch.tensor(list(tokens), dtype=torch.long, device=weight.device)
122
+ rows = f64(weight.index_select(0, index)).cpu()
123
+ return rho * (rows * gamma) @ f64(write).reshape(-1)
124
+
125
+
126
+ def content(run: Any, write: Any, sets: list[Candidates], basis: tuple[float, Any], *,
127
+ tokenizer: Any = None, top: int = 5, flags: bool = False) -> dict[str, Any]:
128
+ """The content readout of one binding's write (see the module docstring). ``flags``: add
129
+ ``truth`` and the candidate flags (``candidates.content_flags``) per set."""
130
+ from ..measure.readout import logit_lens
131
+ from .candidates import content_flags
132
+
133
+ out: dict[str, Any] = {}
134
+ for cand in sets:
135
+ if len(cand.tokens) < 2:
136
+ raise Refusal(f"candidate set {cand.name} needs at least two tokens")
137
+ scores = _scores(run, write, cand.tokens, basis)
138
+ order = scores.argsort(descending=True)
139
+ best, second = int(order[0]), int(order[1])
140
+ item: dict[str, Any] = {
141
+ "best": cand.tokens[best],
142
+ "score": num(float(scores[best]), EXACT, "P19"),
143
+ "margin": num(float(scores[best] - scores[second]), EXACT, "P19"),
144
+ "size": len(cand.tokens)}
145
+ if tokenizer is not None:
146
+ item["text"] = tokenizer.decode([cand.tokens[best]])
147
+ if cand.truth is not None and cand.truth in cand.tokens:
148
+ where = cand.tokens.index(cand.truth)
149
+ item["truth_rank"] = int((scores > scores[where]).sum()) + 1
150
+ item["names_truth"] = cand.tokens[best] == cand.truth
151
+ if flags:
152
+ item["truth"] = int(cand.truth)
153
+ if flags:
154
+ item["flags"] = content_flags(cand, cand.tokens[best], sets)
155
+ out[cand.name] = item
156
+ ids = logit_lens(run, write, top=top)
157
+ out["vocab_top"] = {"tokens": ids, "authority": "derived-local",
158
+ "note": "float32 ranking of gamma * write over the vocabulary"}
159
+ if tokenizer is not None:
160
+ out["vocab_top"]["text"] = [tokenizer.decode([i]) for i in ids]
161
+ return out
162
+
163
+
164
+ def _content_strip(run: Any, writes: dict[int, Any], layers: int, cand: Candidates,
165
+ best: int, basis: tuple[float, Any]) -> str:
166
+ marks = []
167
+ for layer in range(layers):
168
+ if layer not in writes:
169
+ marks.append("-")
170
+ continue
171
+ scores = _scores(run, writes[layer], cand.tokens, basis)
172
+ order = [cand.tokens[int(i)] for i in scores.argsort(descending=True)[:3]]
173
+ marks.append("C" if order[0] == best else "c" if best in order else ".")
174
+ return "".join(marks)
175
+
176
+
177
+ def _token_rows(run: Any, here: int, users: list[Binding]) -> list[Binding]:
178
+ """One binding per token row holding exactly the cells no declared symbol holds."""
179
+ layers, kv = run.adapter.layers, run.adapter.num_kv_heads
180
+ out = []
181
+ for s in range(here + 1):
182
+ if any(b.whole(s) for b in users):
183
+ continue
184
+ cells = [(layer, k, port) for layer in range(layers) for k in range(kv)
185
+ for port in _PORTS if not any(b.covers(s, layer, k, port) for b in users)]
186
+ if not cells:
187
+ continue
188
+ if len(cells) == layers * kv * len(_PORTS):
189
+ out.append(Binding(f"t{s}", "token", [Source(s, text=f"t{s}")],
190
+ [f"t{s}.L*.k", f"t{s}.L*.v"]))
191
+ continue
192
+ out.append(Binding(f"t{s}", "token",
193
+ [Source(s, (layer,), (k,), f"cache.L{layer}.{port}[kv{k},row={s}]",
194
+ (port,)) for layer, k, port in cells],
195
+ [f"t{s} (uncovered part: {len(cells)} of "
196
+ f"{layers * kv * len(_PORTS)} k/v cells)"]))
197
+ return out
198
+
199
+
200
+ def _default_consumer(run: Any) -> Margin | None:
201
+ row, stop = run.where.split(".", 1)
202
+ if stop not in ("logits", "sample"):
203
+ return None
204
+ logits = f64(run.read(f"{row}.logits")).reshape(-1)
205
+ first, second = (int(i) for i in logits.topk(2).indices)
206
+ return Margin(int(row[1:]), first, second)
207
+
208
+
209
+ def _status_edits(run: Any, row: int, layers: int, here: tuple[int, int]) -> list[str]:
210
+ """The edits ``Run.read_info`` reports on this row's ``k``/``v`` (own or upstream in the
211
+ row); a prefilled row has none."""
212
+ if row < first_row(run):
213
+ return []
214
+ found: list[str] = []
215
+ for layer in range(layers):
216
+ for port in ("k", "v"):
217
+ address = f"t{row}.L{layer}.{port}"
218
+ if run.parse(address) > here:
219
+ continue
220
+ info = run.read_info(address)
221
+ if info["edited"]:
222
+ found.append(f"{address} ({','.join(info['ops'])})")
223
+ for edit in info["upstream_edits"]:
224
+ if int(edit["row"]) == row:
225
+ found.append(f"t{row}.L{edit['layer']}.{edit['port']} ({edit['op']})")
226
+ return list(dict.fromkeys(found))
227
+
228
+
229
+ @dataclass
230
+ class Table:
231
+ """A symbol table: ``report`` (bounded JSON), ``records`` (sealed, one per page) and the
232
+ float64 ``tensors`` behind it: ``mass[(row, layer)]`` (bindings x heads) with
233
+ ``unbound_mass`` and ``total_mass`` per head, ``contribution`` per binding."""
234
+
235
+ report: dict[str, Any]
236
+ records: list[dict[str, Any]]
237
+ tensors: dict[str, Any] = field(default_factory=dict)
238
+
239
+ def to_frame(self, level: str = "binding", *, item: str | None = None,
240
+ foreign: bool = False) -> Any:
241
+ """A long pandas DataFrame (``analysis.symbols.frame.to_frame``: binding, read or head)."""
242
+ from .frame import to_frame
243
+
244
+ return to_frame(self, level, item=item, foreign=foreign)
245
+
246
+ def to_arrow(self, level: str = "binding", **kw: Any) -> Any:
247
+ from .frame import to_arrow
248
+
249
+ return to_arrow(self.to_frame(level, **kw))
250
+
251
+ def to_parquet(self, path: str, level: str = "binding", **kw: Any) -> str:
252
+ from .frame import to_parquet
253
+
254
+ return to_parquet(self.to_frame(level, **kw), path)
255
+
256
+
257
+ def table(run: Any, *, consumer: Any = None, rows: str | None = None, min_mass: float = 0.1,
258
+ readers: int = 3, offset: int = 0, limit: int = PAGE,
259
+ session_id: str | None = None, tokenizer: Any = None,
260
+ pending: dict[str, dict[str, Any]] | None = None,
261
+ sets: list[Candidates] | None = None, content_layers: bool = False,
262
+ hops: dict[str, dict[str, Any]] | None = None, sink: tuple[int, ...] | None = (0,),
263
+ co: list[Any] | None = None, lexical_null: bool = False,
264
+ switch: dict[str, str] | None = None, labels: dict[str, Any] | None = None,
265
+ derive: dict[str, str] | None = None, foreign: bool = False,
266
+ causal: bool | str = False, min_effect: float = 0.0,
267
+ components: list[Any] | None = None, subspaces: list[Any] | None = None,
268
+ neuronpedia: dict[str, Any] | None = None, store: Any = None,
269
+ finite: Any = None, interactions: list[str] | None = None,
270
+ doses: Any = None, ledger: str | None = None) -> Table:
271
+ """The symbol table at the cursor (see the module docstring); ``offset``/``limit`` page
272
+ the bindings (declared symbols first, then token rows in order). ``pending``: declared
273
+ symbols that cannot be bound on this run yet (name -> ``addresses``, ``reason``), listed
274
+ ``unresolved``.
275
+
276
+ Further columns (``docs/SYMBOL-TABLE-SCHEMA.md`` lists every column):
277
+
278
+ * ``sink``: sink rows for ``mass_nonsink`` (default ``(0,)``: t0; ``None`` or ``()``: off);
279
+ token row 0 also gets ``sink_ratio``. ``contrast``, ``mask_delta`` and ``share`` are added
280
+ under a scalar consumer.
281
+ * ``sets`` built from words (``candidates.CandidateSet.candidates``) add ``truth`` and
282
+ ``flags`` per set; ``lexical_null`` adds the truth token's own readout per set; ``co``
283
+ (``candidates.CoReadout`` items) adds orthogonalised co-readouts with the whole subspace
284
+ of another set removed; ``switch`` (target set -> set it switches on) adds the switched
285
+ readout.
286
+ * ``labels``: item-level labels (name -> value, ``supplied``), reported and attached to
287
+ every binding; ``derive``: label name -> dotted path within a binding row (e.g.
288
+ ``content.countries.best``), a derived label per binding.
289
+ * ``foreign``: TransformerLens / nnsight / pyvene names per binding and per read.
290
+ * ``causal`` (``True``, ``"mask"`` or ``"zero"``): the causal-liveness column
291
+ (``analysis.symbols.liveness``), per binding on this page; without it every binding's
292
+ ``causal`` is ``unknown``.
293
+ * ``subspaces``: ``subspace.SubspaceBinding`` items bound to a row: a ``subspaces`` section
294
+ with basis authority, provenance, digest, the native cell's mass in the subspace, the
295
+ direct consumer share of the in-subspace part (scalar consumer) and attached labels
296
+ (e.g. measured IIA).
297
+ * ``components``: ``components.ComponentBinding`` items (feature bindings): a separate
298
+ ``components`` section with per-feature activation, direct effect, content, SAELens ids
299
+ and Neuronpedia links resolved offline (explicit mapping, basis metadata, then the
300
+ installed SAELens registry).
301
+ * ``finite`` (``"zero"`` or a donor run, scalar consumer): per binding on this page a
302
+ ``finite`` cell (``symbol_finite.split``): its cells edited to zero (or to the donor's),
303
+ the key-cell credit (routing / payload / interaction per attention output) and the
304
+ indirect parts; with a margin the per-layer detail adds the adjoint column.
305
+ * ``interactions``: binding names (2..12): Moebius terms of their joint edits
306
+ (``symbol_finite.interactions``, pairs), under the same edit as ``finite`` (zero by
307
+ default).
308
+ * ``doses``: the ``symbol_runs.DosePolicy`` of the causal column (default: the decision
309
+ envelope, ``symbol_runs.EnvelopeDoses``).
310
+ * ``ledger`` (reader rows ``R``, ``A:B`` or ``all``): ``report.ledger``, one mass scalar per
311
+ binding on this page and reader row (``symbol_runs.lifetime_ledger``, only ``p`` read).
312
+ * A binding with more than 64 rows or definitions keeps the compact form for display and
313
+ its full lists behind ``full`` (a sha256-checked JSON blob in ``store``, else held in
314
+ memory on the run; ``core.bounded.load_json`` reads it).
315
+ """
316
+ from ..measure.reads import reader_rows
317
+
318
+ if not 0 <= min_mass <= 1:
319
+ raise Refusal("min_mass must be in 0..1")
320
+ if not 1 <= limit <= PAGE:
321
+ raise Refusal(f"limit must be in 1..{PAGE}")
322
+ here_key = run.parse(run.where)
323
+ layers = run.adapter.layers
324
+ found_rows = reader_rows(run, Source(0), rows)
325
+ if consumer is None:
326
+ consumer = _default_consumer(run)
327
+ reader = None if consumer is None else readout(run, consumer)
328
+ users = list(declared(run).values())
329
+ bindings = users + _token_rows(run, here_key[0], users)
330
+ n = len(bindings)
331
+ sink = tuple(sink or ())
332
+ grid = _Grid(run, bindings, reader, found_rows, keep_writes=bool(sets), sink=sink)
333
+ names = None
334
+ if foreign:
335
+ names = {"head_dim": run.adapter.head_dim, "kv_heads": run.adapter.num_kv_heads,
336
+ "layers": layers}
337
+ item_labels = {k: label_claim(v) for k, v in (labels or {}).items()}
338
+ entries = [_entry(run, binding, b, grid, reader, found_rows, layers, min_mass, readers,
339
+ here_key, tokenizer, names, item_labels)
340
+ for b, binding in enumerate(bindings)]
341
+ shown = entries[offset:offset + limit]
342
+ if sink and 0 in sink:
343
+ for b in range(offset, min(offset + limit, n)):
344
+ if bindings[b].kind == "token" and bindings[b].cells[0].row == 0:
345
+ entries[b]["view"]["sink_ratio"] = _sink_ratio(run, here_key[0])
346
+ flagged = any(getattr(c, "info", None) is not None for c in (sets or ()))
347
+ if flagged:
348
+ for b in range(offset, min(offset + limit, n)):
349
+ view = entries[b]["view"]
350
+ if "token" in view:
351
+ view["first_subword_of"] = sorted(
352
+ c.name for c in sets if getattr(c, "info", None) is not None
353
+ and c.info.multi_piece(view["token"]))
354
+ if sets:
355
+ basis = readout_basis(run, here_key[0])
356
+ co_spaces = _subspaces(run, sets, co or (), basis)
357
+ for b in range(offset, min(offset + limit, n)):
358
+ per_layer: dict[int, Any] = {}
359
+ for (j, layer), w in grid.write.items():
360
+ if bool(grid.cover[(j, layer)][b].any()):
361
+ per_layer[layer] = per_layer.get(layer, 0) + w[b]
362
+ view = entries[b]["view"]
363
+ if not per_layer:
364
+ view["content"] = {"state": "unresolved", "reason": "no read of this binding"}
365
+ continue
366
+ total = sum(per_layer.values())
367
+ view["content"] = content(run, total, sets, basis, tokenizer=tokenizer,
368
+ flags=flagged or lexical_null or bool(co) or bool(switch))
369
+ view["content"]["meaning"] = ("readout of the binding's write into the reader "
370
+ "row(s), summed over its reads, through rho * gamma * "
371
+ "W_U (P19)")
372
+ _content_extras(run, view["content"], total, sets, basis, co or (), co_spaces,
373
+ lexical_null, switch or {})
374
+ if content_layers:
375
+ view["content_lifetime"] = {
376
+ c.name: _content_strip(run, per_layer, layers, c, view["content"][c.name]["best"],
377
+ basis) for c in sets}
378
+ for b in range(offset, min(offset + limit, n)):
379
+ view = entries[b]["view"]
380
+ hop = (hops or {}).get(view["symbol"])
381
+ if hop is None:
382
+ continue
383
+ native = float(hop["native_delta"])
384
+ direct = float(hop["direct_delta"])
385
+ view["hop"] = {"native_delta": num(native, MEASURED),
386
+ "direct_delta": num(direct, EXACT, "P19"),
387
+ "indirect_share": (num(1.0 - direct / native, MEASURED) if native else
388
+ {"state": "unresolved", "reason": "native delta 0"}),
389
+ "replacement": hop.get("replacement", "supplied by the caller")}
390
+ if hop.get("edge") is not None:
391
+ view["hop"]["edge"] = hop["edge"]
392
+ donor = None if finite in (None, "zero") else finite
393
+ if finite is not None or interactions:
394
+ if reader is None or not reader.scalar:
395
+ raise Refusal("finite= and interactions= need a scalar consumer (a margin or logit)")
396
+ if finite is not None:
397
+ from .symbol_finite import adjoints, compact, split
398
+
399
+ lam = adjoints(run, reader) if isinstance(reader.target, Margin) else None
400
+ for b in range(offset, min(offset + limit, n)):
401
+ entries[b]["view"]["finite"] = compact(
402
+ split(run, bindings[b], reader, donor=donor, through=lam), store=store, run=run)
403
+ for b in range(offset, min(offset + limit, n)):
404
+ view = entries[b]["view"]
405
+ for name, path in (derive or {}).items():
406
+ try:
407
+ from ..numerics.summary import leaf
408
+
409
+ value = leaf(view, path)
410
+ except (KeyError, IndexError, ValueError, TypeError):
411
+ continue
412
+ view.setdefault("labels", {})[name] = label_claim(value, "derived")
413
+ page_bindings = [bindings[b] for b in range(offset, min(offset + limit, n))]
414
+ for binding, b in zip(page_bindings, range(offset, min(offset + limit, n))):
415
+ rows_all = sorted({c.row for c in binding.cells})
416
+ if len(rows_all) > _LIST_CAP or len(binding.addresses) > _LIST_CAP:
417
+ from mdb.core.bounded import put_json
418
+
419
+ entries[b]["view"]["full"] = put_json(
420
+ {"rows": rows_all, "definitions": list(binding.addresses)}, store=store, run=run)
421
+ if causal:
422
+ from .liveness import liveness
423
+
424
+ form = "mask" if causal is True else str(causal)
425
+ found_causal = liveness(run, page_bindings, reader, form=form, min_effect=min_effect,
426
+ doses=doses)
427
+ for b in range(offset, min(offset + limit, n)):
428
+ entries[b]["view"]["causal"] = found_causal[bindings[b].name]
429
+ else:
430
+ from .liveness import UNKNOWN
431
+
432
+ for b in range(offset, min(offset + limit, n)):
433
+ entries[b]["view"]["causal"] = dict(UNKNOWN)
434
+ listed = sorted(range(offset, min(offset + limit, n)))
435
+ keys = sorted(grid.mass)
436
+ unbound_mass = {key: grid.total[key] - grid.mass[key][listed].sum(0) for key in keys}
437
+ report: dict[str, Any] = {
438
+ "where": run.where, "rows": found_rows,
439
+ "consumer": (reader.text if reader is not None else
440
+ "none: per-layer o (norm of each read's share); give consumer= or run "
441
+ "until logits"),
442
+ "min_mass": num(float(min_mass), SUPPLIED),
443
+ "mass_meaning": "a binding's mass is a sum over the heads and layers that read it "
444
+ "(count reads; mean_mass per read)",
445
+ "attribution": "a read (row, layer, head, source) belongs to the binding holding its "
446
+ "value cell v",
447
+ "legend": LEGEND,
448
+ "columns": COLUMN_NOTES,
449
+ "bindings": [e["view"] for e in shown],
450
+ "page": {"offset": offset, "limit": limit, "total": n},
451
+ }
452
+ if pending:
453
+ report["unresolved_symbols"] = [
454
+ {"symbol": name, "kind": "declared", "definitions": item["addresses"],
455
+ "status": "unresolved", "reason": item["reason"]}
456
+ for name, item in sorted(pending.items())][:PAGE]
457
+ broken = grid.partition_error()
458
+ listed_sum = sum((float(grid.mass[k][listed].sum()) for k in keys), 0.0)
459
+ unbound: dict[str, Any] = {
460
+ "symbol": "Unbound",
461
+ "mass": refused(broken) if broken else num(
462
+ sum(float(unbound_mass[k].sum()) for k in keys), EXACT),
463
+ "meaning": "attention mass of the bindings not on this page, per head summed; the "
464
+ "consumer part no listed binding's reads carry, by part",
465
+ }
466
+ contribution = {}
467
+ if broken:
468
+ unbound["readout"] = refused(broken)
469
+ elif reader is not None and reader.scalar:
470
+ listed_effect = sum(entries[b]["contribution"] for b in listed
471
+ if entries[b]["contribution"] is not None)
472
+ unbound["readout"] = num(float(f64(reader.native)) - listed_effect, MEASURED)
473
+ unbound["parts"] = _unbound_parts(run, reader, listed_effect)
474
+ report["consumer_total"] = claim(f64(reader.native), reader.native_authority
475
+ or MEASURED)
476
+ contribution = {b: e["contribution"] for b, e in enumerate(entries)}
477
+ else:
478
+ unbound["readout"] = {"state": "unresolved",
479
+ "reason": "no scalar consumer: the per-layer o shares have no "
480
+ "common total"}
481
+ report["unbound"] = unbound
482
+ report["accounting"] = {
483
+ "heads": sum(int(grid.total[k].numel()) for k in keys),
484
+ "listed_mass": num(listed_sum, EXACT),
485
+ "max_head_deviation": num(grid.deviation, MEASURED),
486
+ "deviation_bound": num(grid.bound, BOUND),
487
+ "partition": refused(broken) if broken else {
488
+ "max_gap": num(grid.gap, EXACT),
489
+ "meaning": "per head, the sum over all bindings of their mass minus sum_s p "
490
+ "(float64 summation order only)"},
491
+ "within_bound": grid.deviation <= grid.bound and not broken,
492
+ "meaning": "per head, bindings + Unbound = sum_s p (native); |sum_s p - 1| against "
493
+ "T u_dtype + 2 T u_f32 (softmax in float32, each weight cast to the dtype)",
494
+ }
495
+ if grid.missing:
496
+ report["not_computed"] = grid.missing[:16]
497
+ if item_labels:
498
+ report["labels"] = item_labels
499
+ if derive:
500
+ report["derived_labels"] = dict(derive)
501
+ if sink:
502
+ report["sink"] = [f"t{r}" for r in sink]
503
+ if sets:
504
+ report["candidate_sets"] = [
505
+ {**c.info.describe(), "truth": c.truth} if getattr(c, "info", None) is not None
506
+ else {"name": c.name, "size": len(c.tokens), "truth": c.truth,
507
+ "source": "token ids"} for c in sets][:PAGE]
508
+ if components:
509
+ report["components"] = [_component_row(run, cb, consumer, sets, tokenizer, neuronpedia)
510
+ for cb in components][:PAGE]
511
+ if subspaces:
512
+ from .subspace import table_row
513
+
514
+ report["subspaces"] = [table_row(run, sb, consumer) for sb in subspaces][:PAGE]
515
+ if interactions:
516
+ from .symbol_finite import interactions as joint
517
+
518
+ by_name = {b.name: b for b in bindings}
519
+ missing = [name for name in interactions if name not in by_name]
520
+ if missing:
521
+ raise Refusal(f"interactions name no binding {missing[0]!r}")
522
+ report["interactions"] = joint(run, [by_name[name] for name in interactions], reader,
523
+ donor=donor)
524
+ if ledger is not None:
525
+ from .symbol_runs import lifetime_ledger
526
+
527
+ report["ledger"] = lifetime_ledger(run, page_bindings, rows=ledger, min_mass=min_mass)
528
+ records = _records(run, report, session_id)
529
+ report["records"] = [r["id"] for r in records]
530
+ tensors = {"mass": grid.mass, "effect": grid.effect, "write": grid.write, "total_mass": grid.total,
531
+ "unbound_mass": unbound_mass, "contribution": contribution,
532
+ "contrast": grid.contrast, "mask_delta": grid.mask_delta,
533
+ "sink_mass": grid.sink_mass, "nonsink_total": grid.nonsink_total,
534
+ "cover": grid.cover, "sources": grid.sources, "supplied": grid.supplied,
535
+ "bindings": [b.name for b in bindings], "listed": listed,
536
+ "binding_objects": bindings}
537
+ return Table(report, records, tensors)
538
+
539
+
540
+ def _sink_ratio(run: Any, here: int) -> dict[str, Any]:
541
+ """Row 0's value norm over the median row's, per layer (mean over KV heads), summarised as
542
+ the median over layers (derived-exact from the cache)."""
543
+ torch = _torch()
544
+ ratios = []
545
+ for layer in range(run.adapter.layers):
546
+ try:
547
+ v = f64(run.read_cache(layer, "v", staged=False))[0, :, :here + 1] # (kv, T, dh)
548
+ except (ValueError, IndexError, RuntimeError):
549
+ continue
550
+ norms = v.norm(dim=-1).mean(0) # (T,)
551
+ if norms.numel() < 2:
552
+ continue
553
+ median = float(norms.median())
554
+ if median > 0:
555
+ ratios.append(float(norms[0]) / median)
556
+ if not ratios:
557
+ return {"state": "unresolved", "reason": "no cache layer with two rows"}
558
+ ratios_t = torch.tensor(ratios, dtype=torch.float64)
559
+ return num(float(ratios_t.median()), EXACT)
560
+
561
+
562
+ def _subspaces(run: Any, sets: list[Candidates], co: Any, basis: tuple[float, Any]) -> dict:
563
+ from .candidates import subspace
564
+
565
+ by_name = {c.name: c for c in sets}
566
+ out = {}
567
+ for spec in co:
568
+ if spec.target not in by_name:
569
+ raise Refusal(f"co-readout target {spec.target} is not a candidate set of the table")
570
+ if spec.project_out is not None:
571
+ if spec.project_out not in by_name:
572
+ raise Refusal(f"co-readout projects out {spec.project_out}, not a candidate set "
573
+ "of the table")
574
+ tokens = by_name[spec.project_out].tokens
575
+ elif spec.tokens:
576
+ tokens = tuple(spec.tokens)
577
+ else:
578
+ raise Refusal("a co-readout names project_out (a set) or tokens")
579
+ out[spec] = subspace(run, tokens, basis[1], spec.k)
580
+ return out
581
+
582
+
583
+ def _content_extras(run: Any, found: dict[str, Any], write: Any, sets: list[Candidates],
584
+ basis: tuple[float, Any], co: Any, subspaces: dict, lexical: bool,
585
+ switch: dict[str, str]) -> None:
586
+ """Lexical nulls, co-readouts and switched readouts of one binding's content."""
587
+ from . import candidates as cands
588
+
589
+ by_name = {c.name: c for c in sets}
590
+ if lexical:
591
+ for c in sets:
592
+ if c.truth is not None and c.truth in c.tokens:
593
+ found[c.name]["lexical_null"] = cands.lexical_null(run, c, c.truth, basis)
594
+ for spec in co:
595
+ target = found[spec.target]
596
+ target.setdefault("co", {})[spec.project_out or "tokens"] = cands.co_readout(
597
+ run, write, by_name[spec.target], subspaces[spec], basis, spec)
598
+ for target, on in switch.items():
599
+ if target not in by_name or on not in by_name:
600
+ raise Refusal(f"switch {target}:{on} names a set the table does not read")
601
+ found[target]["switched"] = cands.switched(
602
+ by_name[target], found[on], by_name[on],
603
+ lambda tokens: _scores(run, write, tokens, basis))
604
+
605
+
606
+ def _component_row(run: Any, cb: Any, consumer: Any, sets: Any, tokenizer: Any,
607
+ neuronpedia: dict[str, Any] | None) -> dict[str, Any]:
608
+ """One feature binding's section row (``components.component_table`` plus names)."""
609
+ from mdb.core.foreign_names import ct_node, neuronpedia_url
610
+
611
+ from .components import component_table
612
+
613
+ if consumer is None:
614
+ consumer = _default_consumer(run)
615
+ row = component_table(run, cb, consumer, sets=sets, tokenizer=tokenizer)
616
+ mass = row.get("mass")
617
+ if isinstance(mass, dict) and "inherited" in mass: # record-safe: a claim holds NUM_KEYS
618
+ row["mass_meaning"] = mass.pop("inherited")
619
+ ref = (cb.basis or {}).get("saelens") or {}
620
+ for entry in row["components"]:
621
+ if entry.get("feature") is None:
622
+ continue
623
+ f = int(entry["feature"])
624
+ entry["saelens"] = {"release": ref.get("release"), "sae_id": ref.get("sae_id"),
625
+ "hook_name": ref.get("hook_name"), "feature": f}
626
+ entry["neuronpedia"] = neuronpedia_url(neuronpedia, ref.get("release"),
627
+ ref.get("sae_id"), f,
628
+ metadata=(cb.basis or {}).get("source"))
629
+ if (cb.basis or {}).get("transcoder"):
630
+ entry["ct_node"] = ct_node(cb.layer, cb.row, f)
631
+ row["kind"] = "feature"
632
+ return row
633
+
634
+
635
+ def _remainder_bound(rest: Any) -> dict[str, Any]:
636
+ """The remainder's rounding bound, or a refused bound when its premise fails (no number)."""
637
+ if rest.bound is None:
638
+ return {"bound": {"state": "refused", "reason": "the rounding bound's accumulation "
639
+ "premise fails on this run (see `explain`)"}, "within": None}
640
+ return {"bound": num(float(rest.bound), BOUND), "within": bool(rest.within)}
641
+
642
+
643
+ def _unbound_parts(run: Any, reader: Any, listed_effect: float) -> dict[str, Any]:
644
+ """The consumer minus the listed bindings' reads, by part (see the module docstring)."""
645
+ from ..circuits.build import terms, top_gap
646
+
647
+ listed = terms(run, reader, 1, 1)
648
+ native = float(f64(reader.native))
649
+ attention = sum(float(t.value) for t in listed if t.kind == "attn")
650
+ other = sum(float(t.value) for t in listed if t.kind != "attn")
651
+ tail = top_gap(run, reader, f64(native - attention - other))
652
+ edits = [t for t in tail if t.kind == "edit"]
653
+ rest = tail[-1]
654
+ parts: dict[str, Any] = {
655
+ "embedding_mlp": num(other, EXACT, "P19"),
656
+ "attention_not_listed": num(attention - listed_effect, EXACT, "P19"),
657
+ "remainder": {"value": num(float(rest.value), MEASURED), **_remainder_bound(rest)},
658
+ "meaning": "embedding, MLP and head-bias terms; the layers' attention output (native o, "
659
+ "read exactly) minus the listed reads (reads of bindings off this page, "
660
+ "heads an edit wrote, o_proj rounding); residual-stream edits; the measured "
661
+ "remainder (residual-add, final-norm and head rounding) with its bound",
662
+ }
663
+ if edits:
664
+ labels = {t.authority for t in edits}
665
+ parts["residual_edits"] = num(sum(float(t.value) for t in edits),
666
+ SUPPLIED if SUPPLIED in labels else EXACT)
667
+ return parts
668
+
669
+
670
+ class _Grid:
671
+ """Per (reader row, layer): each binding's mass, effect and reads per head, from the value
672
+ mix; reads are owned by the binding holding their value cell."""
673
+
674
+ def __init__(self, run: Any, bindings: list[Binding], reader: Any, rows: list[int], *,
675
+ keep_writes: bool = False, sink: tuple[int, ...] = ()):
676
+ torch = _torch()
677
+ self.sink = tuple(int(s) for s in sink)
678
+ # scalar consumer only: per binding and head, the contrast-form effect and the
679
+ # direct-path mask prediction; per binding and head the mass from sink rows
680
+ self.contrast: dict[tuple[int, int], Any] = {}
681
+ self.mask_delta: dict[tuple[int, int], Any] = {}
682
+ self.sink_mass: dict[tuple[int, int], Any] = {}
683
+ self.nonsink_total: dict[tuple[int, int], Any] = {}
684
+ self.write: dict[tuple[int, int], Any] = {} # (row, layer) -> (bindings, d), on request
685
+ n, heads, layers = len(bindings), run.adapter.num_heads, run.adapter.layers
686
+ self.mass: dict[tuple[int, int], Any] = {}
687
+ self.effect: dict[tuple[int, int], Any] = {}
688
+ self.total: dict[tuple[int, int], Any] = {}
689
+ self.reach: dict[tuple[int, int], str | None] = {}
690
+ self.cover: dict[tuple[int, int], Any] = {}
691
+ self.sources: dict[tuple[int, int], Any] = {}
692
+ self.supplied: dict[tuple[int, int], Any] = {}
693
+ self.blocked: dict[tuple[int, int], dict[int, str]] = {}
694
+ self.missing: list[str] = []
695
+ self.owners: list[str] = []
696
+ self.deviation = self.bound = self.gap = self.tolerance = 0.0
697
+ weights: dict[int, Any] = {} # float64 o_proj by layer, cast once for all rows
698
+ for j in rows:
699
+ for layer in range(layers):
700
+ try:
701
+ mix = head_mix(run, j, layer, weights, lazy=True)
702
+ except Refusal as error:
703
+ self.missing.append(f"t{j}.L{layer}: {error}")
704
+ continue
705
+ key = (j, layer)
706
+ count = mix.p.shape[1]
707
+ scalar = reader is not None and reader.scalar
708
+ # per-read shares: the scalar readout's share (H, T) without building the
709
+ # (H, T, d) tensor, else the o parts themselves
710
+ parts = mix.scalar_parts(reader.vector) if scalar else mix.o_parts()
711
+ owner = [self._owners(bindings, count, layer, kv)
712
+ for kv in range(run.adapter.num_kv_heads)]
713
+ edited_p = run.read_info(f"t{j}.L{layer}.p")["kind"] != "native"
714
+ m = torch.zeros(n, heads, dtype=torch.float64)
715
+ cover = torch.zeros(n, heads, dtype=torch.bool)
716
+ sources = torch.zeros(n, heads, dtype=torch.int64)
717
+ supplied = torch.zeros(n, heads, dtype=torch.bool)
718
+ width = () if reader is None or scalar else (parts.shape[-1],)
719
+ e = torch.zeros(n, heads, *width, dtype=torch.float64)
720
+ why = None if reader is None else (reader.reaches(layer, "attn") or (
721
+ None if reader.row == j else f"{reader.text} is in another row"))
722
+ blocked = {}
723
+ # each binding's (d,) write into the row (content readouts): the o parts,
724
+ # built only when asked for (the scalar path never builds them otherwise)
725
+ full = (parts if not scalar else mix.o_parts()) if keep_writes else None
726
+ total_write = (torch.zeros(n, full.shape[-1], dtype=torch.float64)
727
+ if keep_writes else None)
728
+ con = torch.zeros(n, heads, dtype=torch.float64) if scalar else None
729
+ mdel = torch.zeros(n, heads, dtype=torch.float64) if scalar else None
730
+ sinkm = torch.zeros(n, heads, dtype=torch.float64)
731
+ den = torch.zeros(heads, dtype=torch.float64)
732
+ sink_rows = [s for s in self.sink if s < count]
733
+ is_sink = torch.zeros(count, dtype=torch.bool)
734
+ if sink_rows:
735
+ is_sink[sink_rows] = True
736
+ for h in range(heads):
737
+ reason = edited_block(mix, run, h)
738
+ if reason:
739
+ blocked[h] = reason
740
+ index = owner[mix.kappa[h]]
741
+ held = index >= 0
742
+ idx = index[held]
743
+ m[:, h] = torch.zeros(n, dtype=torch.float64).index_add_(
744
+ 0, idx, mix.p[h][held])
745
+ tally = torch.bincount(idx, minlength=n)
746
+ sources[:, h] = tally
747
+ cover[:, h] = tally > 0
748
+ share = torch.zeros(n, *parts.shape[2:], dtype=torch.float64).index_add_(
749
+ 0, idx, parts[h][held])
750
+ if total_write is not None:
751
+ total_write.index_add_(0, idx, full[h][held])
752
+ if edited_p:
753
+ for s in held.nonzero().reshape(-1).tolist():
754
+ if source_label(run, mix, h, s) == SUPPLIED:
755
+ supplied[int(index[s]), h] = True
756
+ ph = mix.p[h]
757
+ in_sink = held & is_sink
758
+ sinkm[:, h] = torch.zeros(n, dtype=torch.float64).index_add_(
759
+ 0, index[in_sink], ph[in_sink])
760
+ den[h] = ph.sum() - ph[is_sink].sum()
761
+ if reader is None:
762
+ e[:, h] = torch.where(cover[:, h], share.norm(dim=-1), 0.0)
763
+ elif why is None and h not in blocked:
764
+ if scalar:
765
+ e[:, h] = torch.where(cover[:, h], share, 0.0)
766
+ # contrast p_s (x_s - xbar_h) = parts_s - p_s sum_s' parts_s'
767
+ c_all = parts[h] - ph * parts[h].sum()
768
+ con[:, h] = torch.zeros(n, dtype=torch.float64).index_add_(
769
+ 0, idx, c_all[held])
770
+ mdel[:, h] = torch.zeros(n, dtype=torch.float64).index_add_(
771
+ 0, idx, (-c_all / (1 - ph))[held])
772
+ else:
773
+ e[:, h] = torch.where(cover[:, h, None], share, 0.0)
774
+ self.mass[key], self.cover[key], self.effect[key] = m, cover, e
775
+ self.sink_mass[key], self.nonsink_total[key] = sinkm, den
776
+ if scalar:
777
+ self.contrast[key], self.mask_delta[key] = con, mdel
778
+ if total_write is not None:
779
+ self.write[key] = total_write
780
+ self.sources[key], self.supplied[key] = sources, supplied
781
+ self.reach[key], self.blocked[key] = why, blocked
782
+ self.total[key] = mix.p.sum(1)
783
+ self.deviation = max(self.deviation, float((mix.p.sum(1) - 1).abs().max()))
784
+ self.bound = max(self.bound, count * unit_roundoff(mix.dtype) + 2 * count * _U32)
785
+ self.gap = max(self.gap, float((m.sum(0) - mix.p.sum(1)).abs().max()))
786
+ self.tolerance = max(self.tolerance, 4 * count * 2.0 ** -53
787
+ * float(mix.p.abs().sum(1).max()))
788
+
789
+ def _owners(self, bindings: list[Binding], count: int, layer: int, kv: int) -> Any:
790
+ """The binding holding each value cell ``cache.L<layer>.v[kv<kv>,row=s]``, ``s <
791
+ count`` (-1: none); a cell held by zero or several bindings is listed in ``owners``."""
792
+ torch = _torch()
793
+ held: list[list[int]] = [[] for _ in range(count)]
794
+ for b, binding in enumerate(bindings):
795
+ for row in {c.row for c in binding.cells}:
796
+ if row < count and binding.covers(row, layer, kv, "v"):
797
+ held[row].append(b)
798
+ out = torch.full((count,), -1, dtype=torch.int64)
799
+ for s, found in enumerate(held):
800
+ if len(found) != 1:
801
+ self.owners.append(f"cache.L{layer}.v[kv{kv},row={s}] is held by "
802
+ f"{len(found)} bindings")
803
+ if found:
804
+ out[s] = found[0]
805
+ return out
806
+
807
+ def partition_error(self) -> str | None:
808
+ """Why the bindings do not partition the heads' mass, or None."""
809
+ if self.owners:
810
+ return "the bindings do not partition the value cells: " + self.owners[0]
811
+ if self.gap > self.tolerance:
812
+ return (f"per head the bindings' mass differs from sum_s p by {self.gap:.3g} "
813
+ f"(> {self.tolerance:.3g}, float64 summation)")
814
+ return None
815
+
816
+
817
+ def _torch():
818
+ import torch
819
+
820
+ return torch
821
+
822
+
823
+ def _entry(run, binding, b, grid, reader, found_rows, layers, min_mass, readers, here_key,
824
+ tokenizer, foreign=None, item_labels=None) -> dict[str, Any]:
825
+ """One binding's row of the table (``view``) and its float64 contribution (None when an
826
+ edit blocks one of its reads)."""
827
+ strips, first, last = [], None, None
828
+ total_mass, count, supplied = 0.0, 0, False
829
+ contrast_sum, mask_sum, nonsink, nonsink_ok = 0.0, 0.0, 0.0, True
830
+ contribution: float | None = 0.0
831
+ blocked_by = None
832
+ scalar = reader is not None and reader.scalar
833
+ reads = []
834
+ for j in found_rows:
835
+ marks = []
836
+ for layer in range(layers):
837
+ key = (j, layer)
838
+ if key not in grid.mass:
839
+ marks.append("?")
840
+ continue
841
+ covered = grid.cover[key][b]
842
+ if not bool(covered.any()):
843
+ marks.append("-")
844
+ continue
845
+ m = grid.mass[key][b]
846
+ total_mass += float(m.sum())
847
+ if grid.sink:
848
+ den = grid.nonsink_total[key]
849
+ own = m - grid.sink_mass[key][b]
850
+ live = covered & (own != 0)
851
+ if bool((den[live] <= 0).any()):
852
+ nonsink_ok = False
853
+ elif bool(live.any()):
854
+ nonsink += float((own[live] / den[live]).sum())
855
+ count += int(covered.sum())
856
+ supplied = supplied or bool(grid.supplied[key][b].any())
857
+ above = bool((m[covered] >= min_mass).any())
858
+ marks.append("#" if above else ".")
859
+ if above:
860
+ first = first or f"t{j}.L{layer}"
861
+ last = f"t{j}.L{layer}"
862
+ e = grid.effect[key][b]
863
+ for h in range(len(covered)):
864
+ if not covered[h]:
865
+ continue
866
+ reason = grid.blocked[key].get(h)
867
+ value = e[h]
868
+ if reason and reader is not None:
869
+ shown, rank = refused(reason), -1.0
870
+ if scalar and grid.reach[key] is None:
871
+ blocked_by = blocked_by or reason
872
+ elif scalar and grid.reach[key] is not None:
873
+ shown, rank = refused(grid.reach[key]), -1.0
874
+ elif reader is None:
875
+ shown, rank = {"norm": num(float(value), EXACT, "P07")}, float(value)
876
+ else:
877
+ shown = claim(value, EXACT, "P19" if reader.scalar else "P07")
878
+ rank = size(value)
879
+ if scalar:
880
+ contribution += float(value)
881
+ contrast_sum += float(grid.contrast[key][b, h])
882
+ mask_sum += float(grid.mask_delta[key][b, h])
883
+ label = (SUPPLIED if grid.supplied[key][b, h] else
884
+ MEASURED if int(grid.sources[key][b, h]) == 1 else EXACT)
885
+ read = {"name": f"t{j}.L{layer}.h{h}", "mass": num(float(m[h]), label),
886
+ "effect": shown}
887
+ if scalar and key in grid.contrast and not (reason and reader is not None) \
888
+ and grid.reach[key] is None:
889
+ read["contrast"] = num(float(grid.contrast[key][b, h]), EXACT, "P19")
890
+ if foreign is not None:
891
+ from mdb.core.foreign_names import read_names
892
+
893
+ read["foreign"] = read_names(j, layer, h)
894
+ reads.append((rank, read))
895
+ strips.append(f"t{j}:{''.join(marks)}")
896
+ reads.sort(key=lambda r: -r[0])
897
+ edits = []
898
+ for row in sorted({c.row for c in binding.cells}):
899
+ edits += _status_edits(run, row, layers, here_key)
900
+ pending = any(c == "?" for strip in strips for c in strip.split(":", 1)[1])
901
+ if edits:
902
+ status = "edited"
903
+ elif first is not None:
904
+ status = "read"
905
+ elif pending:
906
+ status = "live"
907
+ else:
908
+ status = "unread"
909
+ label = SUPPLIED if supplied else EXACT
910
+ view: dict[str, Any] = {
911
+ "symbol": binding.name, "kind": binding.kind,
912
+ "rows": _compact_rows(sorted({c.row for c in binding.cells})),
913
+ "definitions": _compact_list(binding.addresses),
914
+ "lifetime": {"strip": " ".join(strips), "first": first, "last": last},
915
+ "mass": num(total_mass, label),
916
+ "count": count,
917
+ "mean_mass": (num(total_mass / count, label) if count else
918
+ {"state": "unresolved", "reason": "no read of this binding"}),
919
+ "readers": [r[1] for r in reads[:readers]],
920
+ "status": status,
921
+ }
922
+ if binding.kind == "token":
923
+ row = binding.cells[0].row
924
+ token = _token_at(run, row)
925
+ view["position"] = row
926
+ view["is_sink"] = row in grid.sink
927
+ if token is not None:
928
+ view["token"] = token
929
+ if tokenizer is not None:
930
+ view["text"] = tokenizer.decode([token])
931
+ view.update(token_meta(run, row, tokenizer))
932
+ if blocked_by is not None:
933
+ contribution = None
934
+ view["to_consumer"] = refused(blocked_by)
935
+ elif scalar:
936
+ view["to_consumer"] = num(contribution, EXACT, "P19")
937
+ view["contrast"] = num(contrast_sum, EXACT, "P19")
938
+ if math.isfinite(mask_sum):
939
+ view["mask_delta"] = num(mask_sum, EXACT, "P19")
940
+ else:
941
+ view["mask_delta"] = refused("a read has p = 1: masking its only source does not "
942
+ "renormalise")
943
+ native = reader.native
944
+ if native is not None and float(f64(native)) != 0.0:
945
+ total = float(f64(native))
946
+ view["share"] = num(contribution / total, EXACT)
947
+ view["share_of_abs"] = num(contribution / abs(total), EXACT)
948
+ else:
949
+ contribution = None
950
+ view["to_consumer"] = {"state": "unresolved", "reason": "no scalar consumer"}
951
+ if grid.sink:
952
+ if not nonsink_ok:
953
+ view["mass_nonsink"] = refused("a head reads only sink rows (no non-sink mass)")
954
+ else:
955
+ view["mass_nonsink"] = num(nonsink, label)
956
+ if binding.slot is not None:
957
+ view["slot"] = binding.slot
958
+ view["role"] = binding.role
959
+ if binding.map_digest is not None:
960
+ view["map_digest"] = binding.map_digest
961
+ if binding.labels or item_labels:
962
+ view["labels"] = {**(item_labels or {}),
963
+ **{k: label_claim(v) for k, v in binding.labels.items()}}
964
+ if foreign is not None:
965
+ from mdb.core.foreign_names import binding_names
966
+
967
+ view["foreign"] = binding_names(binding.cells, **foreign)
968
+ if edits:
969
+ view["edited_by"] = edits[:8]
970
+ if len(reads) > readers:
971
+ view["omitted"] = len(reads) - readers
972
+ return {"view": view, "contribution": contribution}
973
+
974
+
975
+ _SPECIAL = ("<|", "<s>", "</s>", "<pad>", "<unk>")
976
+
977
+
978
+ def token_meta(run: Any, row: int, tokenizer: Any) -> dict[str, Any]:
979
+ """Per-row token metadata (structural, from the tokenizer): ``token_class``
980
+ (``special``, ``bos_or_t0``, ``whitespace``, ``punct``, ``digit``, ``word_initial`` or
981
+ ``continuation``) and ``pieces_of_word`` (index of this piece within its whitespace-delimited
982
+ word, and the word's piece count). Without a tokenizer only ``bos_or_t0`` is known."""
983
+ if row == 0:
984
+ cls = "bos_or_t0"
985
+ elif tokenizer is None:
986
+ return {}
987
+ else:
988
+ cls = _token_class(tokenizer.decode([_token_at(run, row)]))
989
+ out: dict[str, Any] = {"token_class": cls}
990
+ if tokenizer is None:
991
+ return out
992
+ texts = [tokenizer.decode([_token_at(run, r)]) for r in range(max(0, row - 32),
993
+ row + 1)]
994
+ start = len(texts) - 1
995
+ while start > 0 and not texts[start][:1].isspace() and _word_piece(texts[start]):
996
+ start -= 1
997
+ index = len(texts) - 1 - start
998
+ end, pieces = row, index + 1
999
+ while True:
1000
+ nxt = _token_at(run, end + 1) if end + 1 < len(run.tokens) else None
1001
+ if nxt is None:
1002
+ break
1003
+ text = tokenizer.decode([nxt])
1004
+ if text[:1].isspace() or not _word_piece(text):
1005
+ break
1006
+ end, pieces = end + 1, pieces + 1
1007
+ out["pieces_of_word"] = {"index": index, "count": pieces}
1008
+ return out
1009
+
1010
+
1011
+ def _word_piece(text: str) -> bool:
1012
+ return bool(text) and any(ch.isalnum() for ch in text)
1013
+
1014
+
1015
+ def _token_class(text: str) -> str:
1016
+ if any(text.startswith(p) for p in _SPECIAL):
1017
+ return "special"
1018
+ if not text.strip():
1019
+ return "whitespace"
1020
+ body = text.strip()
1021
+ if body.isdigit():
1022
+ return "digit"
1023
+ if not any(ch.isalnum() for ch in body):
1024
+ return "punct"
1025
+ return "word_initial" if text[:1].isspace() else "continuation"
1026
+
1027
+
1028
+ def label_claim(value: Any, authority: str = SUPPLIED) -> dict[str, Any]:
1029
+ """A label as a record leaf: a number is a claim ``{value, authority}``; any other value
1030
+ is ``{label, source}`` (``source``: ``supplied`` or ``derived``). ``value`` may already be
1031
+ such a leaf, or a ``(value, authority)`` pair."""
1032
+ if isinstance(value, dict) and ("label" in value or "value" in value):
1033
+ return dict(value)
1034
+ if isinstance(value, tuple) and len(value) == 2:
1035
+ value, authority = value
1036
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
1037
+ return num(value, authority if authority in (SUPPLIED, EXACT, MEASURED, BOUND,
1038
+ "derived-local") else EXACT)
1039
+ return {"label": value, "source": "derived" if authority == "derived" else str(authority)}
1040
+
1041
+
1042
+ _LIST_CAP = 64 # records hold lists of at most 64 items (core.pointers)
1043
+
1044
+
1045
+ def _compact_rows(rows: list[int]) -> list[Any]:
1046
+ """The rows as given when there are at most ``_LIST_CAP``; else half-open ranges ``"a:b"``
1047
+ (a long span such as a whole chain of thought is a few ranges, not thousands of ids)."""
1048
+ if len(rows) <= _LIST_CAP:
1049
+ return rows
1050
+ ranges, start = [], rows[0]
1051
+ for prev, cur in zip(rows, rows[1:] + [None]):
1052
+ if cur != prev + 1 if cur is not None else True:
1053
+ ranges.append(f"{start}:{prev + 1}")
1054
+ start = cur
1055
+ if len(ranges) > _LIST_CAP:
1056
+ ranges = ranges[:_LIST_CAP - 1] + [f"... +{len(ranges) - _LIST_CAP + 1} more ranges"]
1057
+ return ranges
1058
+
1059
+
1060
+ def _compact_list(items: list[str]) -> list[str]:
1061
+ """At most ``_LIST_CAP`` items: the first ones and a count of the rest."""
1062
+ if len(items) <= _LIST_CAP:
1063
+ return items
1064
+ return items[:_LIST_CAP - 1] + [f"... +{len(items) - _LIST_CAP + 1} more"]
1065
+
1066
+
1067
+ def _token_at(run: Any, row: int) -> int | None:
1068
+ if row < len(run.tokens):
1069
+ return int(run.tokens[row])
1070
+ held = run.session.read("tokens")[0]
1071
+ return int(held[row]) if row < held.numel() else None
1072
+
1073
+
1074
+ def _records(run: Any, report: dict[str, Any], session_id: str | None) -> list[dict[str, Any]]:
1075
+ """The table sealed as one ``symbol-table`` record (this page)."""
1076
+ body = {"schema": SCHEMA, **{k: report[k] for k in ("where", "consumer", "rows", "min_mass",
1077
+ "bindings", "unbound", "page",
1078
+ "accounting")}}
1079
+ for key in ("labels", "derived_labels", "candidate_sets", "components", "subspaces",
1080
+ "interactions", "ledger"):
1081
+ if key in report:
1082
+ body[key] = report[key]
1083
+ if "consumer_total" in report:
1084
+ body["consumer_total"] = report["consumer_total"]
1085
+ body["procedure"] = procedure(run)
1086
+
1087
+ def seal() -> dict[str, Any]:
1088
+ return seal_record(session_id=session_id or run_session_id(run), kind="symbol-table",
1089
+ model_identity=run.adapter.model_identity,
1090
+ execution=dict(run.adapter.execution), authority=EXACT, body=body, run=run)
1091
+
1092
+ try:
1093
+ return [seal()]
1094
+ except RecordError:
1095
+ if not body.get("components"):
1096
+ raise
1097
+ # a feature binding of a k=50 SAE (about 50 rows with content) exceeds the record bound:
1098
+ # each section keeps its totals and partition, its rows go behind a sha256 pointer
1099
+ # (``core.bounded.load_json``); ``report["components"]`` keeps every row
1100
+ from mdb.core.bounded import put_json
1101
+
1102
+ body["components"] = [
1103
+ {**{k: v for k, v in section.items() if k != "components"},
1104
+ "components_full": put_json(section.get("components", []), run=run)}
1105
+ for section in body["components"]]
1106
+ return [seal()]
1107
+
1108
+
1109
+ __all__ = ["LEGEND", "content", "readout_basis", "PAGE", "STATUSES", "SYMBOL_TABLE", "Table",
1110
+ "table"]