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,451 @@
1
+ """Long-frame export of symbol tables, circuit maps and traces, with a published JSON Schema.
2
+
3
+ ``to_frame(table, level=...)`` turns a ``symbols.Table`` into a long pandas DataFrame:
4
+
5
+ * ``binding``: one row per listed binding, every field of the table row flattened to dotted
6
+ columns (``content.countries.best``); a labelled number becomes its value column plus an
7
+ ``<column>__auth`` column holding its authority label; lists become JSON text. Each row also
8
+ carries ``item``, ``where``, ``consumer``, ``model_identity`` and ``record_id`` (the sealed
9
+ record the numbers came from: the record stays the authority, the frame is a view).
10
+ * ``read``: one row per (binding, reader row, layer, head) read, from the float64 tensors:
11
+ ``mass``, ``effect`` (scalar consumer), ``contrast``, ``mask_delta``, ``sources`` (value
12
+ cells of the binding read by the head), ``supplied``, and with ``foreign=True`` the
13
+ TransformerLens / nnsight names of the read.
14
+ * ``head``: one row per (reader row, layer, head): ``total_mass`` and ``unbound_mass``.
15
+
16
+ ``to_arrow``/``to_parquet`` keep the schema name and record id in the Arrow schema metadata;
17
+ ``from_frame`` re-imports a binding frame read-only (labelled numbers rebuilt from the
18
+ ``__auth`` columns), so an analysis notebook needs no model. ``trace_frame`` flattens a
19
+ ``rows.Trace`` (one row per step, a column per table entry), ``map_frame`` the per-item rows of
20
+ a circuit map's reports.
21
+
22
+ ``COLUMNS`` is the column reference (name, type, authority, meaning) that ``json_schema`` and
23
+ ``docs/SYMBOL-TABLE-SCHEMA.md`` are generated from.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import numbers
30
+ from typing import Any
31
+
32
+ AUTH = "__auth"
33
+ SCHEMAS = ("mdb-symbol-table-v1", "mdb-circuit-map-v1", "mdb-trace-v1")
34
+
35
+ # (column, JSON type, authority, meaning). ``claim``: a labelled number {value, authority}.
36
+ COLUMNS: list[tuple[str, str, str, str]] = [
37
+ ("symbol", "string", "structural", "the binding's name (a declared symbol, a slot, or t<row>)"),
38
+ ("kind", "string", "structural", "declared, token, or component"),
39
+ ("rows", "array", "structural", "source rows; half-open ranges a:b past 64 rows"),
40
+ ("definitions", "array", "structural", "the addresses that define it (first 64, then a count)"),
41
+ ("lifetime.strip", "string", "derived", "per reader row, one mark per layer: # read at or "
42
+ "above min_mass, . below, - no value cell there, ? not computed"),
43
+ ("lifetime.first", "string", "derived", "first t<j>.L<l> read at or above min_mass"),
44
+ ("lifetime.last", "string", "derived", "last t<j>.L<l> read at or above min_mass"),
45
+ ("mass", "claim", "derived-exact (supplied under a p/s edit)",
46
+ "attention weight its reads receive, summed over heads and layers"),
47
+ ("count", "integer", "structural", "number of (row, layer, head) reads"),
48
+ ("mean_mass", "claim", "derived-exact", "mass per read"),
49
+ ("readers", "array", "mass exact or measured; effect derived-exact P19",
50
+ "top reads {name t<j>.L<l>.h<h>, mass, effect, contrast, foreign}"),
51
+ ("status", "string", "derived", "edited, read, live, unread (unresolved: pending symbol)"),
52
+ ("token", "integer", "structural", "token rows: the token id"),
53
+ ("text", "string", "structural", "token rows: the decoded text (with a tokenizer)"),
54
+ ("position", "integer", "structural", "token rows: the row index"),
55
+ ("is_sink", "boolean", "structural", "token rows: the row is a declared sink row"),
56
+ ("token_class", "string", "structural (tokenizer)", "special, bos_or_t0, whitespace, "
57
+ "punct, digit, word_initial or continuation"),
58
+ ("pieces_of_word.index", "integer", "structural (tokenizer)",
59
+ "index of the piece within its whitespace-delimited word"),
60
+ ("pieces_of_word.count", "integer", "structural (tokenizer)", "pieces in that word"),
61
+ ("first_subword_of", "array", "derived-exact (tokenizer)",
62
+ "candidate sets in which this row's token is the first piece of a multi-piece word"),
63
+ ("to_consumer", "claim", "derived-exact P19",
64
+ "exact direct contribution to the scalar consumer (share form: sum p c.W_O v_s)"),
65
+ ("contrast", "claim", "derived-exact P19",
66
+ "sum over its reads of p (c.W_O v_s - c.W_O vbar_h): the effect against the head's own "
67
+ "mean value (vbar_h = sum_s p v_s)"),
68
+ ("mask_delta", "claim", "derived-exact P19, direct path only",
69
+ "sum over its reads of -contrast/(1-p): each read masked alone with renormalisation, "
70
+ "every other input held; not the native mask effect (FT1: within 2 bf16 spacings on "
71
+ "6/32 items)"),
72
+ ("share", "claim", "derived-exact", "to_consumer / consumer_total (flips sign with the "
73
+ "margin)"),
74
+ ("share_of_abs", "claim", "derived-exact", "to_consumer / |consumer_total|"),
75
+ ("mass_nonsink", "claim", "derived-exact",
76
+ "mass renormalised per head over non-sink sources (sink rows: report.sink, default t0)"),
77
+ ("sink_ratio", "claim", "derived-exact", "t0 only: its value norm over the median row's, "
78
+ "median over layers"),
79
+ ("role", "string", "structural", "the circuit-map role of the slot that bound it"),
80
+ ("slot", "string", "structural", "the circuit-map slot that bound it"),
81
+ ("map_digest", "string", "structural", "sha256 of the map whose slot bound it"),
82
+ ("labels.<name>", "claim or {value, authority}", "supplied, or derived (with from)",
83
+ "item labels (family, depth, country) and derived labels (decoded_country = "
84
+ "content.countries.best)"),
85
+ ("causal.status", "string", "structural", "unknown (observed only) or intervened"),
86
+ ("causal.verdict", "string", "measured", "effect, null or below_floor"),
87
+ ("causal.delta", "claim", "measured", "native consumer change with the consumer row's reads "
88
+ "of the binding removed (p = 0, no renormalisation) at every layer and head"),
89
+ ("causal.floor", "claim", "measured", "|null arm - the run's stepped consumer|"),
90
+ ("causal.doses", "object", "measured; envelope derived-exact on the secant path",
91
+ "the doses a DosePolicy picked (default the decision envelope): per dose the native "
92
+ "consumer, delta from the null arm, greedy winner, the envelope's predicted winner and "
93
+ "agrees; the envelope segments (derived-local as a forecast of the native dose path)"),
94
+ ("content.<set>.best", "integer", "derived-exact P19", "best token of the set for the "
95
+ "binding's write"),
96
+ ("content.<set>.score", "claim", "derived-exact P19", "its readout rho gamma.W_U[t].w"),
97
+ ("content.<set>.margin", "claim", "derived-exact P19", "best minus runner-up"),
98
+ ("content.<set>.truth", "integer", "supplied", "the declared true token"),
99
+ ("content.<set>.truth_rank", "integer", "derived-exact", "1-based rank of the truth"),
100
+ ("content.<set>.names_truth", "boolean", "derived-exact", "best == truth"),
101
+ ("content.<set>.flags.first_subword", "boolean", "derived-exact (tokenizer)",
102
+ "best is the first piece of a multi-piece word of the set"),
103
+ ("content.<set>.flags.collision", "boolean", "derived-exact (tokenizer)",
104
+ "best stands for more than one word of the set"),
105
+ ("content.<set>.flags.kind", "array", "derived-exact (tokenizer)",
106
+ "other declared sets that hold the best token"),
107
+ ("content.<set>.lexical_null.names_truth", "boolean", "derived-exact P19",
108
+ "the truth token's own unembedding read through the same basis names the truth"),
109
+ ("content.<set>.co.<other>.projected.names_truth", "boolean",
110
+ "derived-exact P19; projection supplied", "readout with the whole span of <other>'s "
111
+ "gamma W_U rows removed from the write"),
112
+ ("content.<set>.co.<other>.lexical_null.names_truth", "boolean", "derived-exact P19",
113
+ "readout of the removed part alone"),
114
+ ("content.<set>.co.<other>.counts", "boolean", "derived-exact",
115
+ "projected names the truth and the removed part alone does not"),
116
+ ("content.<set>.switched.names_truth", "boolean", "derived-exact",
117
+ "names the word paired with the decoded word of the switch set"),
118
+ ("content_lifetime.<set>", "string", "derived", "per layer: C names the overall best, c in "
119
+ "top 3, . names another, - no value cell"),
120
+ ("hop.native_delta", "claim", "measured", "native consumer change under a supplied "
121
+ "replacement of the binding"),
122
+ ("hop.direct_delta", "claim", "derived-exact P19", "its direct-path change"),
123
+ ("hop.indirect_share", "claim", "measured", "1 - direct/native"),
124
+ ("finite", "object", "derived-exact P07/P15; remainders measured", "finite split under an "
125
+ "edit of the binding's cells (finite=): edit, credit, closure_max, indirect, full"),
126
+ ("finite.credit.<term>", "claim", "derived-exact P07; remainder, native measured",
127
+ "routing (dp v0), payload (p0 dv), interaction (dp dv), each also _on_binding (the "
128
+ "binding's own sources), through W_O,h^T c, summed over heads and layers; terms + remainder "
129
+ "= native"),
130
+ ("finite.closure_max", "claim", "derived-exact P07", "largest float64 gap of one head's "
131
+ "split against mix(p1, v1) - mix(p0, v0)"),
132
+ ("finite.indirect.<part>", "claim", "derived-exact P07/P15; remainders measured",
133
+ "native_delta = direct + attention_rest + mlp.{gate, up, interaction, mlp_remainder} + "
134
+ "norm + stream_rounding + rounding; indirect_share = 1 - direct/native"),
135
+ ("finite.full", "object", "structural", "sha256-checked pointer to the per-layer detail "
136
+ "(with the adjoint column, derived-local, under a margin)"),
137
+ ("foreign.cells", "array", "measured (TL, nnsight) / unverified (pyvene)",
138
+ "per cell: TransformerLens hook + index, nnsight path + index, pyvene spec"),
139
+ ("components.<i>.components.<j>", "object", "derived-exact P19; SAE weights supplied",
140
+ "feature bindings: activation, to_consumer, content, saelens ids, neuronpedia link"),
141
+ ]
142
+ READ_COLUMNS = [
143
+ ("binding", "string", "structural", "the binding holding the value cells read"),
144
+ ("reader_row", "integer", "structural", "the reading row j"),
145
+ ("layer", "integer", "structural", "layer l"),
146
+ ("head", "integer", "structural", "query head h"),
147
+ ("mass", "number", "derived-exact", "sum over the binding's sources of p[h, j, s]"),
148
+ ("effect", "number", "derived-exact P19", "share-form contribution to the scalar consumer"),
149
+ ("contrast", "number", "derived-exact P19", "contrast-form contribution"),
150
+ ("mask_delta", "number", "derived-exact P19, direct path", "-contrast/(1-p) per source, "
151
+ "summed"),
152
+ ("sources", "integer", "structural", "value cells of the binding the head reads"),
153
+ ("supplied", "boolean", "structural", "a p/s edit supplied a weight"),
154
+ ]
155
+ HEAD_COLUMNS = [
156
+ ("reader_row", "integer", "structural", "row j"), ("layer", "integer", "structural", "l"),
157
+ ("head", "integer", "structural", "h"),
158
+ ("total_mass", "number", "measured", "sum_s p[h, j, s]"),
159
+ ("unbound_mass", "number", "derived-exact", "mass of bindings not on this page"),
160
+ ]
161
+
162
+
163
+ def _pd():
164
+ import pandas as pd
165
+
166
+ return pd
167
+
168
+
169
+ def _is_claim(node: Any) -> bool:
170
+ return (isinstance(node, dict) and "value" in node and "authority" in node
171
+ and isinstance(node["value"], numbers.Real) and not isinstance(node["value"], bool))
172
+
173
+
174
+ def flatten(node: Any, prefix: str = "", out: dict[str, Any] | None = None,
175
+ skip: tuple[str, ...] = ()) -> dict[str, Any]:
176
+ """Dotted columns of a nested mapping: claims -> value + ``__auth``; lists -> JSON text."""
177
+ out = {} if out is None else out
178
+ if _is_claim(node):
179
+ out[prefix] = float(node["value"]) if not isinstance(node["value"], bool) else \
180
+ node["value"]
181
+ out[prefix + AUTH] = str(node["authority"])
182
+ return out
183
+ if isinstance(node, dict):
184
+ for key, item in node.items():
185
+ path = f"{prefix}.{key}" if prefix else str(key)
186
+ if path in skip:
187
+ continue
188
+ flatten(item, path, out, skip)
189
+ return out
190
+ if isinstance(node, (list, tuple)):
191
+ out[prefix] = json.dumps(node, default=str)
192
+ return out
193
+ out[prefix] = node
194
+ return out
195
+
196
+
197
+ def _context(table: Any, item: str | None) -> dict[str, Any]:
198
+ report = table.report
199
+ record = table.records[0] if getattr(table, "records", None) else None
200
+ return {"item": item, "where": report.get("where"), "consumer": report.get("consumer"),
201
+ "model_identity": (json.dumps(record["model_identity"], sort_keys=True, default=str)
202
+ if record else None),
203
+ "record_id": record["id"] if record else None}
204
+
205
+
206
+ def to_frame(table: Any, level: str = "binding", *, item: str | None = None,
207
+ foreign: bool = False) -> Any:
208
+ """A long DataFrame of ``table`` at ``level`` (module docstring)."""
209
+ pd = _pd()
210
+ if level not in ("binding", "read", "head"):
211
+ raise ValueError("level is binding, read or head")
212
+ ctx = _context(table, item)
213
+ if level == "binding":
214
+ rows = []
215
+ for view in table.report["bindings"]:
216
+ row = dict(ctx)
217
+ row.update(flatten(view, skip=("readers",)))
218
+ rows.append(row)
219
+ return pd.DataFrame(rows)
220
+ t = table.tensors
221
+ names = t["bindings"]
222
+ objects = t.get("binding_objects") or []
223
+ roles = {b.name: (b.role, b.slot) for b in objects}
224
+ rows = []
225
+ if level == "head":
226
+ for (j, layer), total in sorted(t["total_mass"].items()):
227
+ unbound = t["unbound_mass"][(j, layer)]
228
+ for h in range(int(total.numel())):
229
+ rows.append({**ctx, "reader_row": j, "layer": layer, "head": h,
230
+ "total_mass": float(total[h]), "unbound_mass": float(unbound[h])})
231
+ return pd.DataFrame(rows)
232
+ listed = set(t["listed"])
233
+ for (j, layer), mass in sorted(t["mass"].items()):
234
+ cover = t["cover"][(j, layer)]
235
+ effect = t["effect"][(j, layer)]
236
+ contrast = t["contrast"].get((j, layer))
237
+ mask = t["mask_delta"].get((j, layer))
238
+ for b in sorted(listed):
239
+ for h in cover[b].nonzero().reshape(-1).tolist():
240
+ row = {**ctx, "binding": names[b], "role": roles.get(names[b], (None, None))[0],
241
+ "slot": roles.get(names[b], (None, None))[1], "reader_row": j,
242
+ "layer": layer, "head": h, "mass": float(mass[b, h]),
243
+ "sources": int(t["sources"][(j, layer)][b, h]),
244
+ "supplied": bool(t["supplied"][(j, layer)][b, h])}
245
+ e = effect[b, h]
246
+ row["effect"] = float(e) if e.dim() == 0 else float(e.norm())
247
+ if contrast is not None:
248
+ row["contrast"] = float(contrast[b, h])
249
+ row["mask_delta"] = float(mask[b, h])
250
+ if foreign:
251
+ from mdb.core.foreign_names import read_names
252
+
253
+ names_ = read_names(j, layer, h)
254
+ row["tl_hook"], row["tl_index"] = names_["tl"]["hook"], names_["tl"]["index"]
255
+ row["nn_path"] = names_["nnsight"]["path"]
256
+ row["nn_index"] = names_["nnsight"]["index"]
257
+ rows.append(row)
258
+ return pd.DataFrame(rows)
259
+
260
+
261
+ def to_arrow(frame: Any, *, schema: str = "mdb-symbol-table-v1") -> Any:
262
+ """``frame`` as a ``pyarrow.Table`` with ``mdb_schema`` and ``record_id`` metadata."""
263
+ import pyarrow as pa
264
+
265
+ out = pa.Table.from_pandas(frame, preserve_index=False)
266
+ ids = sorted({str(x) for x in frame.get("record_id", []) if x is not None}) \
267
+ if "record_id" in frame else []
268
+ meta = dict(out.schema.metadata or {})
269
+ meta[b"mdb_schema"] = schema.encode()
270
+ meta[b"record_ids"] = json.dumps(ids).encode()
271
+ return out.replace_schema_metadata(meta)
272
+
273
+
274
+ def to_parquet(frame: Any, path: str, *, schema: str = "mdb-symbol-table-v1") -> str:
275
+ import pyarrow.parquet as pq
276
+
277
+ pq.write_table(to_arrow(frame, schema=schema), path)
278
+ return path
279
+
280
+
281
+ def from_frame(frame: Any) -> list[dict[str, Any]]:
282
+ """Binding rows rebuilt from a binding-level frame (read-only): dotted columns nested
283
+ again, ``<col>`` + ``<col>__auth`` -> ``{value, authority}``, JSON text left as text."""
284
+ out = []
285
+ columns = [c for c in frame.columns if not c.endswith(AUTH)]
286
+ for _, series in frame.iterrows():
287
+ row: dict[str, Any] = {}
288
+ for col in columns:
289
+ value = series[col]
290
+ if value is None or (isinstance(value, float) and value != value):
291
+ continue
292
+ auth = series.get(col + AUTH) if col + AUTH in frame.columns else None
293
+ if hasattr(value, "item"):
294
+ value = value.item()
295
+ leaf = {"value": value, "authority": auth} if isinstance(auth, str) else value
296
+ node = row
297
+ parts = col.split(".")
298
+ for part in parts[:-1]:
299
+ node = node.setdefault(part, {})
300
+ if not isinstance(node, dict):
301
+ break
302
+ else:
303
+ node[parts[-1]] = leaf
304
+ out.append(row)
305
+ return out
306
+
307
+
308
+ def trace_frame(trace: Any, table: str | None = None) -> Any:
309
+ """One row per step: scalars as columns, each table entry as ``<table>.<key>``; with
310
+ ``table``: long form ``step, key, value`` of that table only."""
311
+ pd = _pd()
312
+ if table is not None:
313
+ return pd.DataFrame([{"step": r.get("step"), "key": k, "value": v}
314
+ for r in trace.records for k, v in (r.get(table) or {}).items()])
315
+ rows = []
316
+ for r in trace.records:
317
+ row = {}
318
+ for key, value in r.items():
319
+ if isinstance(value, dict):
320
+ for k, v in value.items():
321
+ row[f"{key}.{k}"] = v
322
+ elif isinstance(value, (list, tuple)):
323
+ row[key] = json.dumps(value)
324
+ else:
325
+ row[key] = value
326
+ rows.append(row)
327
+ out = pd.DataFrame(rows)
328
+ out.attrs["meta"] = dict(trace.meta)
329
+ return out
330
+
331
+
332
+ def map_frame(reports: list[dict[str, Any]]) -> Any:
333
+ """Per-item binding rows of circuit-map item reports (``circuit_map.item_report``): one row
334
+ per (item, binding) with ``item`` and the item's labels as columns."""
335
+ pd = _pd()
336
+ rows = []
337
+ for rep in reports:
338
+ table = rep.get("table") or {}
339
+ bindings = table.get("bindings") or []
340
+ if isinstance(bindings, dict):
341
+ bindings = list(bindings.values())
342
+ base = {"item": rep.get("item")}
343
+ for key, value in (rep.get("labels") or {}).items():
344
+ base[f"item_labels.{key}"] = _label_value(value)
345
+ for view in bindings:
346
+ row = dict(base)
347
+ row.update(flatten(view, skip=("readers",)))
348
+ rows.append(row)
349
+ return pd.DataFrame(rows)
350
+
351
+
352
+ def _label_value(value: Any) -> Any:
353
+ if isinstance(value, dict):
354
+ return value.get("label", value.get("value"))
355
+ return value
356
+
357
+
358
+ def loo_position_mean(frame: Any, value: str, by: str = "position") -> Any:
359
+ """``value`` minus the leave-one-out mean of ``value`` over the other rows with the same
360
+ ``by`` (a position or role); NaN where no other row shares it (identical prefixes can put
361
+ many copies of a row in its own position mean, so the mean must exclude the row)."""
362
+ groups = frame.groupby(by)[value]
363
+ total = groups.transform("sum")
364
+ count = groups.transform("count")
365
+ others = (total - frame[value]) / (count - 1)
366
+ return (frame[value] - others).where(count > 1)
367
+
368
+
369
+ def token_constancy(frame: Any, by: str = "position", token: str = "token") -> Any:
370
+ """Per ``by`` value: whether every item has the same ``token`` there (a template row), the
371
+ number of items and of distinct tokens (derived across items)."""
372
+ groups = frame.dropna(subset=[token]).groupby(by)[token]
373
+ out = groups.agg(n="count", distinct="nunique").reset_index()
374
+ out["constant"] = out["distinct"] == 1
375
+ return out
376
+
377
+
378
+ _CLAIM_SCHEMA = {"type": "object", "required": ["value", "authority"],
379
+ "properties": {"value": {"type": "number"}, "authority": {"type": "string"},
380
+ "proof": {"type": "string"}}}
381
+
382
+
383
+ def _prop(kind: str) -> dict[str, Any]:
384
+ if kind == "claim":
385
+ return {"$ref": "#/$defs/claim"}
386
+ if kind in ("string", "integer", "boolean", "array", "object", "number"):
387
+ return {"type": kind}
388
+ return {}
389
+
390
+
391
+ def json_schema(name: str = "mdb-symbol-table-v1") -> dict[str, Any]:
392
+ """A JSON Schema (draft 2020-12) for a record body of ``name`` (``SCHEMAS``), generated
393
+ from the record kind's required fields and ``COLUMNS``."""
394
+ from mdb.core.kinds import CIRCUIT_MAP, SYMBOL_TABLE, TRACE
395
+
396
+ if name not in SCHEMAS:
397
+ raise ValueError(f"schema is one of {SCHEMAS}")
398
+ base = {"$schema": "https://json-schema.org/draft/2020-12/schema",
399
+ "$id": f"https://mdb.local/schemas/{name}.json", "title": name, "type": "object",
400
+ "$defs": {"claim": _CLAIM_SCHEMA}}
401
+ if name == "mdb-symbol-table-v1":
402
+ props: dict[str, Any] = {}
403
+ for col, kind, auth, meaning in COLUMNS:
404
+ if "<" in col or "." in col:
405
+ continue
406
+ props[col] = {**_prop(kind), "description": f"{meaning} [{auth}]"}
407
+ binding = {"type": "object", "required": ["symbol", "kind", "mass", "status"],
408
+ "properties": props, "additionalProperties": True}
409
+ base["$defs"]["binding"] = binding
410
+ base["required"] = list(SYMBOL_TABLE.required)
411
+ base["properties"] = {"schema": {"const": name},
412
+ "bindings": {"type": "array", "items": {"$ref": "#/$defs/binding"}},
413
+ "page": {"type": "object"}, "unbound": {"type": "object"},
414
+ "accounting": {"type": "object"}, "labels": {"type": "object"},
415
+ "candidate_sets": {"type": "array"},
416
+ "components": {"type": "array"}}
417
+ elif name == "mdb-circuit-map-v1":
418
+ base["required"] = ["schema", "slots", "edges", "consumer_rule", "candidate_sets"]
419
+ base["properties"] = {
420
+ "schema": {"const": name},
421
+ "slots": {"type": "array", "items": {"type": "object", "required": [
422
+ "name", "role", "rows_rule"]}},
423
+ "edges": {"type": "array", "items": {"type": "object", "required": [
424
+ "src", "dst", "kind"]}},
425
+ "consumer_rule": {"type": "object"},
426
+ "candidate_sets": {"type": "object", "additionalProperties": {
427
+ "type": "array", "items": {"type": "integer"}}},
428
+ "constants": {"type": "object"}}
429
+ base["x-record-kind"] = {"kind": "circuit-map", "required": list(CIRCUIT_MAP.required)}
430
+ else:
431
+ base["required"] = ["kind", "meta", "records"]
432
+ base["properties"] = {"kind": {"type": "string"}, "meta": {"type": "object"},
433
+ "records": {"type": "array", "items": {"type": "object"}}}
434
+ base["x-record-kind"] = {"kind": "trace", "required": list(TRACE.required)}
435
+ return base
436
+
437
+
438
+ def schema_markdown() -> str:
439
+ """The column reference as Markdown tables (``docs/SYMBOL-TABLE-SCHEMA.md``)."""
440
+ def table(rows):
441
+ out = ["| Column | Type | Authority | Meaning |", "|---|---|---|---|"]
442
+ out += [f"| `{c}` | {k} | {a} | {m} |" for c, k, a, m in rows]
443
+ return "\n".join(out)
444
+ return ("## Binding rows (`report.bindings[*]`, frame level `binding`)\n\n" + table(COLUMNS)
445
+ + "\n\n## Reads (frame level `read`)\n\n" + table(READ_COLUMNS)
446
+ + "\n\n## Heads (frame level `head`)\n\n" + table(HEAD_COLUMNS) + "\n")
447
+
448
+
449
+ __all__ = ["COLUMNS", "HEAD_COLUMNS", "READ_COLUMNS", "SCHEMAS", "flatten", "from_frame",
450
+ "json_schema", "loo_position_mean", "token_constancy", "map_frame", "schema_markdown", "to_arrow",
451
+ "to_frame", "to_parquet", "trace_frame"]