model-debugger 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
mdb/repl/render.py ADDED
@@ -0,0 +1,1699 @@
1
+ """Op result JSON -> compact text. Deterministic: fixed float format, no timings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ STAT_ORDER = ("norm", "min", "max", "mean", "abs_max")
9
+
10
+
11
+ def fmt(value: Any) -> str:
12
+ if isinstance(value, bool):
13
+ return "true" if value else "false"
14
+ if isinstance(value, float):
15
+ text = f"{value:.5g}"
16
+ return "0" if text in ("-0", "0") else text
17
+ return str(value)
18
+
19
+
20
+ def tag(authority: str, qualifier: str = "") -> str:
21
+ return f"[{authority}, {qualifier}]" if qualifier else f"[{authority}]"
22
+
23
+
24
+ def qualifier(provenance: dict[str, Any] | None) -> str:
25
+ """Why a value carries its label: ``under edit t3.L0.q``, ``replica of native``,
26
+ ``realised through o``, ``mixed 4 written/12 untouched``, ``untouched, port edit: replace``."""
27
+ if not provenance:
28
+ return ""
29
+ parts = []
30
+ kind = provenance.get("edit_kind")
31
+ if provenance.get("replica_checked") is False:
32
+ at = provenance.get("replica_check_at")
33
+ parts.append(f"replica unchecked until {at}" if at else "replica unchecked")
34
+ elif kind == "replica":
35
+ parts.append("replica of native")
36
+ elif kind == "realisation":
37
+ parts.append("realised through o")
38
+ if provenance.get("mixed"):
39
+ mixed = provenance["mixed"]
40
+ parts.append(f"mixed {mixed['written']} written/{mixed['untouched']} untouched")
41
+ if provenance.get("same_port_edit"):
42
+ parts.append("untouched; port edited: " + ",".join(provenance["same_port_edit"]["ops"]))
43
+ under = provenance.get("under_edits") or []
44
+ if under:
45
+ first = under[0]
46
+ text = f"under edit {first['address']}"
47
+ extra = provenance.get("under_edits_total", len(under)) - 1
48
+ parts.append(text + (f" +{extra} more" if extra > 0 else ""))
49
+ origin = provenance.get("from_checkpoint")
50
+ if origin:
51
+ parts.append(checkpoint_label(origin))
52
+ return ", ".join(parts)
53
+
54
+
55
+ def checkpoint_label(origin: dict[str, Any]) -> str:
56
+ """``from checkpoint ab12cd34…, path unverified`` (+ ``replica, no null check``)."""
57
+ text = f"from checkpoint {str(origin['checkpoint'])[:8]}…, path {origin['path']}"
58
+ if origin.get("replica"):
59
+ check = origin.get("null_check")
60
+ text += ", replica" + (", no null check" if check is None else
61
+ "" if check else ", null check failed")
62
+ return text
63
+
64
+
65
+ def num(item: Any) -> str:
66
+ if isinstance(item, dict) and item.get("state") == "unresolved":
67
+ return f"unresolved ({item['reason']})"
68
+ if isinstance(item, dict) and item.get("state") == "refused":
69
+ return f"refused ({item['reason']})"
70
+ if isinstance(item, dict) and "value" in item:
71
+ return f"{fmt(item['value'])} {tag(item.get('authority', '?'))}"
72
+ return fmt(item)
73
+
74
+
75
+ def _proofs(proofs: list[str]) -> str:
76
+ return "{" + " ".join(proofs) + "}" if proofs else ""
77
+
78
+
79
+ def stop_line(stop: dict[str, Any]) -> str:
80
+ parts = [stop["address"], stop.get("operator", "")]
81
+ if stop.get("proofs"):
82
+ parts.append(_proofs(stop["proofs"]))
83
+ return " ".join(part for part in parts if part)
84
+
85
+
86
+ def _nonfinite(counts: dict[str, Any]) -> str:
87
+ parts = [f"{counts[k]} {label}" for k, label in (("nan", "nan"), ("posinf", "+inf"),
88
+ ("neginf", "-inf")) if counts.get(k)]
89
+ return ", ".join(parts)
90
+
91
+
92
+ def stats_line(stats: dict[str, Any], why: str = "") -> str:
93
+ present = [name for name in STAT_ORDER if name in stats]
94
+ unresolved = [name for name in present if stats[name].get("state") == "unresolved"]
95
+ tail = ""
96
+ if stats.get("nonfinite"):
97
+ tail = f" (over finite elements; non-finite: {_nonfinite(stats['nonfinite'])})"
98
+ if unresolved:
99
+ return f"unresolved: {stats[unresolved[0]]['reason']}{tail}"
100
+ authorities = {stats[name]["authority"] for name in present}
101
+ body = " ".join(f"{name} {fmt(stats[name]['value'])}" for name in present)
102
+ if len(authorities) == 1:
103
+ return f"{body} {tag(authorities.pop(), why)}{tail}"
104
+ return " ".join(f"{name} {num(stats[name])}" for name in present) + tail
105
+
106
+
107
+ def _token_text(tokens: list[dict[str, Any]]) -> str:
108
+ out = []
109
+ for token in tokens:
110
+ text = token.get("text")
111
+ out.append(str(token["id"]) if text is None else f"{token['id']}:{json.dumps(text)}")
112
+ return " ".join(out)
113
+
114
+
115
+ def _index(index: list[int]) -> str:
116
+ return "[" + ",".join(str(i) for i in index) + "]"
117
+
118
+
119
+ def reduction_lines(result: dict[str, Any], indent: str = " ") -> list[str]:
120
+ head = f"{result['address']} {result['dtype']} {result['shape']}"
121
+ if "selected_shape" in result:
122
+ head += f" -> {result['selected_shape']}"
123
+ if result.get("axes"):
124
+ head += " (" + ", ".join(result["axes"]) + ")"
125
+ lines = [head]
126
+ provenance = result.get("provenance") or {}
127
+ why = qualifier(provenance)
128
+ if provenance.get("state") == "refused":
129
+ lines.append(f"{indent}label refused: {provenance.get('reason')}")
130
+ if provenance.get("edited"):
131
+ by = f" by {provenance['by']}" if provenance.get("by") else ""
132
+ lines.append(f"{indent}edited{by}: {provenance.get('authority', 'refused')}")
133
+ if provenance.get("realisation_exact") is False:
134
+ lines.append(f"{indent}realisation inexact: max abs error "
135
+ f"{num(provenance.get('realisation_max_abs_error'))}")
136
+ if "replica_equal" in provenance:
137
+ found = provenance["replica_equal"]
138
+ if isinstance(found, dict):
139
+ lines.append(f"{indent}replica check: unresolved ({found['reason']})")
140
+ else:
141
+ text = "equal" if found else "differs"
142
+ if "replica_max_abs_diff" in provenance:
143
+ text += f" max_abs_diff {num(provenance['replica_max_abs_diff'])}"
144
+ lines.append(f"{indent}replica check: {text}")
145
+ if "margin" in result:
146
+ margin = result["margin"]
147
+ value = margin["value"]
148
+ sides = f"logits[{_token_text([margin['a']])}] - logits[{_token_text([margin['b']])}]"
149
+ lines.append(f"{indent}{sides} = " + (
150
+ f"{fmt(value['value'])} {tag(value['authority'], why)}" if "authority" in value
151
+ else num(value)))
152
+ return lines
153
+ if "tokens" in result:
154
+ total = result.get("tokens_total", len(result["tokens"]))
155
+ more = "" if total == len(result["tokens"]) else f" (last {len(result['tokens'])})"
156
+ label = provenance.get("authority")
157
+ qualified = f" {tag(label, why)}" if label else ""
158
+ lines.append(f"{indent}tokens{more}: {_token_text(result['tokens'])}{qualified}")
159
+ if "stats" in result:
160
+ lines.append(indent + stats_line(result["stats"], why))
161
+ nonfinite = (result.get("stats") or {}).get("nonfinite")
162
+ ranked = "top" if result.get("rank") == "value" else "top |v|"
163
+ if nonfinite and not result.get("top"):
164
+ lines.append(f"{indent}{ranked}: none (non-finite: {_nonfinite(nonfinite)})")
165
+ if result.get("top") and any("authority" not in e["value"] for e in result["top"]):
166
+ lines.append(f"{indent}{ranked}: {num(result['top'][0]['value'])}")
167
+ elif result.get("top"):
168
+ authorities = {entry["value"]["authority"] for entry in result["top"]}
169
+ items = []
170
+ for entry in result["top"]:
171
+ text = f"{_index(entry['index'])} {fmt(entry['value']['value'])}"
172
+ if "text" in entry:
173
+ text += f" {json.dumps(entry['text'])}"
174
+ items.append(text)
175
+ suffix = f" {tag(authorities.pop(), why)}" if len(authorities) == 1 else ""
176
+ lines.append(f"{indent}{ranked}: " + ", ".join(items) + suffix)
177
+ if "slice" in result and not isinstance(result["slice"]["values"], list):
178
+ lines.append(f"{indent}first values: {num(result['slice']['values'])}")
179
+ elif "slice" in result:
180
+ values = " ".join(fmt(v) for v in result["slice"]["values"])
181
+ lines.append(f"{indent}first {len(result['slice']['values'])}: {values} "
182
+ f"{tag(result['slice']['authority'], why)}")
183
+ if "pointer" in result:
184
+ pointer = result["pointer"]
185
+ sha = (pointer["value"].get("sha256") or "")[:16]
186
+ cut = f" cut {pointer['cut'][:12]}" if pointer.get("cut") else ""
187
+ lines.append(f"{indent}pointer {pointer['kind']} ~{pointer['program']} sha256 {sha}{cut}")
188
+ elif "pointer_omitted" in result:
189
+ lines.append(f"{indent}pointer omitted: {result['pointer_omitted']}")
190
+ return lines
191
+
192
+
193
+ def _displays(result: dict[str, Any]) -> list[str]:
194
+ lines = []
195
+ for item in result.get("displays", ()):
196
+ if "unavailable" in item:
197
+ lines.append(f"{item['id']}: {item['address']} <{item['unavailable']}>")
198
+ continue
199
+ body = reduction_lines(item, indent=" ")
200
+ lines.append(f"{item['id']}: {body[0]}")
201
+ lines.extend(body[1:])
202
+ return lines
203
+
204
+
205
+ def _hit_lines(hits: list[dict[str, Any]]) -> list[str]:
206
+ lines = []
207
+ for hit in hits:
208
+ kind = hit["kind"]
209
+ if kind == "watch":
210
+ line = f"Watch {hit['id']} ({hit['mode']}) {hit['pattern']}"
211
+ if "old" in hit:
212
+ line += f" old {stats_line(hit['old'], qualifier(hit.get('old_provenance')))}"
213
+ lines.append(line)
214
+ lines.append(f" new {stats_line(hit['new'], qualifier(hit.get('new_provenance')))}")
215
+ elif kind == "advance":
216
+ lines.append(f"Advanced to {hit['pattern']}")
217
+ else:
218
+ name = "Temporary breakpoint" if kind == "tbreak" else "Breakpoint"
219
+ lines.append(f"{name} {hit['id']}, {hit['pattern']}")
220
+ return lines
221
+
222
+
223
+ def _motion(result: dict[str, Any]) -> list[str]:
224
+ lines = []
225
+ reason = result.get("reason")
226
+ if reason in ("budget", "end-of-context", "start-of-run", "no-breakpoints"):
227
+ lines.append(f"stopped: {reason}")
228
+ elif reason == "error":
229
+ error = result.get("error") or {}
230
+ lines.append(f"stopped: error in breakpoint {error.get('id')}: {error.get('message')}")
231
+ lines.extend(_hit_lines(result.get("hits", ())))
232
+ if result.get("omitted"):
233
+ lines.append(f"... {result['omitted']} more of {result['hits_total']} hits not shown")
234
+ if result.get("note"):
235
+ lines.append(f"note: {result['note']}")
236
+ if result.get("ignored"):
237
+ lines.append(f"ignoring breakpoint {' '.join(map(str, result['ignored']['ids']))} "
238
+ f"{result['ignored']['count']} more time(s)")
239
+ if "committed" in result:
240
+ lines.append(f"committed {result['committed']} edit(s)"
241
+ + (f" and {result['committed_cells']} cell edit(s)"
242
+ if result.get("committed_cells") else ""))
243
+ if result.get("op") == "abort":
244
+ lines.append(f"dropped {result.get('count', 0)} staged edit(s)"
245
+ + (f" and {result['staged_cells']} cell edit(s)"
246
+ if result.get("staged_cells") else ""))
247
+ if result.get("op") in ("start", "run") and result.get("run") not in (None, "main"):
248
+ lines.append(f"run {result['run']}")
249
+ if result.get("op") in ("start", "run"):
250
+ lines.extend(_procedure_lines(result))
251
+ if result.get("op") == "start" and result.get("from_checkpoint"):
252
+ loaded = result["checkpoint"]
253
+ lines.append(f"{checkpoint_label(result['from_checkpoint'])} (record "
254
+ f"{loaded['record'][:16]}, history {loaded['history']}, loaded in "
255
+ f"{fmt(loaded['load_seconds']['value'])} s)")
256
+ found = result.get("verified")
257
+ if found is not None:
258
+ lines.append("verify by recompute: " + (
259
+ "reaches the checkpoint [measured]" if found["ok"] else
260
+ "does not reach the checkpoint [measured]" if found["state"] == "resolved"
261
+ else f"unresolved ({found['reason']})"))
262
+ elif result["from_checkpoint"]["path"] != "verified":
263
+ lines.append("its path is unverified: start from=... verify=true replays it")
264
+ lines.append(stop_line(result["stop"]))
265
+ if result.get("focus"):
266
+ lines.append(f"focus {result['focus']}")
267
+ lines.extend(_displays(result))
268
+ return lines
269
+
270
+
271
+ def _edit(edit: dict[str, Any]) -> str:
272
+ op = edit["op"] + (f" {num(edit['dose'])}" if "dose" in edit else "")
273
+ if edit["kind"] == "scalar":
274
+ text = f"{edit['port']} {op} {num(edit['value'])}"
275
+ else:
276
+ text = (f"{edit['port']} {op} tensor {edit['shape']} {edit['dtype']} "
277
+ f"sha256 {edit['sha256'][:12]}")
278
+ if edit.get("origin"):
279
+ origin = edit["origin"]
280
+ text += f" from {origin['origin']}:{origin['address'].split(':', 1)[-1]} ({origin['via']})"
281
+ if edit.get("cell"):
282
+ text += f" [{edit['cell']['timing']} the read]"
283
+ if "realised_exact" in edit:
284
+ if edit["realised_exact"]:
285
+ text += " (realised exactly"
286
+ else:
287
+ text += " (NOT realised exactly"
288
+ if "realised_max_abs_error" in edit:
289
+ text += f", max abs error {num(edit['realised_max_abs_error'])}"
290
+ if edit.get("realised_dtype"):
291
+ text += f" as {str(edit['realised_dtype']).removeprefix('torch.')}"
292
+ if edit.get("realised_at"):
293
+ text += f" via {edit['realised_at']}"
294
+ if edit.get("realisation_exact") is False: # the cost of going through o
295
+ text += (f"; realisation inexact, max abs error "
296
+ f"{num(edit.get('realisation_max_abs_error'))}")
297
+ text += ")"
298
+ if edit.get("selection"):
299
+ text += f" on [{edit['selection']}]"
300
+ if "mask_count" in edit:
301
+ text += f" ({edit['mask_count']} elements)"
302
+ if edit.get("fired") is False:
303
+ text += " (not fired yet)"
304
+ if "changed_fraction" in edit:
305
+ text += f" changed {num(edit['changed_fraction'])}"
306
+ if "cast_max_abs_error" in edit and not edit.get("cast_exact", True):
307
+ text += f" cast error {num(edit['cast_max_abs_error'])}"
308
+ if "is_distribution" in edit:
309
+ text += (f" row sums {num(edit.get('row_sum_min'))}..{num(edit.get('row_sum_max'))}"
310
+ f" tol {num(edit.get('row_sum_tolerance'))}"
311
+ f" {'a distribution' if edit['is_distribution'] else 'NOT a distribution'}")
312
+ if edit.get("mix"):
313
+ text += f" mix {edit['mix']}"
314
+ if "replica_verified" in edit:
315
+ text += " verified" if edit["replica_verified"] else " UNVERIFIED"
316
+ return text
317
+
318
+
319
+ def _info(result: dict[str, Any]) -> list[str]:
320
+ subject = result["subject"]
321
+ if subject == "program":
322
+ program = result["program"]
323
+ lines = [f"{program['family']} ({program['modeling']}), {program['layers']} layers, "
324
+ f"d_model {program['hidden_size']}, heads {program['heads']}/"
325
+ f"{program['kv_heads']} x {program['head_dim']}, vocab {program['vocab_size']}, "
326
+ f"{program['dtype']} on {program['device']}, attention {program['attention']}"
327
+ + (f", lookahead {program['lookahead']}" if program.get("lookahead") else "")]
328
+ lines.append("ports: " + " ".join(program["port_names"]))
329
+ lines.append("globals: " + " ".join(program["globals"]))
330
+ return lines
331
+ if subject == "ports":
332
+ return [f"{p['name']:<6}{p['sublayer']:<5}{p['operator']} {_proofs(p['proofs'])}"
333
+ + ("" if p["editable"] else " (not editable)") for p in result["ports"]]
334
+ if subject in ("breakpoints", "watch"):
335
+ if not result["items"]:
336
+ if result.get("total"):
337
+ return [_page_note(result)]
338
+ return ["no breakpoints or watches" if subject == "breakpoints" else "no watches"]
339
+ lines = []
340
+ for item in result["items"]:
341
+ extra = ""
342
+ if item["kind"] == "watch":
343
+ extra = f" {item['mode']}"
344
+ if item.get("predicate"):
345
+ extra += f" if {item['predicate']}"
346
+ elif item.get("condition"):
347
+ extra = f" if {item['condition']}"
348
+ lines.append(f"{item['id']:<4}{item['kind']:<7}{item['pattern']}{extra} "
349
+ f"hits {item['hits']}" + _flags(item))
350
+ lines.extend(_more(result))
351
+ return lines
352
+ if subject == "display":
353
+ lines = [f"{d['id']}: {d['address']}" for d in result["displays"]] or ["no displays"]
354
+ return lines + _more(result)
355
+ if subject == "checkpoints":
356
+ return _checkpoints(result["checkpoints"]) + _more(result)
357
+ if subject == "runs":
358
+ return [f"{'*' if r['current'] else ' '} {r['name']:<10}{r['where']} "
359
+ f"{r['prompt_tokens']} prompt tokens, staged {r['staged']}"
360
+ + (f" + {r['staged_cells']} cell(s)" if r["staged_cells"] else "")
361
+ + "".join(f", {line}" for line in _procedure_lines(r))
362
+ for r in result["runs"]] + _more(result) or ["no runs"]
363
+ lines = [f"staged at {result['where']}: " + (
364
+ "; ".join(_edit(e) for e in result["staged"]) or "none")]
365
+ for entry in result["committed"]:
366
+ more = (f" (+{entry['omitted']} more of {entry['edits_total']})"
367
+ if entry.get("omitted") else "")
368
+ lines.append(f"committed L{entry['layer']} (transition {entry['transition']}): "
369
+ + "; ".join(_edit(e) for e in entry["edits"]) + more)
370
+ cells = result.get("cells")
371
+ if cells:
372
+ omitted = cells.get("omitted") or {}
373
+ for e in cells["staged"]:
374
+ lines.append(f"staged cell: {_edit(e)}")
375
+ if omitted.get("staged"):
376
+ lines.append(f"staged cell: +{omitted['staged']} more of {cells['staged_total']} "
377
+ "(use limit= for the rest)")
378
+ for e in cells["committed"]:
379
+ lines.append(f"committed cell (t{e['row']} L{e['layer']} transition "
380
+ f"{e['transition']}): {_edit(e)}")
381
+ if omitted.get("committed"):
382
+ lines.append(f"committed cell: +{omitted['committed']} more of "
383
+ f"{cells['committed_total']} (use limit= for the rest)")
384
+ return lines + _more(result)
385
+
386
+
387
+ def _flags(item: dict[str, Any]) -> str:
388
+ flags = []
389
+ if not item.get("enabled", True):
390
+ flags.append("disabled")
391
+ if item.get("ignore"):
392
+ flags.append(f"ignore next {item['ignore']}")
393
+ return f" ({', '.join(flags)})" if flags else ""
394
+
395
+
396
+ def _page_note(result: dict[str, Any]) -> str:
397
+ return f"(offset {result['offset']} is past the {result['total']} items)"
398
+
399
+
400
+ def _more(result: dict[str, Any]) -> list[str]:
401
+ """A page footer when the list has more than was shown."""
402
+ total, offset = result.get("total", 0), result.get("offset", 0)
403
+ shown = offset + result.get("limit", 0)
404
+ if total > shown or offset:
405
+ return [f"(items {offset + 1}-{min(shown, total)} of {total}; "
406
+ f"use offset= and limit= for the rest)"]
407
+ return []
408
+
409
+
410
+ def _checkpoints(items: list[dict[str, Any]]) -> list[str]:
411
+ if not items:
412
+ return ["no checkpoints"]
413
+ lines = []
414
+ for c in items:
415
+ text = f"{c['name']:<10}{c['where']}"
416
+ text += (f" staged {c['staged']}, committed {c['committed']}" if "staged" in c
417
+ else " (in the project)")
418
+ if c.get("record"):
419
+ text += f" record {c['record'][:16]}"
420
+ lines.append(text)
421
+ return lines
422
+
423
+
424
+ def _frame(stop: dict[str, Any]) -> str:
425
+ return stop_line(stop)
426
+
427
+
428
+ def render(result: dict[str, Any]) -> str:
429
+ """Compact text of one op result; a result whose state is not ``resolved`` says so."""
430
+ text = _render(result)
431
+ for use in result.get("symbol_uses", ()):
432
+ token = f" {json.dumps(use['text'], ensure_ascii=False)}" if "text" in use else ""
433
+ text += f"\n symbol {use['symbol']} = {use['address']} (row {use['row']}{token}: " \
434
+ f"{use['how']})"
435
+ if result.get("state", "resolved") != "resolved":
436
+ text += f"\nstate: {result['state']}"
437
+ return text
438
+
439
+
440
+ def _render(result: dict[str, Any]) -> str:
441
+ name = result.get("op")
442
+ if name in ("start", "run", "step", "next", "finish", "until", "advance", "continue",
443
+ "commit", "abort", "restart", "reverse-step", "reverse-next", "reverse-finish",
444
+ "reverse-continue"):
445
+ return "\n".join(_motion(result))
446
+ if name == "where":
447
+ lines = [stop_line(result["stop"])]
448
+ if result.get("focus"):
449
+ lines.append(f"focus {result['focus']}")
450
+ total = result["tokens_total"]
451
+ more = "" if total == len(result["tokens"]) else f" (last {len(result['tokens'])})"
452
+ lines.append(f"tokens{more}: {_token_text(result['tokens'])}")
453
+ lines.append(f"staged edits: {result['staged']}"
454
+ + (f" + {result['staged_cells']} cell edit(s)"
455
+ if result.get("staged_cells") else "")
456
+ + (f", lookahead {result['lookahead']}" if result.get("lookahead") else ""))
457
+ for port in result.get("computed_past_cursor", ()):
458
+ lines.append(f"{port} was computed by the native call but is not held")
459
+ lines.extend(_procedure_lines(result))
460
+ return "\n".join(lines)
461
+ if name == "frame" and "run" in result:
462
+ return f"run {result['run']}\n" + stop_line(result["stop"])
463
+ if name == "frame":
464
+ lines = [f"focus {result['focus']} (cursor {result['cursor']})"]
465
+ if "frame" in result:
466
+ lines.append(_frame(result["frame"]))
467
+ return "\n".join(lines)
468
+ if name in ("up", "down"):
469
+ line = _frame(result["frame"])
470
+ if result.get("computed") is False:
471
+ line += " (not computed yet)"
472
+ if result.get("alternatives"):
473
+ line += "\n also produced by: " + ", ".join(result["alternatives"])
474
+ return line
475
+ if name == "print":
476
+ return "\n".join(reduction_lines(result))
477
+ if name == "x":
478
+ head = (f"{result['address']} [{result['offset']}:{result['offset'] + result['count']}]"
479
+ f" of {result['numel']}")
480
+ if "values" in result:
481
+ values = result["values"]
482
+ if values.get("state") in ("unresolved", "refused"):
483
+ return f"{head}: {num(values)}"
484
+ text = f"{head}: " + " ".join(fmt(v) for v in values["values"]) + \
485
+ f" {tag(values['authority'], qualifier(result.get('provenance')))}"
486
+ if result.get("nonfinite"):
487
+ text += f" (non-finite: {_nonfinite(result['nonfinite'])})"
488
+ return text
489
+ return f"{head}: {_token_text(result['tokens'])}"
490
+ if name == "list":
491
+ lines = [f"L{result['layer']} at row {result['row']} (cursor {result['where']})"]
492
+ for row in result["ports"]:
493
+ mark = "=>" if row["cursor"] else ("*" if row["focus"] else " ")
494
+ state = "" if row["computed"] else " ."
495
+ lines.append(f"{mark:>2} {row['port']:<6}{row['operator']} {_proofs(row['proofs'])}"
496
+ f"{state}")
497
+ for check, value in result.get("checks", {}).items():
498
+ text = "equal" if value.get("equal") else "differs"
499
+ if "max_abs_diff" in value:
500
+ text += f" max_abs_diff {num(value['max_abs_diff'])}"
501
+ lines.append(f" replica check {check}: {text}")
502
+ return "\n".join(lines)
503
+ if name == "backtrace":
504
+ lines = [result["chain"]]
505
+ for frame in result["frames"]:
506
+ inputs = frame.get("inputs")
507
+ reads = f" <- {','.join(inputs)}" if inputs else ""
508
+ if frame.get("reads"):
509
+ reads += (" + " if inputs else " <- ") + ",".join(frame["reads"])
510
+ lines.append(f"#{frame['level']:<2} {_frame(frame)}{reads}")
511
+ return "\n".join(lines)
512
+ if name in ("break", "tbreak"):
513
+ item = result["breakpoint"]
514
+ cond = f" if {item['condition']}" if item["condition"] else ""
515
+ label = "Temporary breakpoint" if item["kind"] == "tbreak" else "Breakpoint"
516
+ return f"{label} {item['id']} at {item['pattern']}{cond}"
517
+ if name == "watch":
518
+ item = result["watch"]
519
+ pred = f" if {item['predicate']}" if item["predicate"] else ""
520
+ return f"Watch {item['id']} ({item['mode']}) on {item['pattern']}{pred}"
521
+ if name in ("delete", "undisplay"):
522
+ text = "deleted " + (" ".join(str(i) for i in result["deleted"]) or "nothing")
523
+ if result.get("omitted"):
524
+ text += f" ... ({result['deleted_total']} in all)"
525
+ return text
526
+ if name in ("enable", "disable"):
527
+ text = f"{name}d " + (" ".join(str(i) for i in result["ids"]) or "nothing")
528
+ if result.get("omitted"):
529
+ text += f" ... ({result['total']} in all)"
530
+ return text
531
+ if name in ("condition", "ignore"):
532
+ item = result.get("breakpoint") or result["watch"]
533
+ if name == "ignore":
534
+ return (f"Will ignore next {result['ignore']} crossings of breakpoint {item['id']}."
535
+ if result["ignore"] else f"Will stop next time breakpoint {item['id']} is "
536
+ "reached.")
537
+ what = item.get("condition") if "condition" in item else item.get("predicate")
538
+ return (f"Breakpoint {item['id']} now unconditional." if what is None
539
+ else f"Breakpoint {item['id']}: if {what}")
540
+ if name == "display":
541
+ return "\n".join(_displays(result)) or "no displays"
542
+ if name == "set" and "cell" in result:
543
+ cell = result["cell"]
544
+ lines = [f"staged cell {result['target']}: "
545
+ + "; ".join(_edit(e) for e in result["edits"])
546
+ + f" ({result['staged_cells']} cell edit(s) staged)",
547
+ f" realised {cell['timing']} {cell['read']} reads it (boundary "
548
+ f"{cell['boundary']}); reads already made are not recomputed"]
549
+ if "source" in result:
550
+ lines.append(f" value from {result['source']}")
551
+ return "\n".join(lines)
552
+ if name == "set":
553
+ lines = [f"staged at {result['target']}: " + "; ".join(_edit(e) for e in result["edits"])
554
+ + f" ({result['staged']} staged)"]
555
+ if "source" in result:
556
+ lines.append(f" value from {result['source']}")
557
+ if "realised_as" in result:
558
+ lines.append(f" realised as {result['realised_as']}")
559
+ return "\n".join(lines)
560
+ if name == "checkpoint":
561
+ text = f"checkpoint {result['name']} at {result['where']} ({result['bytes']} bytes)"
562
+ if result.get("durable"):
563
+ text += f"; stored in the project as record {result['durable']['record'][:16]}"
564
+ return text
565
+ if name == "checkpoints":
566
+ return "\n".join(_checkpoints(result["checkpoints"]) + _more(result))
567
+ if name == "info":
568
+ return "\n".join(_info(result))
569
+ if name in _PREDICT:
570
+ return "\n".join(_PREDICT[name](result))
571
+ if name in _INSPECT:
572
+ return "\n".join(_INSPECT[name](result))
573
+ return json.dumps(result, sort_keys=True)
574
+
575
+
576
+ # --------------------------------------------------------------------------- explain/forecast/
577
+ # verify/whatif
578
+
579
+
580
+ def _claimed(item: Any) -> str:
581
+ """A labelled number with its proof (``0.25 [derived-local P14]``), a labelled
582
+ ``{max_abs, norm}`` pair, or the state and reason of a field that has no number."""
583
+ if isinstance(item, dict) and item.get("state") in ("unresolved", "refused"):
584
+ return num(item)
585
+ if isinstance(item, dict) and "max_abs" in item and "value" not in item:
586
+ return f"max_abs {_claimed(item['max_abs'])} norm {_claimed(item['norm'])}"
587
+ proof = item.get("proof")
588
+ return f"{fmt(item['value'])} [{item['authority']}{' ' + proof if proof else ''}]"
589
+
590
+
591
+ def _explain_lines(result: dict[str, Any]) -> list[str]:
592
+ data = result["explain"]
593
+ if data.get("state") == "refused":
594
+ return [f"explain {result['target']}: refused ({data['reason']})"]
595
+ if result["kind"] == "margin":
596
+ lines = [f"explain {result['target']} native {_claimed(data['native_margin'])} "
597
+ f"float64 {_claimed(data['float64_margin'])} eta {_claimed(data['eta'])}"]
598
+ for term in data["terms"]:
599
+ lines.append(f" {term['name']:<19}{_claimed(term['value'])}")
600
+ summary = data.get("terms_summary")
601
+ if summary and summary["rest"]["count"]:
602
+ rest = summary["rest"]
603
+ lines.append(f" +{rest['count']} more, sum = {_claimed(rest['sum'])}"
604
+ f" (of {summary['count']} terms; full list "
605
+ f"{summary['pointer']['state']}, sha256 {summary['pointer']['sha256'][:16]})")
606
+ for rem in data["remainders"]:
607
+ line = f" ~{rem['name']:<18}{_claimed(rem['value'])}"
608
+ if "scale" in rem:
609
+ line += (f" scale {_claimed(rem['scale'])} k {rem['k']} "
610
+ f"{'within' if rem['within_rounding'] else 'OUTSIDE'}")
611
+ elif rem.get("bound", {}).get("state") == "refused":
612
+ line += f" bound refused ({rem['bound']['reason']})"
613
+ lines.append(line)
614
+ lines.append(f" listed_sum {_claimed(data['listed_sum'])} closure "
615
+ f"{_claimed(data['closure'])}")
616
+ else:
617
+ lines = [f"explain {result['target']} {data['function']} {data['proof']}: "
618
+ f"{data['operator']} {_proofs(data['proofs_declared'])}"]
619
+ if "eta_max_abs" in data:
620
+ lines.append(f" eta_max_abs {_claimed(data['eta_max_abs'])} eta_rel "
621
+ f"{_claimed(data['eta_rel'])} (against {data['against']})")
622
+ if "edit_delta_max_abs" in data:
623
+ lines.append(f" written by an edit ({data['edit']['by']}): edit_delta_max_abs "
624
+ f"{_claimed(data['edit_delta_max_abs'])}")
625
+ lines += [f" note: {note}" for note in data.get("notes", ())]
626
+ if data.get("state") not in (None, "resolved"):
627
+ lines.append(f" {data['state']}: {data.get('reason')}")
628
+ return lines
629
+
630
+
631
+ def _predicted(body: dict[str, Any]) -> str:
632
+ if "token" in body:
633
+ return f"token {body['token']}"
634
+ if "value" in body:
635
+ return _claimed(body["value"])
636
+ return f"{_claimed(body)} sha256 {body['sha256'][:16]}"
637
+
638
+
639
+ def _forecast_lines(result: dict[str, Any]) -> list[str]:
640
+ view = result["forecast"]
641
+ summary = view["method_summary"]
642
+ count, first, last = summary["count"], summary["first"][0], summary["last"][-1]
643
+ method = (f"{last['identity']} {last['proof'] or ''}: {last['operator']}" if count == 1
644
+ else f"{count} identities {first['stop']} .. {last['stop']} (last "
645
+ f"{last['identity']} {last['proof'] or ''})")
646
+ pointer = summary["chain_pointer"]
647
+ method += (f"; chain blob {pointer['ref'][:16]}" if pointer["state"] == "stored"
648
+ else "; chain not stored (no project)")
649
+ vector = "sha256" in view["predicted"]
650
+ emulated = view.get("emulated") or {}
651
+ if "margin" in emulated:
652
+ second = _claimed(emulated["margin"])
653
+ elif "token" in emulated:
654
+ second = f"token {emulated['token']}"
655
+ elif "max_abs" in emulated:
656
+ second = f"{_claimed(emulated)} sha256 {emulated['sha256'][:16]}"
657
+ else:
658
+ second = "none"
659
+ return [f"forecast {view['id']} {view['target']} sealed at {view['sealed_at']} "
660
+ f"record {view['record'][:16]}",
661
+ f" method {method}",
662
+ f" predicted exact {_predicted(view['predicted'])} emulated {second}",
663
+ f" {bound_text(view['bound'], vector)}"]
664
+
665
+
666
+ def bound_text(bound: dict[str, Any], vector: bool = False) -> str:
667
+ """The sealed worst-case interval as information: its largest value, or the stop where
668
+ it stopped being informative and why, or why there is none."""
669
+ if "max" in bound:
670
+ return (f"worst-case rounding interval {_claimed(bound['max'])}"
671
+ f"{' per element' if vector else ''} (information, not the verdict)")
672
+ if "note" in bound:
673
+ return bound["note"]
674
+ return f"worst-case rounding interval {bound.get('state', 'absent')} ({bound.get('reason')})"
675
+
676
+
677
+ def _floor_text(item: dict[str, Any]) -> str:
678
+ """``residual 0 = 0 spacings <= floor 0.0156 = 1 bfloat16 spacing (supplied)``: the residual
679
+ native - emulated in dtype spacings next to the floor in spacings."""
680
+ text = ""
681
+ if "residual_spacings" in item:
682
+ text += f" = {item['residual_spacings']['value']:.2g} spacings"
683
+ text += f" {'<=' if item['verdict'] == 'confirmed' else '>'} floor {_claimed(item['floor'])}"
684
+ if "floor_spacings" in item:
685
+ count = item["floor_spacings"]["value"]
686
+ text += (f" = {count:g} {item.get('dtype', '?')} spacing{'' if count == 1 else 's'} "
687
+ f"({item['floor_spacings']['authority']})")
688
+ return text
689
+
690
+
691
+ def _verify_lines(result: dict[str, Any]) -> list[str]:
692
+ if not result["forecasts"]:
693
+ return [f"no open forecasts (cursor {result['where']})"]
694
+ lines = []
695
+ for item in result["forecasts"]:
696
+ head = f"forecast {item['id']} {item['target']}: {item['verdict']}"
697
+ if item["verdict"] == "open":
698
+ lines.append(f"{head} ({item.get('reason', 'target not reached')})")
699
+ continue
700
+ if item["verdict"] == "edited":
701
+ lines.append(f"{head} ({'; '.join(item['edited_after_seal'])}): not a forecast "
702
+ "failure")
703
+ else:
704
+ text = f"{head} native {_claimed(item['native'])}" if "native" in item else head
705
+ if "residual_max_abs" in item:
706
+ text += f" residual vs emulated {_claimed(item['residual_max_abs'])}"
707
+ if "floor" in item:
708
+ text += _floor_text(item) + f" [P20, {item.get('state', 'resolved')}]"
709
+ if "reason" in item:
710
+ text += f" ({item['reason']})"
711
+ lines.append(text)
712
+ effect = item.get("rounding_effect")
713
+ if effect is not None:
714
+ text = f" rounding effect native - exact {_claimed(effect['max_abs'])}"
715
+ if "spacings" in effect:
716
+ text += f" = {effect['spacings']['value']:.3g} spacings"
717
+ if "bound_max" in item:
718
+ text += (f"; worst-case bound {_claimed(item['bound_max'])} "
719
+ f"({'holds' if item['within_bound'] else 'exceeded'}, information)")
720
+ if "worst_excess" in item:
721
+ text += f" (worst excess {_claimed(item['worst_excess'])})"
722
+ elif "bound_note" in item:
723
+ text += f"; {item['bound_note']}"
724
+ lines.append(text)
725
+ if "stages" in item:
726
+ lines.append(f" {stages_text(item['stages'])}")
727
+ if "rounding_origin" in item:
728
+ lines.append(f" rounding origin (sealed): {item['rounding_origin']['text']}")
729
+ order = item["order"]
730
+ lineage = ("same cut (the target is a later port of the sealed layer)"
731
+ if order["same_cut"] else
732
+ f"cut {'descends' if order['descends'] else 'does not descend'} through "
733
+ f"{order['receipts_after_seal']['count']} receipts")
734
+ lines.append(f" order: sealed at {item['sealed_at']} (stop {order['sealed']['index']}) "
735
+ f"{'before' if order['sealed_before_target'] else 'NOT before'} the target "
736
+ f"(stop {order['target']['index']}); {lineage}")
737
+ return lines
738
+
739
+
740
+ def stages_text(stages: dict[str, Any]) -> str:
741
+ """The per-stage containment on native operands, labelled as a per-stage bound."""
742
+ if stages.get("state") in ("refused", "unresolved"):
743
+ return f"stages: {stages['state']} ({stages['reason']})"
744
+ return f"stages [per-stage bound, not a chain bound]: {stages['text']}"
745
+
746
+
747
+ def _delta_name(consumer: dict[str, Any]) -> str:
748
+ return {"margin": "\u0394M", "logit": "\u0394logit"}.get(consumer["kind"], "\u0394")
749
+
750
+
751
+ def _path_text(moved: dict[str, Any]) -> str:
752
+ moved = {k: v["value"] if isinstance(v, dict) and "value" in v else v for k, v in moved.items()}
753
+ return (f"first {moved['first']}, {moved['moved']} selections in {moved.get('heads', 0)} "
754
+ f"heads moved" if moved["diverged"] else f"no downstream argmax moved "
755
+ f"({moved['selections']} selections, {moved['ties']} ties)")
756
+
757
+
758
+ def _whatif_donor_lines(result: dict[str, Any]) -> list[str]:
759
+ lines = [f"whatif {result['address']} donors {len(result['donors'])} -> {result['consumer']}: "
760
+ f"{result['label']}"
761
+ + (f", {result['n_path_diverged']['value']} path-diverged"
762
+ if "n_path_diverged" in result else "")]
763
+ for d in result["per_donor"]:
764
+ text = (f" {d['name']}: {d.get('label') or d['verdict']} delta {_claimed(d['delta'])}"
765
+ f"{'' if d['informative'] is not False else ' (value equals the base)'}")
766
+ if "path" in d:
767
+ text += (f" path {d['path']['verdict']}, frozen-selection "
768
+ f"{_claimed(d['path']['frozen']['dM'])}")
769
+ lines.append(text)
770
+ lines.append(f" session unchanged at {result['where']}")
771
+ return lines
772
+
773
+
774
+ def _whatif_lines(result: dict[str, Any]) -> list[str]:
775
+ if "per_donor" in result:
776
+ return _whatif_donor_lines(result)
777
+ edit, consumer, delta = result["edit"], result["consumer"], _delta_name(result["consumer"])
778
+ value = (_claimed(edit["value"]) if "value" in edit
779
+ else f"tensor {edit['sha256'][:12]}" + (f" from {edit['source']}"
780
+ if "source" in edit else ""))
781
+ where = edit["address"] + (f"[{edit['selection']}]"
782
+ if "selection" in edit and "cell" not in edit else "")
783
+ lines = [f"whatif {where} {edit['op']} {value} -> {consumer['address']} "
784
+ f"(mode {result['mode']}, record {result['record'][:16]})"]
785
+ prediction = result["prediction"]
786
+ if prediction["state"] == "refused":
787
+ lines.append(f" sealed prediction refused ({prediction['reason']})")
788
+ else:
789
+ linear = prediction["linear"]
790
+ exact = prediction["exact"]
791
+ bound = f" bound {_claimed(exact['bound'])}" if "bound" in exact else ""
792
+ if "bound_note" in exact:
793
+ bound = f" ({exact['bound_note']})"
794
+ if exact.get("wider_than_value"):
795
+ bound += " (worst case, >= |exact|: no sign)"
796
+ operands = exact.get("operands", {})
797
+ if operands.get("source") == "forecast":
798
+ bound += f" (operands forecast from {operands['at']})"
799
+ emulated = prediction.get("emulated", {})
800
+ lines.append(f" sealed linear {delta} = "
801
+ f"{_claimed(linear['value']) if 'value' in linear else num(linear)} "
802
+ f"exact {delta} = {_claimed(exact['value'])}{bound} emulated {delta} = "
803
+ + (_claimed(emulated["value"]) if "value" in emulated else num(emulated)))
804
+ measured = result["measured"]
805
+ lines.append(f" native {delta} = {_claimed(measured['delta'])} (base "
806
+ f"{_claimed(measured['base'])} -> edited {_claimed(measured['edited'])})")
807
+ split = result["split"]
808
+ if split.get("state") == "refused":
809
+ lines.append(" error split: none (no prediction)")
810
+ else:
811
+ parts = []
812
+ for term in split["terms"]:
813
+ text = f"{term['name']} {_claimed(term['value'])}"
814
+ if term.get("within_bound") is not None:
815
+ state = term["within_bound"]
816
+ text += f" ({'within' if state else 'OUTSIDE'} bound {_claimed(term['bound'])})"
817
+ elif term.get("bound_note"):
818
+ text += f" ({term['bound_note']})"
819
+ parts.append(text)
820
+ lines.append(f" error split ({split['proof']}): " + " + ".join(parts))
821
+ if "effect" in result:
822
+ lines.append(" " + effect_line(result["effect"], delta,
823
+ exact_note=" (written value, measured operands)"))
824
+ for side, stages in result.get("stages", {}).items():
825
+ lines.append(f" {side} run {stages_text(stages)}")
826
+ other = (result.get("prediction") or {}).get("other_edits")
827
+ if other:
828
+ lines.append(f" other edits in the chains: {', '.join(other['applied'])}")
829
+ session = result["session"]
830
+ lines.append(f" session {'unchanged' if session['unchanged'] else 'CHANGED'} at "
831
+ f"{result['where']} ({len(result['measured']['moves'])} moves, restored)")
832
+ if "path" in result:
833
+ path = result["path"]
834
+ where = _path_text(path["path"])
835
+ lines.append(f" path: {path['verdict']} ({where}); total {delta} "
836
+ f"{_claimed(path['total']['dM'])}, frozen-selection {delta} "
837
+ f"{_claimed(path['frozen']['dM'])} ({path['frozen']['holds']})")
838
+ return lines
839
+
840
+
841
+ def effect_line(effect: dict[str, Any], delta: str = "\u0394", exact_note: str = "") -> str:
842
+ """The P20 verdict: native against the emulated change within the floor (1 spacing,
843
+ supplied), the exact change beside it; ``exact_note`` says which exact change it is."""
844
+ numbers = f"native {delta} {_claimed(effect['native'])}"
845
+ if "size_spacings" in effect:
846
+ numbers += f" = {effect['size_spacings']['value']:.2g} spacings"
847
+ if "emulated" in effect:
848
+ numbers += (f", emulated {delta} {_claimed(effect['emulated'])}, residual "
849
+ f"{_claimed(effect['residual'])} = "
850
+ f"{effect['residual_spacings']['value']:.2g} spacings")
851
+ if "exact" in effect:
852
+ numbers += f"; exact {delta}{exact_note} {_claimed(effect['exact'])}"
853
+ if "emulated" not in effect:
854
+ numbers += f" ({effect['basis']})"
855
+ count = effect["floor_spacings"]["value"]
856
+ floor = (f"floor {_claimed(effect['floor'])} = {count:g} {effect['dtype']} "
857
+ f"spacing{'' if count == 1 else 's'} ({effect['floor_spacings']['authority']})")
858
+ text = f"verdict (P20): {effect.get('label', effect['verdict'])} {numbers}; {floor}"
859
+ for key in ("note", "reason"):
860
+ if effect.get(key):
861
+ text += f" [{effect[key]}]"
862
+ return text
863
+
864
+
865
+ _PREDICT = {"explain": _explain_lines, "forecast": _forecast_lines, "verify": _verify_lines,
866
+ "whatif": _whatif_lines}
867
+
868
+
869
+ # --------------------------------------------------------------------------- reads/symbols/
870
+ # circuit/compare/seek
871
+
872
+
873
+ def _short(item: Any) -> str:
874
+ """A labelled scalar, or the norm of a labelled vector, or a state and reason."""
875
+ if isinstance(item, dict) and "norm" in item and "value" not in item:
876
+ return f"norm {_claimed(item['norm'])}"
877
+ return _claimed(item)
878
+
879
+
880
+ def _verdict(causal: dict[str, Any]) -> str:
881
+ if "delta" not in causal:
882
+ return f"unresolved ({causal['reason']})"
883
+ head = causal["verdict"] + (f" ({causal['reason']})" if causal.get("reason") else "")
884
+ donors = (causal.get("effect") or {}).get("label")
885
+ if causal["verdict"] == "not causal at this dose" and donors:
886
+ head += f" [{donors.replace('no effect', 'null', 1)}]"
887
+ text = f"{head}: Δ {_short(causal['delta'])}"
888
+ effect = causal.get("effect") or {}
889
+ emulated = causal.get("emulated")
890
+ if isinstance(emulated, dict) and emulated.get("state") is None:
891
+ text += f", emulated {_short(emulated)}"
892
+ if "residual" in effect:
893
+ text += (f", residual {_claimed(effect['residual'])} = "
894
+ f"{effect['residual_spacings']['value']:.2g} spacings")
895
+ predicted = causal.get("predicted")
896
+ if isinstance(predicted, dict) and predicted.get("state") is None:
897
+ text += f"; exact {_short(predicted)}"
898
+ if "floor" in effect:
899
+ text += f"; floor {_claimed(effect['floor'])}"
900
+ return text
901
+
902
+
903
+ def _reads_lines(result: dict[str, Any]) -> list[str]:
904
+ source = result["source"]
905
+ lines = [f"reads {source['address']} at {result['where']} rows "
906
+ f"{','.join(f't{r}' for r in result['rows'])} consumer {result['consumer']} "
907
+ f"({result['total']} reads)"]
908
+ for entry in result["reads"]:
909
+ lines.append(f" {entry['name']:<10} mass {_claimed(entry['mass'])} effect "
910
+ f"{_short(entry['to_consumer'])}")
911
+ lines.append(f" {_verdict(entry['causal'])}")
912
+ if "omitted" in result:
913
+ omitted = result["omitted"]
914
+ lines.append(f" +{omitted['count']} more: mass Σ {_claimed(omitted['mass'])} "
915
+ f"effect Σ {_short(omitted['to_consumer'])}")
916
+ for name, check in result["checks"].items():
917
+ if check.get("state"):
918
+ continue
919
+ lines.append(f" {name}: eta_max_abs {_claimed(check['eta_max_abs'])} worst |eta|/bound "
920
+ f"{_claimed(check['worst_ratio'])} "
921
+ f"{'within' if check['within_bound'] else 'OUTSIDE'} bound "
922
+ f"({check['count']} layer rows)")
923
+ lines += [f" not computed: {item}" for item in result.get("not_computed", ())]
924
+ return lines
925
+
926
+
927
+ def _display_width(text: str) -> int:
928
+ """Terminal columns: wide characters count 2, combining marks 0."""
929
+ import unicodedata
930
+
931
+ return sum(0 if unicodedata.combining(c) else 2 if unicodedata.east_asian_width(c) in "WF"
932
+ else 1 for c in text)
933
+
934
+
935
+ def _pad(text: str, width: int) -> str:
936
+ return text + " " * max(width - _display_width(text), 0)
937
+
938
+
939
+ def _symbol_name(item: dict[str, Any]) -> str:
940
+ """A binding's name; token text is quoted with escapes so spaces and newlines show."""
941
+ name = item["symbol"]
942
+ if "text" in item:
943
+ name += f" {json.dumps(item['text'], ensure_ascii=False)}"
944
+ elif "token" in item:
945
+ name += f" (id {item['token']})"
946
+ return name
947
+
948
+
949
+ def _symbols_lines(result: dict[str, Any]) -> list[str]:
950
+ head = f"symbols at {result['where']} consumer {result['consumer']}"
951
+ if "consumer_total" in result:
952
+ head += f" = {_claimed(result['consumer_total'])}"
953
+ lines = [head + f" min_mass {_claimed(result['min_mass'])}",
954
+ " mass: a sum over the heads and layers that read the binding (n reads, mean per "
955
+ "read)",
956
+ " life: " + " ".join(f"{mark} {text}" for mark, text in result["legend"].items())]
957
+ names = [_symbol_name(item) for item in result["bindings"]]
958
+ names += [item["symbol"] for item in result.get("unresolved_symbols", ())] + ["Unbound"]
959
+ width = max(len(n) if n.isascii() else _display_width(n) for n in names) + 1
960
+ for item, name in zip(result["bindings"], names):
961
+ life = item["lifetime"]
962
+ span = f" ({life['first']}..{life['last']})" if life["first"] else ""
963
+ lines.append(f" {_pad(name, width)}{item['status']:<7}mass {_claimed(item['mass'])} over "
964
+ f"{item['count']} reads (mean {_short(item['mean_mass'])}) to_consumer "
965
+ f"{_short(item['to_consumer'])} life {life['strip']}{span}")
966
+ lines.append(f" defined {', '.join(item['definitions'])}")
967
+ readers = "; ".join(f"{r['name']} mass {_claimed(r['mass'])} effect "
968
+ f"{_short(r['effect'])}" for r in item["readers"])
969
+ more = f" (+{item['omitted']} more)" if item.get("omitted") else ""
970
+ lines.append(f" readers {readers or 'none'}{more}")
971
+ if item.get("edited_by"):
972
+ lines.append(f" edited by {', '.join(item['edited_by'])}")
973
+ if item.get("slot"):
974
+ lines.append(f" slot {item['slot']} (role {item.get('role')})")
975
+ if item.get("labels"):
976
+ lines.append(" labels " + ", ".join(
977
+ f"{k}={v.get('label', v.get('value'))}" for k, v in item["labels"].items()))
978
+ if isinstance(item.get("content"), dict):
979
+ parts = []
980
+ for name, found in item["content"].items():
981
+ if not isinstance(found, dict) or "best" not in found or name == "vocab_top":
982
+ continue
983
+ text = f"{name}: {found.get('text', found['best'])}"
984
+ if "names_truth" in found:
985
+ text += " (truth)" if found["names_truth"] else \
986
+ f" (truth rank {found['truth_rank']})"
987
+ flags = found.get("flags") or {}
988
+ marks = [m for m in ("collision", "first_subword") if flags.get(m)]
989
+ if flags.get("kind"):
990
+ marks.append("also " + "/".join(flags["kind"]))
991
+ if marks:
992
+ text += " [" + ", ".join(marks) + "]"
993
+ for other, co in (found.get("co") or {}).items():
994
+ if "counts" in co:
995
+ text += f" co-{other} {'counts' if co['counts'] else 'no'}"
996
+ parts.append(text)
997
+ if parts:
998
+ lines.append(" content " + "; ".join(parts))
999
+ causal = item.get("causal") or {}
1000
+ if causal.get("status") == "intervened":
1001
+ lines.append(f" causal {causal['verdict']} Δ {_short(causal['delta'])} (floor "
1002
+ f"{_short(causal.get('floor', {'state': 'n/a', 'reason': 'none'}))}) "
1003
+ f"contrast {_short(item.get('contrast', {'state': 'n/a', 'reason': 'none'}))}")
1004
+ for item in result.get("unresolved_symbols", ()):
1005
+ lines.append(f" {_pad(item['symbol'], width)}unresolved defined {', '.join(item['definitions'])}"
1006
+ f" ({item['reason']})")
1007
+ for item in result.get("named", ()):
1008
+ lines.append(f" named {item['symbol']} = {item['source']} -> {item['consumer']} Δ "
1009
+ f"{_claimed(item['delta'])} {item['verdict']} here "
1010
+ f"{_named_here(item['here'])}")
1011
+ unbound = result["unbound"]
1012
+ lines.append(f" {_pad('Unbound', width)}mass {_short(unbound['mass'])} readout "
1013
+ f"{_short(unbound['readout'])}")
1014
+ parts = unbound.get("parts")
1015
+ if parts:
1016
+ remainder = parts["remainder"]
1017
+ text = (f" = embedding+mlp {_claimed(parts['embedding_mlp'])} + attention not "
1018
+ f"listed {_claimed(parts['attention_not_listed'])}")
1019
+ if "residual_edits" in parts:
1020
+ text += f" + residual edits {_claimed(parts['residual_edits'])}"
1021
+ if remainder["within"] is None:
1022
+ tail = "bound refused (accumulation premise fails)"
1023
+ else:
1024
+ tail = (f"bound {_claimed(remainder['bound'])}: "
1025
+ f"{'within' if remainder['within'] else 'OUTSIDE'}")
1026
+ lines.append(text + f" + remainder {_claimed(remainder['value'])}, {tail}")
1027
+ accounting = result["accounting"]
1028
+ partition = accounting["partition"]
1029
+ split = (f"partition gap {_claimed(partition['max_gap'])}" if "max_gap" in partition
1030
+ else f"partition {num(partition)}")
1031
+ lines.append(f" accounting: {accounting['heads']} heads, listed mass "
1032
+ f"{_claimed(accounting['listed_mass'])}, max |sum p - 1| "
1033
+ f"{_claimed(accounting['max_head_deviation'])} "
1034
+ f"{'<=' if accounting['within_bound'] else '>'} "
1035
+ f"{_claimed(accounting['deviation_bound'])}, {split}")
1036
+ page = result["page"]
1037
+ shown = len(result["bindings"])
1038
+ lines.append(f" (bindings {page['offset'] + 1}-{page['offset'] + shown} of {page['total']})"
1039
+ if shown else f" (no bindings at offset {page['offset']} of {page['total']})")
1040
+ lines += [f" not computed: {item}" for item in result.get("not_computed", ())]
1041
+ if result.get("stored"):
1042
+ lines.append(f" stored {len(result['stored'])} record(s): {result['stored'][0][:16]}")
1043
+ return lines
1044
+
1045
+
1046
+ def _walk(node: dict[str, Any], depth: int = 0, marks: dict[str, str] | None = None,
1047
+ texts: dict[str, str] | None = None, circuit: Any = None) -> list[str]:
1048
+ marks, texts = marks or {}, texts or {}
1049
+ name = node["name"] if node["name"] == node["address"] else (
1050
+ f"{node['name']} {node['address']}")
1051
+ if node["id"] in texts:
1052
+ name += f" {json.dumps(texts[node['id']])}"
1053
+ line = f"{' ' * depth}{name} {_short(node['value'])}"
1054
+ if "bound" in node:
1055
+ line += f" {'within' if node['within'] else 'OUTSIDE'} {_short(node['bound'])}"
1056
+ if node.get("unexamined"):
1057
+ line += (f" (not examined, {int(node['unexamined_count']['value'])} subtree(s) "
1058
+ "not expanded)")
1059
+ if node["id"] in marks:
1060
+ line += f" [patched in: {'ko' if marks[node['id']] == 'retained' else 'keep'}]"
1061
+ lines = [line]
1062
+ for child in node.get("children", ()):
1063
+ lines += _walk(child, depth + 1, marks, texts, circuit)
1064
+ paged = node.get("paged")
1065
+ if paged:
1066
+ lines.append(f"{' ' * (depth + 1)}[paged: {_claimed(paged['children'])} children examined, "
1067
+ f"{_claimed(paged['descendants'])} nodes below, stored as page "
1068
+ f"{paged['pointer']['sha256'][:12]}; circuit show {circuit} "
1069
+ f"node={node['id']}]")
1070
+ return lines
1071
+
1072
+
1073
+ def _count(item: Any) -> str:
1074
+ """A labelled count's value (its label is derived-exact or measured; the caller says which)."""
1075
+ return str(int(item["value"]))
1076
+
1077
+
1078
+ def _circuit_test_lines(test: dict[str, Any]) -> list[str]:
1079
+ """``circuit test ID ref=NAME``: the reference, the component counts, the four measured
1080
+ margins, the two ratios (or why they are refused), the one-spacing readings and the native
1081
+ layer calls per pass (wall time is in the result, not printed)."""
1082
+ ref = test["reference"]
1083
+ where = (f"run, row t{_count(ref['row'])}" if ref["kind"] == "run"
1084
+ else f"mean over {_count(ref['items'])} items at their @last")
1085
+ lines = [f"circuit {_count(test['id'])} test {test['consumer']} "
1086
+ f"ref {ref['name']} ({where})"]
1087
+ comp = test["components"]
1088
+ count = {key: _count(comp[key]) for key in
1089
+ ("total", "circuit", "complement", "from_groups", "unexamined")}
1090
+ coarse = _count(comp["coarsened"]["source_nodes"])
1091
+ lines.append(f" components [derived-exact] {count['total']}: circuit {count['circuit']}, "
1092
+ f"complement {count['complement']} ({count['from_groups']} from +N more groups, "
1093
+ f"{count['unexamined']} of them never expanded); {coarse} source node(s) "
1094
+ "counted as their head")
1095
+ lines.append(f" {test['components']['rows']}")
1096
+ margins = test["margins"]
1097
+ for key in ("base", "ref", "ko", "keep", "full"):
1098
+ extra = ""
1099
+ if key == "full" and "full_equals_ref" in test:
1100
+ extra = " (= ref bit for bit)" if test["full_equals_ref"] else " (differs from ref)"
1101
+ lines.append(f" {key:<5} {_claimed(margins[key])} {test['meaning'][key]}{extra}")
1102
+ ratios = test["ratios"]
1103
+ if ratios.get("state"):
1104
+ lines.append(f" ratios {num(ratios)}")
1105
+ else:
1106
+ for key, label in (("faithfulness", "faithfulness"), ("knockout_share",
1107
+ "knock-out share")):
1108
+ lines.append(f" {label} {ratios['formulas'][key]} = {_claimed(ratios[key])}: "
1109
+ f"{ratios['meaning'][key]}")
1110
+ reading, res = test["reading"], test["resolution"]
1111
+ lines.append(f" reading: knock-out {reading['knockout']}; {reading['keep_vs_base']}; "
1112
+ f"{reading['keep_vs_ref']} (one spacing {_claimed(res['spacing'])} "
1113
+ f"{res['dtype']})")
1114
+ passes = test["cost"]["per_pass"]
1115
+ lines.append(" layer calls completed [measured] " + " ".join(
1116
+ f"{key} {_count(passes[key]['calls']['completed'])}"
1117
+ for key in ("ko", "keep", "full")) + "; edits [derived-exact] " + " ".join(
1118
+ f"{key} {_count(passes[key]['edits'])}" for key in ("ko", "keep", "full")))
1119
+ return lines
1120
+
1121
+
1122
+ def _circuit_lines(result: dict[str, Any]) -> list[str]:
1123
+ if result["action"] == "test":
1124
+ lines = _circuit_test_lines(result["test"])
1125
+ if result.get("stored"):
1126
+ lines.append(f" stored record {result['stored'][0][:16]}")
1127
+ return lines
1128
+ if "page" in result:
1129
+ page = result["page"]
1130
+ lines = [f"circuit {result['id']} node {result['node']} "
1131
+ f"({'inline subtree' if page.get('state') == 'inline' else 'stored page'})"]
1132
+ marks = {}
1133
+ lines += [" " + line for line in _walk(page["node"], 0, marks, result.get("token_text"),
1134
+ result["id"])]
1135
+ return lines
1136
+ body = result["record"]["body"]
1137
+ lines = [f"circuit {result['id']} {body['consumer']} top {body['k']} depth "
1138
+ f"{body['depth']} ({body['count']} nodes, record {result['record']['id'][:16]})"]
1139
+ marks = {ref: name for name, refs in result.get("ablated", {}).items() for ref in refs}
1140
+ lines += [" " + line for line in _walk(body["root"], 0, marks, result.get("token_text"),
1141
+ result["id"])]
1142
+ closure = body["closure"]
1143
+ lines.append(f" closure {_short(closure['value'])} "
1144
+ f"{'within' if closure['within'] else 'OUTSIDE'} {_claimed(closure['bound'])} "
1145
+ f"(zero by construction: float64 summation only)")
1146
+ within = body["remainders_within"]
1147
+ state = ("all within their rounding bounds" if within
1148
+ else "NOT all within their rounding bounds" if within is not None
1149
+ else "not all bounded (a rounding bound was refused)")
1150
+ if body.get("unexamined") and within is not False:
1151
+ state = (f"{int(body['unexamined_count']['value'])} dropped subtree(s) not examined; no claim "
1152
+ "about their rounding bounds")
1153
+ lines.append(f" remainders: {state}; {body['edits']['count']} edit node(s)")
1154
+ for test in result.get("tests", ()):
1155
+ lines += [" " + line for line in _circuit_test_lines(test)]
1156
+ if result.get("stored"):
1157
+ lines.append(f" stored record {result['stored'][0][:16]}")
1158
+ return lines
1159
+
1160
+
1161
+ def _compare_lines(result: dict[str, Any]) -> list[str]:
1162
+ measured, effects = result["measured"], result["effects"]
1163
+ lines = [f"compare A: {result['sides']['A']} B: {result['sides']['B']} -> "
1164
+ f"{result['consumer']}"]
1165
+ lines.append(" " + " ".join(f"{name} {_short(item.get('value', item))}"
1166
+ for name, item in measured.items()))
1167
+ lines.append(" effects " + " ".join(f"{name} {_short(value)}"
1168
+ for name, value in effects.items()))
1169
+ verdicts = result.get("verdicts") or {}
1170
+ if verdicts:
1171
+ lines.append(" verdicts (native only, no exact or emulated chain: effect when edited and "
1172
+ "base differ): " + " ".join(f"{name} {v.get('label', v['verdict'])}"
1173
+ for name, v in verdicts.items()))
1174
+ interaction = result["interaction"]
1175
+ if interaction.get("state"):
1176
+ lines.append(f" interaction {num(interaction)}")
1177
+ else:
1178
+ lines.append(f" interaction {interaction['formula']} = {_short(interaction['value'])}")
1179
+ if "order" in result:
1180
+ lines.append(f" order: {result['order']}")
1181
+ for name, path in result.get("path", {}).items():
1182
+ if path.get("state"):
1183
+ lines.append(f" path {name}: {path['state']} ({path['reason']})")
1184
+ else:
1185
+ lines.append(f" path {name}: {path['verdict']} ({_path_text(path['path'])}); total "
1186
+ f"{_claimed(path['total'])}, frozen-selection {_claimed(path['frozen'])}")
1187
+ session = result["session"]
1188
+ lines.append(f" session {'unchanged' if session['unchanged'] else 'CHANGED'} at "
1189
+ f"{result['where']}")
1190
+ return lines
1191
+
1192
+
1193
+ def _symbol_lines(result: dict[str, Any]) -> list[str]:
1194
+ action = result.get("action")
1195
+ if action == "delete":
1196
+ return [f"symbol {result['symbol']} deleted (record {result['record'][:16]}); "
1197
+ f"{result['note']}"]
1198
+ if action in ("declare", "show"):
1199
+ body = result["body"] if action == "declare" else result["record"]["body"]
1200
+ record = result["record"] if action == "declare" else result["record"]["id"]
1201
+ lines = [f"symbol {result['symbol']} = {body['row']['address']} (record {record[:16]}"
1202
+ + (f", stored {result['stored'][0][:16]}" if result.get("stored") else "")
1203
+ + ")"]
1204
+ lines += _named_symbol_lines(body)
1205
+ if action == "show":
1206
+ lines.append(" here: " + _named_here(result["here"]))
1207
+ return lines
1208
+ return [f"symbol {result['symbol']} = {', '.join(result['definitions'])} (declared: "
1209
+ f"{', '.join(result['declared'])})"]
1210
+
1211
+
1212
+ def _named_here(here: dict[str, Any]) -> str:
1213
+ if here.get("state"):
1214
+ return f"{here['state']} ({here['reason']})"
1215
+ return f"{here['address']} (row {here['row']}: {here['how']})"
1216
+
1217
+
1218
+ def _named_symbol_lines(body: dict[str, Any]) -> list[str]:
1219
+ """A named symbol as schema plus bindings: role, row, readers, evidence, origin."""
1220
+ row, role, evidence = body["row"], body["role"], body["evidence"]
1221
+ writer = role["writer"]
1222
+ token = ""
1223
+ if "text" in row:
1224
+ token = f" {json.dumps(row['text'], ensure_ascii=False)}"
1225
+ elif "token" in row:
1226
+ token = f" (id {row['token']})"
1227
+ how = (f"role @{row['role']} ({row['role_source']})" if row["rule"] == "role"
1228
+ else "absolute (no role names this row)")
1229
+ lines = [f" role writer {writer['address']} ({writer['form']}, L{writer['layer']} "
1230
+ f"{writer['port']})",
1231
+ f" row t{row['row']}{token}: {how}; prompt {row['prompt_rows']} rows sha256 "
1232
+ f"{row['prompt_sha256'][:12]}"]
1233
+ readers = role["readers"]
1234
+ if readers.get("state") != "resolved":
1235
+ lines.append(f" readers {readers['state']} ({readers['reason']})")
1236
+ else:
1237
+ lines.append(f" readers of {readers['source']} at t{readers['rows'][0]} "
1238
+ f"({len(readers['listed'])} of {readers['count']} listed, at "
1239
+ f"{readers['at']}):")
1240
+ for read in readers["listed"]:
1241
+ causal = read.get("causal") or {}
1242
+ verdict = (f" {causal['verdict']} (Δ {_claimed(causal['delta'])})"
1243
+ if "delta" in causal else
1244
+ f" causal {causal['verdict']} ({causal.get('reason')})" if causal
1245
+ else " causal not measured")
1246
+ lines.append(f" {read['name']} mass {_claimed(read['mass'])} effect "
1247
+ f"{_claimed(read['effect'])}{verdict}")
1248
+ lines.append(f" effect {evidence['op']} {evidence['edit']} -> {body['consumer']['address']}"
1249
+ f": base {_claimed(evidence['base'])} -> edited {_claimed(evidence['edited'])},"
1250
+ f" Δ {_claimed(evidence['delta'])}, verdict {evidence['verdict']}")
1251
+ origin = body["origin"]
1252
+ donor = origin.get("donor", {})
1253
+ text = f" origin {origin['from']}; donor {donor.get('address', '?')}"
1254
+ if donor.get("sha256"):
1255
+ text += f" sha256 {donor['sha256'][:12]}"
1256
+ if origin.get("run"):
1257
+ text += f"; run {origin['run']}"
1258
+ if body.get("procedure"):
1259
+ text += f"; {body['procedure']['text']}"
1260
+ lines.append(text)
1261
+ edits = origin.get("edits") or {}
1262
+ if edits.get("committed") or edits.get("staged"):
1263
+ lines.append(f" edits committed {', '.join(edits.get('committed') or ['none'])}; "
1264
+ f"staged {', '.join(edits.get('staged') or ['none'])}")
1265
+ return lines
1266
+
1267
+
1268
+ def _seek_lines(result: dict[str, Any]) -> list[str]:
1269
+ lines = [f"seek {result['target']} via {result['via']}: " + ("; ".join(result["moves"])
1270
+ or "already there")]
1271
+ if result.get("dropped_edits"):
1272
+ lines.append(f" dropped edits: {', '.join(result['dropped_edits'])}")
1273
+ if result.get("restaged_edits"):
1274
+ lines.append(f" committed edits staged again: {', '.join(result['restaged_edits'])}")
1275
+ return lines + _motion(result)
1276
+
1277
+
1278
+ _INSPECT = {"reads": _reads_lines, "symbols": _symbols_lines, "symbol": _symbol_lines,
1279
+ "circuit": _circuit_lines, "compare": _compare_lines, "seek": _seek_lines}
1280
+
1281
+
1282
+ def _promo(item: dict[str, Any]) -> str:
1283
+ promotes = item.get("promotes")
1284
+ if not promotes:
1285
+ return ""
1286
+ texts = [json.dumps(t) if t is not None else str(i)
1287
+ for i, t in zip(promotes["ids"], promotes["texts"])]
1288
+ return f" promotes {' '.join(texts)} [derived-local]"
1289
+
1290
+
1291
+ def _features_lines(result: dict[str, Any]) -> list[str]:
1292
+ if result.get("mode") == "profile":
1293
+ lines = [f"features profile SAE {result['sae']} consumer {result['consumer']} = "
1294
+ f"{_short(result['native'])}" + (f" (each SAE applied {result['shift']:+d} "
1295
+ "layers off its site)" if result.get("shift")
1296
+ else ""),
1297
+ " layer direct(skip path) features bias ERROR error/direct "
1298
+ "|error| share ||e||/||x|| closure"]
1299
+ for row in result["layers"]:
1300
+ share = row["error_share_of_direct"]
1301
+ share = fmt(share["value"]) if "value" in share else share.get("state", "?")
1302
+ lines.append(
1303
+ f" {row['site']:<9} {fmt(row['direct']['value']):>10} "
1304
+ f"{fmt(row['features_sum']['value']):>10} {fmt(row['bias']['value']):>9} "
1305
+ f"{fmt(row['error']['value']):>9} {share:>10} "
1306
+ f"{fmt(row['error_share_of_abs']['value']):>10} "
1307
+ f"{fmt(row['error_fraction_of_norm']['value']):>10} "
1308
+ f"{fmt(row['closure']['value'])}")
1309
+ lines.append(" [derived-exact P19 except native (measured) and remainder (measured)]")
1310
+ return lines
1311
+ sae = result["sae"]
1312
+ stats_x = result["value"]["norm"]
1313
+ lines = [f"features {result['target']} SAE {sae['name']} L{sae['layer']} ({sae['site']}, "
1314
+ f"k {sae['k']}, {result['active']} active) ||x|| {_short(stats_x)}"]
1315
+ for item in result["features"]:
1316
+ line = (f" f{item['feature']:<6} act {_short(item['activation'])} "
1317
+ f"||d|| {fmt(item['decoder_norm']['value'])}")
1318
+ if "effect" in item:
1319
+ line += f" effect {_short(item['effect'])}"
1320
+ lines.append(line + _promo(item))
1321
+ more = result["more"]
1322
+ if more["count"]:
1323
+ line = f" +{more['count']} more act Σ {fmt(more['activation_sum']['value'])}"
1324
+ if "effect_sum" in more:
1325
+ line += f" effect Σ {_short(more['effect_sum'])}"
1326
+ lines.append(line)
1327
+ bias = result["bias"]
1328
+ lines.append(f" b_dec ||b|| {fmt(bias['norm']['value'])}"
1329
+ + (f" effect {_short(bias['effect'])}" if "effect" in bias else ""))
1330
+ err = result["error"]
1331
+ line = (f" ERROR ||e|| {_short(err['norm'])} ||e||/||x|| "
1332
+ f"{fmt(err['fraction_of_norm']['value'])} energy "
1333
+ f"{fmt(err['fraction_of_energy']['value'])}")
1334
+ if "effect" in err:
1335
+ line += f" effect {_short(err['effect'])}"
1336
+ lines.append(line)
1337
+ lines.append(f" identity x = b_dec + Σ a_f d_f + e closes to "
1338
+ f"{fmt(result['identity_closure']['value'])} [derived-exact]")
1339
+ acc = result.get("accounting")
1340
+ if acc:
1341
+ share = acc["error_share_of_direct"]
1342
+ share = fmt(share["value"]) if "value" in share else share.get("state", "?")
1343
+ lines.append(f" {acc['consumer']} {_short(acc['native'])} = direct {_short(acc['direct'])}"
1344
+ f" (features {fmt(acc['features_sum']['value'])} + bias "
1345
+ f"{fmt(acc['bias']['value'])} + error {fmt(acc['error']['value'])}) + later "
1346
+ f"layers {_short(acc['later_layers'])} + head bias "
1347
+ f"{fmt(acc['head_bias']['value'])} + remainder {_short(acc['remainder'])}")
1348
+ lines.append(f" error/direct {share} |error| share {fmt(acc['error_share_of_abs']['value'])}"
1349
+ f" closure {_short(acc['closure'])}")
1350
+ if result.get("match"):
1351
+ m = result["match"]
1352
+ lines.append(f" match {m['unit']}: {m['meaning']} ||v|| {fmt(m['norm']['value'])} "
1353
+ f"outside listed span {fmt(m['outside_fraction']['value'])} [derived-exact]")
1354
+ for item in m["features"]:
1355
+ act = (f" active here, act {fmt(item['activation']['value'])}"
1356
+ if item["active_here"] else " not active here")
1357
+ lines.append(f" f{item['feature']:<6} cos {_short(item['cos'])} coef "
1358
+ f"{fmt(item['coef']['value'])}{act}" + _promo(item))
1359
+ if result.get("circuit"):
1360
+ lines.append(f" circuit {result['circuit']['id']} stored (record "
1361
+ f"{result['circuit']['record'][:16]}): circuit show {result['circuit']['id']}")
1362
+ if result.get("under_edits"):
1363
+ lines.append(f" value under edits: {', '.join(result['under_edits'])}")
1364
+ return lines
1365
+
1366
+
1367
+ def _sae_lines(result: dict[str, Any]) -> list[str]:
1368
+ if "loaded" in result:
1369
+ s = result["loaded"]
1370
+ return [f"sae {s['name']}: {s['path']} site L<l>.{s['site_port']} k {s['k']} layers "
1371
+ f"{','.join(map(str, s['layers']))} revision {s['revision']} cache {s['cache']}"]
1372
+ if "dropped" in result:
1373
+ return [f"sae {result['dropped']} dropped"]
1374
+ lines = [f"{len(result['saes'])} SAE set(s)"]
1375
+ for s in result["saes"]:
1376
+ lines.append(f" {s['name']}: {s['path']} site L<l>.{s['site_port']} k {s['k']} "
1377
+ f"{len(s['layers'])} layers, loaded {s['loaded']}")
1378
+ for layer, info in s["files"].items():
1379
+ sha = info.get("sha256") or info.get("sha256_manifest")
1380
+ lines.append(f" L{layer} {info['file']} sha256 {sha}")
1381
+ return lines
1382
+
1383
+
1384
+ def _feature_trace_lines(result: dict[str, Any]) -> list[str]:
1385
+ lines = [f"feature f{result['feature']} of {result['site']} (SAE {result['sae']}): "
1386
+ f"{'active' if result['active_at_site'] else 'NOT active'} at its site, cutoff "
1387
+ f"{_short(result['cutoff'])}; first above cutoff {result['first_above']}, last "
1388
+ f"{result['last_above']}",
1389
+ " layer probe h probe r probe h_out write attn write mlp"]
1390
+ for p, w in zip(result["probe"], result["writers"]):
1391
+ lines.append(f" L{p['layer']:<5} {fmt(p['h']['value']):>9} {fmt(p['r']['value']):>9} "
1392
+ f"{fmt(p['h_out']['value']):>11} {fmt(w['attn']['value']):>11} "
1393
+ f"{fmt(w['mlp']['value']):>11}")
1394
+ heads = ", ".join(f"h{i['index']} {fmt(i['share']['value'])}"
1395
+ for i in result["heads"]["items"])
1396
+ neurons = ", ".join(f"f{i['index']} {fmt(i['share']['value'])}"
1397
+ for i in result["neurons"]["items"])
1398
+ lines.append(f" top heads of L{result['heads']['layer']}.attn: {heads} [derived-exact P07]")
1399
+ lines.append(f" top neurons of L{result['neurons']['layer']}.mlp: {neurons} "
1400
+ "[derived-exact P15]")
1401
+ return lines
1402
+
1403
+
1404
+ _INSPECT.update({"features": _features_lines, "sae": _sae_lines,
1405
+ "feature": _feature_trace_lines})
1406
+
1407
+
1408
+ def render_error(error: Any) -> str:
1409
+ data = error.to_json() if hasattr(error, "to_json") else {"type": "error",
1410
+ "message": str(error)}
1411
+ return f"error ({data['type']}): {data['message']}"
1412
+
1413
+
1414
+ # --------------------------------------------------------------------------- each / prompt sets
1415
+
1416
+
1417
+ def _cell(item: Any, labelled: bool, digits: int = 5) -> str:
1418
+ if isinstance(item, dict) and item.get("state") in ("unresolved", "refused"):
1419
+ return item["state"]
1420
+ if digits != 5 and isinstance(item["value"], float) and not isinstance(item["value"], bool):
1421
+ text = f"{item['value']:.{digits}g}"
1422
+ value = "0" if text in ("-0", "0") else text
1423
+ return f"{value} {tag(item.get('authority', '?'))}" if labelled else value
1424
+ return num(item) if labelled else fmt(item["value"])
1425
+
1426
+
1427
+ def _each_table(rows: list[dict[str, Any]], columns: list[str], uniform: dict[str, str],
1428
+ digits: int) -> list[tuple[list[str], str | None]]:
1429
+ """The table as (cells, refusal text) rows, header first; a refused row has its name only
1430
+ and the refusal text, which does not size any column."""
1431
+ has_label = any("label" in row.get("key", {}) for row in rows)
1432
+ has_verdict = any("verdict" in row.get("key", {}) for row in rows)
1433
+ table: list[tuple[list[str], str | None]] = [
1434
+ (["item"] + (["read"] if has_label else []) + columns
1435
+ + (["verdict"] if has_verdict else []), None)]
1436
+ for row in rows:
1437
+ if row["state"] == "refused":
1438
+ table.append(([row["name"]], f"refused: {row['reason']}"))
1439
+ continue
1440
+ key = row.get("key", {})
1441
+ cells = [row["name"]] + ([key.get("label", "-")] if has_label else [])
1442
+ for name in columns:
1443
+ item = key.get("columns", {}).get(name)
1444
+ cells.append("-" if item is None else _cell(item, name not in uniform, digits))
1445
+ if has_verdict:
1446
+ verdict = key.get("verdict", "")
1447
+ if row["state"] != "resolved":
1448
+ verdict = f"{verdict} ({row['state']})".strip()
1449
+ cells.append(verdict)
1450
+ table.append((cells, None))
1451
+ return table
1452
+
1453
+
1454
+ def _table_lines(table: list[tuple[list[str], str | None]]) -> tuple[list[str], int]:
1455
+ """Aligned lines (every column as wide as its widest cell by display width, two spaces
1456
+ between, the last column unpadded) and the width of the widest line."""
1457
+ count = len(table[0][0])
1458
+ widths = [max(_display_width(cells[i]) for cells, refusal in table
1459
+ if refusal is None or i == 0) for i in range(count)]
1460
+ out, widest = [], 0
1461
+ for cells, refusal in table:
1462
+ if refusal is not None:
1463
+ line = " " + _pad(cells[0], widths[0]) + " " + refusal
1464
+ else:
1465
+ line = " " + " ".join(_pad(c, widths[i]) if i < count - 1 else c
1466
+ for i, c in enumerate(cells)).rstrip()
1467
+ widest = max(widest, _display_width(line))
1468
+ out.append(line)
1469
+ return out, widest
1470
+
1471
+
1472
+ def _stat_lines(stat: dict[str, Any]) -> list[str]:
1473
+ def body(item: dict[str, Any]) -> str:
1474
+ agree = item["agree"]
1475
+ return (f"n {item['n']} mean {fmt(item['mean']['value'])} min "
1476
+ f"{fmt(item['min']['value'])} max {fmt(item['max']['value'])} sign "
1477
+ f"{agree['sign']} {agree['count']}/{item['n']}")
1478
+
1479
+ if stat.get("mixed"):
1480
+ lines = [f" {stat['path']} (mixed labels, summarised per label)"]
1481
+ for label, item in stat["by_authority"].items():
1482
+ lines.append(f" {tag(label)} {body(item)}")
1483
+ return lines
1484
+ return [f" {stat['path']} {tag(stat['mean']['authority'])}", f" {body(stat)}"]
1485
+
1486
+
1487
+ def _each_lines(result: dict[str, Any]) -> list[str]:
1488
+ """``each``: one row per item (name, key numbers, verdict), then the summary lines."""
1489
+ rows = result["items"]
1490
+ split = f" prefill={result['prefill']}" if "prefill" in result else ""
1491
+ lines = [f"each {result['set']}: {result['line']}",
1492
+ f" {result['total']} items at {result['at']}{split}; runs "
1493
+ f"{result['runs'].split(' ')[0]}; result {result['id']}"]
1494
+ columns: list[str] = []
1495
+ for row in rows:
1496
+ for name in row.get("key", {}).get("columns", {}):
1497
+ if name not in columns:
1498
+ columns.append(name)
1499
+ labels: dict[str, set[str]] = {name: set() for name in columns}
1500
+ for row in rows:
1501
+ for name, item in row.get("key", {}).get("columns", {}).items():
1502
+ labels[name].add(item.get("authority", item.get("state", "?")))
1503
+ uniform = {name: next(iter(found)) for name, found in labels.items() if len(found) == 1}
1504
+ for digits in (5, 4, 3): # shorten only numbers until the common case fits 80 columns
1505
+ table_lines, widest = _table_lines(_each_table(rows, columns, uniform, digits))
1506
+ if widest <= 80 or digits == 3:
1507
+ break
1508
+ lines += table_lines
1509
+ if uniform:
1510
+ lines.append(" labels: " + ", ".join(f"{name} {uniform[name]}" for name in columns
1511
+ if name in uniform))
1512
+ statistics = result["statistics"]
1513
+ lines.append(f"summary: {statistics['exclusion']}")
1514
+ numeric = statistics["numeric"]
1515
+ shown = numeric[:len(columns) or 2]
1516
+ for stat in shown:
1517
+ lines += _stat_lines(stat)
1518
+ verdicts = [item for item in statistics["verdicts"]
1519
+ if item["path"].rsplit(".", 1)[-1] == "verdict" or len(item["counts"]) > 1
1520
+ or item["counts"][0]["label"] != "resolved"]
1521
+ for item in verdicts[:4]:
1522
+ counts = " / ".join(f"{c['label']} {c['count']}" for c in item["counts"])
1523
+ lines.append(f" {item['path']}: {counts}")
1524
+ more = (len(numeric) - len(shown) + len(statistics["verdicts"]) - len(verdicts[:4])
1525
+ + statistics["omitted"]["count"])
1526
+ partial = statistics["partial"]["count"]
1527
+ tail = []
1528
+ if more:
1529
+ tail.append(f"+{more} more in the record")
1530
+ if partial:
1531
+ tail.append(f"{partial} paths in some items only")
1532
+ if tail:
1533
+ lines.append(" " + "; ".join(tail) + f" (promptset result {result['id']} [ITEM])")
1534
+ if "stored" in result:
1535
+ stored = result["stored"]
1536
+ lines.append(f" stored record {stored[:16]}" if isinstance(stored, str)
1537
+ else f" not stored: {stored['reason']}")
1538
+ return lines
1539
+
1540
+
1541
+ def _promptset_lines(result: dict[str, Any]) -> list[str]:
1542
+ if result["action"] == "list":
1543
+ return [f"{item['set']:<12}{item['total']} items ({item['source']})"
1544
+ for item in result["sets"]] or ["no prompt sets"]
1545
+ if result["action"] == "result":
1546
+ if "result" in result:
1547
+ return [f"{result['id']} item {result['item']}:", _render(result["result"])]
1548
+ return _each_lines({**result["summary"], "id": result["id"]})
1549
+ lines = [f"set {result['set']}: {result['total']} items ({result['source']})"]
1550
+ shown = result["items"]
1551
+ if result["action"] in ("load", "define") and len(shown) > 10: # show prints them all
1552
+ shown = shown[:5]
1553
+ for item in shown:
1554
+ prompt = (json.dumps(item["prompt"]) if "prompt" in item
1555
+ else " ".join(map(str, item["ids"]))
1556
+ + (" ..." if item["prompt_tokens"] > len(item["ids"]) else ""))
1557
+ roles = " ".join(f"@{r['name']}={r['row']}" for r in item["roles"])
1558
+ variables = " ".join(f"${v['name']}={v.get('token', json.dumps(v.get('text')))}"
1559
+ for v in item["vars"])
1560
+ pair = f" pair {item['pair']}" if "pair" in item else ""
1561
+ lines.append(f" {item['name']:<10}{prompt} {roles} {variables}{pair}".rstrip())
1562
+ if len(shown) < len(result["items"]):
1563
+ lines.append(f" +{len(result['items']) - len(shown)} more (set show {result['set']})")
1564
+ return lines
1565
+
1566
+
1567
+ _INSPECT["each"] = _each_lines
1568
+ _INSPECT["promptset"] = _promptset_lines
1569
+
1570
+
1571
+ # --------------------------------------------------------------------------- procedure / sweep
1572
+
1573
+
1574
+ def _procedure_lines(result: dict[str, Any]) -> list[str]:
1575
+ """The prefill split of a run (``prefill``) as one line, when it is not the default (all
1576
+ prompt rows but the last batched); the JSON always carries it."""
1577
+ prefill = result.get("prefill")
1578
+ if not isinstance(prefill, dict) or prefill.get("default", True):
1579
+ return []
1580
+ return [prefill["text"]]
1581
+
1582
+
1583
+ _HEAT_WIDTH = 80
1584
+
1585
+
1586
+ def _heat_cell(value: float, scale: float, width: int) -> str:
1587
+ """One cell of the heat table: the signed tenths of the largest |delta| (``+9`` .. ``-9``),
1588
+ ``.`` below a twentieth, ``0`` for an exact zero."""
1589
+ if value == 0:
1590
+ text = "0"
1591
+ elif scale == 0 or abs(value) / scale < 0.05:
1592
+ text = "."
1593
+ else:
1594
+ tenths = min(9, max(1, round(abs(value) / scale * 10)))
1595
+ text = ("+" if value > 0 else "-") + str(tenths)
1596
+ return text.rjust(width)
1597
+
1598
+
1599
+ def _token_label(item: dict[str, Any], width: int) -> str:
1600
+ text = item.get("text")
1601
+ if text is None:
1602
+ return str(item.get("token", "?"))[-width:].rjust(width)
1603
+ shown = text.replace(" ", "·").replace("\n", "↵")
1604
+ return shown[:width].rjust(width)
1605
+
1606
+
1607
+ def heat_table(result: dict[str, Any], width: int = _HEAT_WIDTH) -> list[str]:
1608
+ """The rows x layers table of a ``sweep`` as text of at most ``width`` columns: one line per
1609
+ layer, one column per position (row index, and the token text when a tokenizer exists), a
1610
+ cell the signed tenths of the largest |delta|. Positions that do not fit are cut from the
1611
+ left and said so (the record holds them all). A sweep whose table is a blob is drawn from
1612
+ its ``heat`` text (the same codes, computed by the op)."""
1613
+ if "table" in result:
1614
+ table = result["table"]
1615
+ rows, layers, grid = table["rows"], table["layers"], table["delta"]["value"]
1616
+ scale = max((abs(v) for line in grid for v in line), default=0.0)
1617
+ tokens = {item["row"]: item for item in table.get("tokens", ())}
1618
+
1619
+ def code(i: int, j: int, cell: int) -> str:
1620
+ return _heat_cell(grid[i][j], scale, cell)
1621
+ else:
1622
+ heat = result["heat"]
1623
+ low, high = (int(x) for x in heat["rows"].split(":"))
1624
+ first, last = (int(x) for x in heat["layers"].split(":"))
1625
+ rows, layers = list(range(low, high)), list(range(first, last))
1626
+ codes = [line.split(" ") for line in heat["cells"].split("\n")]
1627
+ scale = heat["scale"]["value"]
1628
+ tokens = {r: {"row": r, "text": t} for r, t in zip(rows, heat.get("tokens", ()))}
1629
+
1630
+ def code(i: int, j: int, cell: int) -> str:
1631
+ return codes[i][j].rjust(cell)
1632
+ label = max(len(f"L{layers[-1]}"), 3) + 1
1633
+ need = max(3, len(f"t{rows[-1]}") + 1) # t18 needs 4 columns, not a jammed 3
1634
+ cell = next((c for c in (need, 3) if label + c * len(rows) <= width), 2)
1635
+ fit = max(1, (width - label) // cell)
1636
+ start = max(0, len(rows) - fit)
1637
+ shown = list(range(start, len(rows)))
1638
+ lines = [" " * label + "".join(f"t{rows[j]}"[-cell:].rjust(cell) for j in shown)]
1639
+ if any("text" in tokens.get(rows[j], {}) for j in shown):
1640
+ lines.append(" " * label + "".join(_token_label(tokens[rows[j]], cell) for j in shown))
1641
+ for i, layer in enumerate(layers):
1642
+ lines.append(f"L{layer}".ljust(label) + "".join(code(i, j, cell) for j in shown))
1643
+ if start:
1644
+ lines.append(f"(t{rows[0]}..t{rows[start - 1]} cut to fit; the table holds them)")
1645
+ lines.append(f"cell: tenths of max |Δ| {fmt(scale)} [measured] (9 caps); '.' < 1/20, "
1646
+ "'0' exact")
1647
+ return lines
1648
+
1649
+
1650
+ def _sweep_lines(result: dict[str, Any]) -> list[str]:
1651
+ base = result["base"]
1652
+ if "donors" in result: # several origins (multi-donor mode)
1653
+ d = {k: v["value"] if isinstance(v, dict) and "value" in v else v
1654
+ for k, v in result["donors"].items()}
1655
+ return [f"sweep {result['port']} = {{{result['origin']}}}:{result['port']} -> "
1656
+ f"{result['consumer']} ({result['cells']['count']} cells x {d['n_donors']} "
1657
+ f"donors; base {num(base)})",
1658
+ f" cells with an effect from >= 1 donor: {d['cells_effect']} of "
1659
+ f"{result['cells']['count']} [measured]",
1660
+ f" single-donor nulls: {d['single_origin_nulls']}, overturned by another donor: "
1661
+ f"{d['single_origin_nulls_overturned']} [measured]",
1662
+ f" records: {', '.join(r[:16] for r in result['records'])}",
1663
+ f" session unchanged at {result['where']}"]
1664
+ lines = [f"sweep {result['port']} = {result['origin']}:{result['port']} -> "
1665
+ f"{result['consumer']} ({result['cells']['count']} cells; base "
1666
+ f"{num(base)})"]
1667
+ lines.extend(f" {line}" for line in _procedure_lines(result))
1668
+ if "table" in result:
1669
+ lines.extend(heat_table(result))
1670
+ else:
1671
+ pointer = result["table_pointer"]
1672
+ lines.append(f" table: {pointer['state']} blob sha256 {pointer['sha256'][:12]} "
1673
+ f"({pointer.get('reason') or str(pointer.get('bytes', '')) + ' bytes'})")
1674
+ if "cells" in result.get("heat", {}):
1675
+ lines.extend(heat_table(result))
1676
+ top = ", ".join(f"t{item['row']}.L{item['layer']} {num(item['delta'])}"
1677
+ for item in result["top"])
1678
+ lines.append(f" top |Δ|: {top}")
1679
+ if "nulls" in result:
1680
+ lines.append(f" nulls: {result['nulls']['label']}")
1681
+ if "path" in result:
1682
+ cells = result["path"]["cells"]
1683
+ lines.append(f" path-diverged: {result['path']['diverged']['value']} of "
1684
+ f"{result['cells']['count']} cells [measured]"
1685
+ + (f" ({', '.join(cells)})" if cells else "")
1686
+ + "; frozen-selection deltas in table.frozen_delta")
1687
+ cost = result["cost"]
1688
+ native = cost["native"]
1689
+ planned = cost.get("planned", {}).get("layer")
1690
+ lines.append(f" cost: {native['layer']['value']} layer calls"
1691
+ + (f" (planned {planned['value']})" if planned else "")
1692
+ + f", {native['probe']['value']} probes, "
1693
+ f"{native['transition']['value']} other transitions [measured] "
1694
+ "(wall time in the result: cost.seconds)")
1695
+ lines.append(f" session unchanged at {result['where']}")
1696
+ return lines
1697
+
1698
+
1699
+ _INSPECT["sweep"] = _sweep_lines