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.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
mdb/machines/x86/mlp.py
ADDED
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
"""torchx86's ALU dispatch as a gated MLP, read as mdb sites.
|
|
2
|
+
|
|
3
|
+
torchx86's ``Dispatch`` computes every ALU class on every lane (``up``), gates by the decoded class
|
|
4
|
+
(``gate``), ``f = gate * up``, ``down = sum_k f[k]``. This module records those four sites per
|
|
5
|
+
lane-step and gives them addresses and verbs::
|
|
6
|
+
|
|
7
|
+
i<t>.mlp.up[k] class k's outputs as 134 bits: value (64) | value2 (64) | CF PF AF ZF SF OF
|
|
8
|
+
i<t>.mlp.gate[k] class k's gate (hard: one-hot of the decoded class; soft: softmax(onehot / tau))
|
|
9
|
+
i<t>.mlp.f[k] gate[k] * up[k]
|
|
10
|
+
i<t>.mlp.down the dispatch output as 134 bits (hard: exact; soft: sum_k f[k] > 0.5)
|
|
11
|
+
|
|
12
|
+
``k`` is a class index or a torchx86 class name (``add``, ``xor``, ...). ``t`` is the tick (the
|
|
13
|
+
instruction index, from 0) during which the dispatch ran.
|
|
14
|
+
|
|
15
|
+
``attribute`` names the class unit responsible for ``down`` from ``f`` and ``down`` alone (it never
|
|
16
|
+
reads the decoded class): the exact contribution ``c_k = sum_{j: down_j} f[k, j]`` and the ablation
|
|
17
|
+
``a_k`` = number of output bits that flip when ``f[k]`` is zeroed. A unit is named when its score
|
|
18
|
+
is the unique maximum and > 0; otherwise nothing is named (-1). Given the gate too, it also marks
|
|
19
|
+
the *selected but zero-valued* units (gate on, every bit of ``f[k]`` zero:
|
|
20
|
+
``analysis.numerics.units``),
|
|
21
|
+
and ``named_selected`` names the unique one: run 6's "nothing named" steps were all of this kind
|
|
22
|
+
(a ``mov`` of 0), where the selection lives only in the gate.
|
|
23
|
+
|
|
24
|
+
The SAE here is a minimal top-k SAE in the layout mdb's ``FeatureBasis`` stores (``W_enc (w, d)``,
|
|
25
|
+
``b_enc``, ``W_dec (d, w)``, ``b_dec``, active set = top-k of ``relu(W_enc x + b_enc)``). mdb has no
|
|
26
|
+
SAE trainer, and ``FeatureBasis`` only accepts residual ports (``h``, ``h_out``) of a language model.
|
|
27
|
+
"""
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import re
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
|
|
33
|
+
import torch
|
|
34
|
+
|
|
35
|
+
from mdb.core.records import seal_record
|
|
36
|
+
|
|
37
|
+
from .binary import Binary, torchx86
|
|
38
|
+
from .lanes import Lanes
|
|
39
|
+
from .session import verdict_of # also declares the machine-whatif record kinds
|
|
40
|
+
from .trace import default_input
|
|
41
|
+
|
|
42
|
+
NB = 134 # bits per class unit: value 64, value2 64, six flags
|
|
43
|
+
_ADDR = re.compile(r"^i(?P<t>\d+)\.mlp\.(?P<site>up|gate|f|down)(?:\[(?P<k>\w+)\])?$")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def classes() -> tuple:
|
|
47
|
+
torchx86()
|
|
48
|
+
from torchx86.decode import CLASSES # noqa: PLC0415
|
|
49
|
+
|
|
50
|
+
return CLASSES
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def bits_of(words: torch.Tensor) -> torch.Tensor:
|
|
54
|
+
"""[..., 8] int64 (value, value2, 6 flags) -> [..., 134] uint8."""
|
|
55
|
+
sh = torch.arange(64, device=words.device)
|
|
56
|
+
v = (words[..., 0, None] >> sh) & 1
|
|
57
|
+
v2 = (words[..., 1, None] >> sh) & 1
|
|
58
|
+
return torch.cat([v, v2, (words[..., 2:] != 0).long()], -1).to(torch.uint8)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def words_of(bits: torch.Tensor) -> tuple[int, int, int]:
|
|
62
|
+
"""134 bits -> (value, value2, flag bits CF..OF as an int), unsigned."""
|
|
63
|
+
b = [int(x) for x in bits.reshape(-1).tolist()]
|
|
64
|
+
w = lambda s: sum(bit << i for i, bit in enumerate(b[s:s + 64]))
|
|
65
|
+
return w(0), w(64), sum(bit << i for i, bit in enumerate(b[128:]))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# --------------------------------------------------------------------------- capture
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class Capture:
|
|
73
|
+
"""One batched run in a gated dispatch mode. Per lane-step (``[B, T]``): ``pc`` (-1 once the
|
|
74
|
+
lane has stopped), ``up`` uint8 ``[B, T, K, 134]``, ``gate`` float ``[B, T, K]``, ``down`` uint8
|
|
75
|
+
``[B, T, 134]`` (the machine's own output). ``result`` is the lanes' ``Result``."""
|
|
76
|
+
pc: torch.Tensor
|
|
77
|
+
up: torch.Tensor
|
|
78
|
+
gate: torch.Tensor
|
|
79
|
+
down: torch.Tensor
|
|
80
|
+
result: object
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def live(self) -> torch.Tensor:
|
|
84
|
+
return self.pc >= 0
|
|
85
|
+
|
|
86
|
+
def f(self) -> torch.Tensor:
|
|
87
|
+
return self.gate[..., None] * self.up.float()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def capture(binary: Binary, inputs: list, *, mode: str = "hard", tau=1.0, device="cpu", cap: int = 20000,
|
|
91
|
+
edit: tuple | None = None) -> Capture:
|
|
92
|
+
"""Run every input on its own lane with ``Dispatch(mode, tau)`` and record the four sites.
|
|
93
|
+
|
|
94
|
+
``tau`` may be a float or a tensor ``[B, 1]`` (one temperature per lane). ``edit = (t, k, value)``
|
|
95
|
+
replaces ``gate[k]`` with ``value`` on every lane while it executes tick ``t`` (the gate is the
|
|
96
|
+
machine's own: int64 one-hot under ``hard``)."""
|
|
97
|
+
torchx86()
|
|
98
|
+
from torchx86.machine import Dispatch # noqa: PLC0415
|
|
99
|
+
|
|
100
|
+
lanes = Lanes(binary, inputs, device=device, cap=cap)
|
|
101
|
+
m = lanes.m
|
|
102
|
+
if torch.is_tensor(tau):
|
|
103
|
+
tau = tau.to(m.dev)
|
|
104
|
+
m.dispatch = Dispatch(mode, tau)
|
|
105
|
+
d = m.dispatch
|
|
106
|
+
ups, gates, downs = [], [], []
|
|
107
|
+
|
|
108
|
+
def on_up(_m, _i, out):
|
|
109
|
+
ups.append(bits_of(out) if mode == "hard" else out.to(torch.uint8))
|
|
110
|
+
|
|
111
|
+
def on_gate(_m, _i, out):
|
|
112
|
+
if edit is not None:
|
|
113
|
+
t, k, v = edit
|
|
114
|
+
hit = m.steps == t
|
|
115
|
+
out = out.clone()
|
|
116
|
+
out[:, k] = torch.where(hit, torch.as_tensor(v, dtype=out.dtype, device=out.device), out[:, k])
|
|
117
|
+
gates.append(out.float())
|
|
118
|
+
return out
|
|
119
|
+
|
|
120
|
+
def on_down(_m, _i, out):
|
|
121
|
+
downs.append(bits_of(out) if mode == "hard" else (out > 0.5).to(torch.uint8))
|
|
122
|
+
|
|
123
|
+
hooks = [d.up.register_forward_hook(on_up), d.gate.register_forward_hook(on_gate),
|
|
124
|
+
d.down.register_forward_hook(on_down)]
|
|
125
|
+
try:
|
|
126
|
+
res = lanes.run(record="pc")
|
|
127
|
+
finally:
|
|
128
|
+
for h in hooks:
|
|
129
|
+
h.remove()
|
|
130
|
+
st = lambda xs: torch.stack(xs, 1)
|
|
131
|
+
return Capture(res.pc, st(ups), st(gates), st(downs), res)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def decoded_class(binary: Binary, pc: torch.Tensor) -> torch.Tensor:
|
|
135
|
+
"""The decoded ALU class per tick (-1 where pc < 0). Scoring only: attribution never reads it."""
|
|
136
|
+
sorted_pcs = torch.tensor(binary.pcs, dtype=torch.int64, device=pc.device)
|
|
137
|
+
j = torch.searchsorted(sorted_pcs, pc.clamp(min=0)).clamp(max=len(binary.pcs) - 1)
|
|
138
|
+
row = torch.where(sorted_pcs[j] == pc, j + 1, 0)
|
|
139
|
+
cls = torch.tensor(binary.rows[:, binary.F["cls"]], device=pc.device)[row]
|
|
140
|
+
return torch.where(pc >= 0, cls, -1)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# --------------------------------------------------------------------------- attribution
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def attribute(f: torch.Tensor, down: torch.Tensor, gate: torch.Tensor | None = None,
|
|
147
|
+
gate_floor: float = 0.5) -> dict:
|
|
148
|
+
"""Blind attribution of ``down`` [N, 134] to the class units of ``f`` [N, K, 134].
|
|
149
|
+
|
|
150
|
+
``contribution[n, k] = sum_{j: down_j} f[n, k, j]`` (exact share of the firing bits' pre-threshold
|
|
151
|
+
mass); ``ablation[n, k]`` = number of bits of ``(sum f - f[k]) > 0.5`` that differ from ``down``.
|
|
152
|
+
``named_*`` is the unique argmax with a positive score, else -1. With ``gate`` [N, K]:
|
|
153
|
+
``selected_zero[n, k]`` (gate >= ``gate_floor`` and ``f[n, k]`` all zero) and ``named_selected``,
|
|
154
|
+
the unique such unit, else -1."""
|
|
155
|
+
from mdb.analysis.numerics.units import selected_zero # noqa: PLC0415
|
|
156
|
+
|
|
157
|
+
on = down.bool()
|
|
158
|
+
contrib = (f * on[:, None, :]).sum(-1)
|
|
159
|
+
pre = f.sum(1)
|
|
160
|
+
abl = (((pre[:, None, :] - f) > 0.5) != on[:, None, :]).sum(-1).float()
|
|
161
|
+
out = {"contribution": contrib, "ablation": abl,
|
|
162
|
+
"named_contribution": _unique_argmax(contrib), "named_ablation": _unique_argmax(abl)}
|
|
163
|
+
if gate is not None:
|
|
164
|
+
sel = selected_zero(gate, f.abs().sum(-1), gate_floor=gate_floor, zero_tol=0.0)
|
|
165
|
+
out["selected_zero"] = sel
|
|
166
|
+
out["named_selected"] = torch.where(sel.sum(-1) == 1, sel.float().argmax(-1), -1)
|
|
167
|
+
return out
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _unique_argmax(s: torch.Tensor) -> torch.Tensor:
|
|
171
|
+
top = s.max(-1)
|
|
172
|
+
unique = (s == top.values[:, None]).sum(-1) == 1
|
|
173
|
+
return torch.where(unique & (top.values > 0), top.indices, -1)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def attribute_capture(cap: Capture, chunk: int = 1 << 14) -> dict:
|
|
177
|
+
"""``attribute`` over every live lane-step of a capture (flattened, lane-major)."""
|
|
178
|
+
live = cap.live
|
|
179
|
+
up, gate, down = cap.up[live], cap.gate[live], cap.down[live]
|
|
180
|
+
out = {"named_contribution": [], "named_ablation": [], "named_selected": []}
|
|
181
|
+
for s in range(0, len(up), chunk):
|
|
182
|
+
r = attribute(gate[s:s + chunk, :, None] * up[s:s + chunk].float(), down[s:s + chunk],
|
|
183
|
+
gate[s:s + chunk])
|
|
184
|
+
for key in out:
|
|
185
|
+
out[key].append(r[key])
|
|
186
|
+
return {k: torch.cat(v) if v else torch.zeros(0, dtype=torch.long) for k, v in out.items()}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# --------------------------------------------------------------------------- usage
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def usage(cap: Capture, cls: torch.Tensor, loop_heads) -> list[dict]:
|
|
193
|
+
"""Per lane: class units gated on per step, units with nonzero f, nonzero f coordinates, the union
|
|
194
|
+
of gated units over the run and the tick at which it saturates, and the end of the first loop
|
|
195
|
+
iteration (the first return to a loop head already visited)."""
|
|
196
|
+
K = cap.gate.shape[-1]
|
|
197
|
+
heads = torch.tensor(sorted(loop_heads) or [-2], device=cap.pc.device)
|
|
198
|
+
out = []
|
|
199
|
+
for lane in range(cap.pc.shape[0]):
|
|
200
|
+
live = cap.live[lane]
|
|
201
|
+
T = int(live.sum())
|
|
202
|
+
g = cap.gate[lane, :T] != 0 # [T, K]
|
|
203
|
+
fnz = (cap.gate[lane, :T, :, None] * cap.up[lane, :T].float()) != 0
|
|
204
|
+
first = torch.where(g.any(0), g.float().argmax(0), -1) # first tick each unit is on
|
|
205
|
+
used = first >= 0
|
|
206
|
+
coord_first = torch.where(fnz.any(0), fnz.float().argmax(0), -1)
|
|
207
|
+
pcs = cap.pc[lane, :T]
|
|
208
|
+
at_head = (pcs[:, None] == heads).any(1)
|
|
209
|
+
loop1 = -1
|
|
210
|
+
seen = set()
|
|
211
|
+
for t in torch.nonzero(at_head).flatten().tolist():
|
|
212
|
+
p = int(pcs[t])
|
|
213
|
+
if p in seen:
|
|
214
|
+
loop1 = t
|
|
215
|
+
break
|
|
216
|
+
seen.add(p)
|
|
217
|
+
sat = int(first[used].max()) if used.any() else -1
|
|
218
|
+
out.append({
|
|
219
|
+
"T": T, "K": K,
|
|
220
|
+
"units_on_per_step_mean": float(g.sum(1).float().mean()),
|
|
221
|
+
"units_on_per_step_max": int(g.sum(1).max()),
|
|
222
|
+
"units_f_nonzero_per_step_mean": float(fnz.any(-1).sum(1).float().mean()),
|
|
223
|
+
"coords_f_nonzero_per_step_mean": float(fnz.sum((1, 2)).float().mean()) / (K * NB),
|
|
224
|
+
"union_units": int(used.sum()), "union_units_frac": int(used.sum()) / K,
|
|
225
|
+
"union_classes_decoded": len(set(cls[lane, :T].tolist())),
|
|
226
|
+
"union_saturation_tick": sat,
|
|
227
|
+
"union_coords_frac": int((coord_first >= 0).sum()) / (K * NB),
|
|
228
|
+
"union_coords_saturation_tick": int(coord_first.max()),
|
|
229
|
+
"first_loop_iteration_end_tick": loop1,
|
|
230
|
+
"union_units_at_loop1_end": int((used & (first <= loop1)).sum()) if loop1 >= 0 else 0,
|
|
231
|
+
"units": sorted(torch.nonzero(used).flatten().tolist()),
|
|
232
|
+
})
|
|
233
|
+
return out
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# --------------------------------------------------------------------------- SAE
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def train_topk_sae(X: torch.Tensor, groups: list, *, width: int, k: int, steps: int = 2000, batch: int = 512,
|
|
240
|
+
lr: float = 1e-3, seed: int = 0) -> dict:
|
|
241
|
+
"""Train ``len(groups)`` independent top-k SAEs at once; group g sees rows ``X[groups[g]]``.
|
|
242
|
+
|
|
243
|
+
Returns float32 tensors ``W_enc [G, w, d]``, ``b_enc [G, w]``, ``W_dec [G, d, w]``, ``b_dec [G, d]``
|
|
244
|
+
(``FeatureBasis`` layout per group) and the final batch MSE per group. Decoder columns are kept
|
|
245
|
+
at unit norm; ``b_dec`` starts at the group mean, ``W_enc`` at ``W_dec^T``."""
|
|
246
|
+
gen = torch.Generator(device="cpu").manual_seed(seed)
|
|
247
|
+
dev, G, d = X.device, len(groups), X.shape[1]
|
|
248
|
+
W_dec = torch.randn(G, d, width, generator=gen).to(dev)
|
|
249
|
+
W_dec /= W_dec.norm(dim=1, keepdim=True)
|
|
250
|
+
W_dec.requires_grad_(True)
|
|
251
|
+
W_enc = W_dec.detach().transpose(1, 2).clone().requires_grad_(True)
|
|
252
|
+
b_enc = torch.zeros(G, width, device=dev, requires_grad=True)
|
|
253
|
+
b_dec = torch.stack([X[g].float().mean(0) for g in groups]).requires_grad_(True)
|
|
254
|
+
sizes = torch.tensor([len(g) for g in groups], device=dev)
|
|
255
|
+
flat = torch.cat([torch.as_tensor(g, device=dev) for g in groups])
|
|
256
|
+
offs = torch.cumsum(sizes, 0) - sizes
|
|
257
|
+
opt = torch.optim.Adam([W_enc, b_enc, W_dec, b_dec], lr=lr)
|
|
258
|
+
gdev = torch.Generator(device=dev).manual_seed(seed)
|
|
259
|
+
for _ in range(steps):
|
|
260
|
+
r = (torch.rand(G, batch, device=dev, generator=gdev) * sizes[:, None]).long()
|
|
261
|
+
xb = X[flat[offs[:, None] + r]].float() # [G, b, d]
|
|
262
|
+
a = _encode(xb, W_enc, b_enc, b_dec, k)
|
|
263
|
+
recon = torch.einsum("gbw,gdw->gbd", a, W_dec) + b_dec[:, None]
|
|
264
|
+
loss_g = ((recon - xb) ** 2).sum(-1).mean(-1)
|
|
265
|
+
opt.zero_grad()
|
|
266
|
+
loss_g.sum().backward()
|
|
267
|
+
opt.step()
|
|
268
|
+
with torch.no_grad():
|
|
269
|
+
W_dec /= W_dec.norm(dim=1, keepdim=True).clamp(min=1e-8)
|
|
270
|
+
p = {n: t.detach() for n, t in (("W_enc", W_enc), ("b_enc", b_enc), ("W_dec", W_dec), ("b_dec", b_dec))}
|
|
271
|
+
p["k"] = k
|
|
272
|
+
p["final_mse"] = loss_g.detach()
|
|
273
|
+
return p
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _encode(x, W_enc, b_enc, b_dec, k): # noqa: ARG001 (b_dec is not applied to the input, as in FeatureBasis)
|
|
277
|
+
pre = torch.relu(torch.einsum("gbd,gwd->gbw", x, W_enc) + b_enc[:, None]) # FeatureBasis.select rule
|
|
278
|
+
v, i = pre.topk(k, -1)
|
|
279
|
+
return torch.zeros_like(pre).scatter(-1, i, v)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def sae_encode(p: dict, g: int, x: torch.Tensor) -> torch.Tensor:
|
|
283
|
+
"""Activations [N, w] of group g's SAE on rows x [N, d] (top-k rule)."""
|
|
284
|
+
with torch.no_grad():
|
|
285
|
+
return _encode(x.float()[None], p["W_enc"][g:g + 1], p["b_enc"][g:g + 1], p["b_dec"][g:g + 1], p["k"])[0]
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def purity(acts: torch.Tensor, cls: torch.Tensor, K: int) -> list[dict]:
|
|
289
|
+
"""Per feature: firing count, modal class, class purity among the rows where it is active."""
|
|
290
|
+
on = acts > 0
|
|
291
|
+
onehot = torch.nn.functional.one_hot(cls.clamp(min=0), K).float()
|
|
292
|
+
counts = on.float().T @ onehot # [w, K]
|
|
293
|
+
n = counts.sum(1)
|
|
294
|
+
mode = counts.argmax(1)
|
|
295
|
+
return [{"feature": i, "fires": int(n[i]), "mode_class": int(mode[i]),
|
|
296
|
+
"purity": float(counts[i, mode[i]] / n[i]) if n[i] > 0 else None} for i in range(acts.shape[1])]
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def value_split(acts: torch.Tensor, X: torch.Tensor, cls: torch.Tensor, feats: list[dict], K: int) -> dict:
|
|
300
|
+
"""Does a class's data split across features by value? For each live feature with purity >= 0.9:
|
|
301
|
+
the bit agreement of its active rows (mean over the class block's bits of max(p, 1-p)) minus the
|
|
302
|
+
same over all rows of its class. Also: per class, how many pure features it has."""
|
|
303
|
+
lifts, per_class = [], {}
|
|
304
|
+
for ft in feats:
|
|
305
|
+
if not ft["fires"] or ft["purity"] < 0.9:
|
|
306
|
+
continue
|
|
307
|
+
c = ft["mode_class"]
|
|
308
|
+
blk = X[:, c * NB:(c + 1) * NB].float()
|
|
309
|
+
rows = (acts[:, ft["feature"]] > 0) & (cls == c)
|
|
310
|
+
allc = cls == c
|
|
311
|
+
agree = lambda m: float(torch.maximum(blk[m].mean(0), 1 - blk[m].mean(0)).mean())
|
|
312
|
+
lifts.append(agree(rows) - agree(allc))
|
|
313
|
+
per_class[c] = per_class.get(c, 0) + 1
|
|
314
|
+
return {"pure_features": len(lifts), "mean_bit_agreement_lift": sum(lifts) / len(lifts) if lifts else None,
|
|
315
|
+
"classes_with_2plus_pure_features": sum(v >= 2 for v in per_class.values()),
|
|
316
|
+
"pure_features_per_class": {str(k): v for k, v in sorted(per_class.items())}}
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
# --------------------------------------------------------------------------- a debugger view
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
class MlpRun:
|
|
323
|
+
"""One input's run with the dispatch as sites: ``print``/``read`` an ``i<t>.mlp.*`` address,
|
|
324
|
+
``attribute(t)``, and ``whatif`` on a gate unit (sealed prediction of ``down``, then native)."""
|
|
325
|
+
|
|
326
|
+
def __init__(self, program, input: bytes | None = None, *, device="cpu", cap: int | None = None):
|
|
327
|
+
self.binary = program if isinstance(program, Binary) else Binary.load(program)
|
|
328
|
+
self.input = input if input is not None else default_input(self.binary)
|
|
329
|
+
self.device = device
|
|
330
|
+
self.cap = cap or 20000
|
|
331
|
+
self.cap_ = capture(self.binary, [self.input], device=device, cap=self.cap)
|
|
332
|
+
self.T = int(self.cap_.live[0].sum())
|
|
333
|
+
self.cap = cap or 4 * self.T + 64
|
|
334
|
+
self.names = classes()
|
|
335
|
+
|
|
336
|
+
def _unit(self, k: str | None) -> int | None:
|
|
337
|
+
if k is None:
|
|
338
|
+
return None
|
|
339
|
+
return int(k) if k.isdigit() else self.names.index(k)
|
|
340
|
+
|
|
341
|
+
def _parse(self, text: str) -> tuple[int, str, int | None]:
|
|
342
|
+
m = _ADDR.match(text.strip())
|
|
343
|
+
if not m:
|
|
344
|
+
raise ValueError(f"not an mlp address: {text!r} (i<t>.mlp.up|gate|f[k] or i<t>.mlp.down)")
|
|
345
|
+
t, site, k = int(m["t"]), m["site"], self._unit(m["k"])
|
|
346
|
+
if not 0 <= t < self.T:
|
|
347
|
+
raise ValueError(f"tick {t} is outside 0..{self.T - 1}")
|
|
348
|
+
if (site == "down") != (k is None):
|
|
349
|
+
raise ValueError("up/gate/f take a unit [k]; down takes none")
|
|
350
|
+
return t, site, k
|
|
351
|
+
|
|
352
|
+
def read(self, text: str) -> dict:
|
|
353
|
+
t, site, k = self._parse(text)
|
|
354
|
+
c = self.cap_
|
|
355
|
+
if site == "gate":
|
|
356
|
+
g = float(c.gate[0, t, k])
|
|
357
|
+
return {"address": text, "value": g, "authority": "measured"}
|
|
358
|
+
bits = {"up": lambda: c.up[0, t, k], "f": lambda: c.gate[0, t, k] * c.up[0, t, k].float(),
|
|
359
|
+
"down": lambda: c.down[0, t]}[site]()
|
|
360
|
+
v, v2, fl = words_of((bits != 0).long())
|
|
361
|
+
return {"address": text, "value": v, "value2": v2, "flags": fl, "nonzero_bits": int((bits != 0).sum()),
|
|
362
|
+
"authority": "measured"}
|
|
363
|
+
|
|
364
|
+
def print(self, text: str) -> str:
|
|
365
|
+
r = self.read(text)
|
|
366
|
+
if "value2" not in r:
|
|
367
|
+
return f"{r['address']} = {r['value']:g} [{r['authority']}]"
|
|
368
|
+
return (f"{r['address']} = value {r['value']:#x} value2 {r['value2']:#x} flags {r['flags']:#08b} "
|
|
369
|
+
f"({r['nonzero_bits']} bits on) [{r['authority']}]")
|
|
370
|
+
|
|
371
|
+
def attribute(self, t: int) -> dict:
|
|
372
|
+
c = self.cap_
|
|
373
|
+
r = attribute(c.f()[0, t:t + 1], c.down[0, t:t + 1], c.gate[0, t:t + 1])
|
|
374
|
+
name = lambda i: self.names[i] if i >= 0 else None
|
|
375
|
+
return {"tick": t, "named_contribution": name(int(r["named_contribution"][0])),
|
|
376
|
+
"named_ablation": name(int(r["named_ablation"][0])),
|
|
377
|
+
"selected_zero": [self.names[k] for k in
|
|
378
|
+
torch.nonzero(r["selected_zero"][0]).flatten().tolist()],
|
|
379
|
+
"contribution": r["contribution"][0].tolist(), "ablation": r["ablation"][0].tolist()}
|
|
380
|
+
|
|
381
|
+
def whatif(self, text: str, value: int) -> dict:
|
|
382
|
+
"""Set ``i<t>.mlp.gate[k]`` to ``value`` during tick t. Sealed first: the dispatch output at t,
|
|
383
|
+
``down' = down + (value - gate_k) * up_k`` in the machine's int64 words (exact, derived). Then
|
|
384
|
+
native: the run re-executes with the edit; the record compares down at t and y."""
|
|
385
|
+
t, site, k = self._parse(text)
|
|
386
|
+
if site != "gate":
|
|
387
|
+
raise ValueError("whatif edits a gate unit: i<t>.mlp.gate[k]")
|
|
388
|
+
c = self.cap_
|
|
389
|
+
g0 = int(c.gate[0, t, k])
|
|
390
|
+
up_w = words_of(c.up[0, t, k].long())
|
|
391
|
+
down_w = words_of(c.down[0, t].long())
|
|
392
|
+
M = (1 << 64) - 1
|
|
393
|
+
dv = int(value) - g0
|
|
394
|
+
pred = ((down_w[0] + dv * up_w[0]) & M, (down_w[1] + dv * up_w[1]) & M,
|
|
395
|
+
sum(((((down_w[2] >> i) & 1) + dv * ((up_w[2] >> i) & 1)) != 0) << i for i in range(6)))
|
|
396
|
+
ident = (f"x86:{self.binary.name}:{self.binary.image_sha256[:12]}",
|
|
397
|
+
{"kind": "x86-64-binary", "program": self.binary.name, "image_sha256": self.binary.image_sha256},
|
|
398
|
+
{"backend": "torchx86", "dispatch": "hard"})
|
|
399
|
+
hx = lambda w: f"value {w[0]:#x} value2 {w[1]:#x} flags {w[2]:#08b}"
|
|
400
|
+
pbody = {"schema": "mdb-machine-whatif-v1", "edit": {"address": text, "value": f"{int(value)}"},
|
|
401
|
+
"consumer": "i<t>.mlp.down, then y = last write bytes + exit code",
|
|
402
|
+
"prediction": {"method": "down + (value - gate_k) * up_k (exact, int64 words)",
|
|
403
|
+
"down": hx(pred)},
|
|
404
|
+
"sealed_prediction": "sealed before the native lane runs"}
|
|
405
|
+
sealed = seal_record(session_id=ident[0], kind="machine-whatif", model_identity=ident[1],
|
|
406
|
+
execution=ident[2], authority="derived-exact", body=pbody)
|
|
407
|
+
e = capture(self.binary, [self.input], device=self.device, cap=self.cap, edit=(t, k, int(value)))
|
|
408
|
+
native = words_of(e.down[0, t].long())
|
|
409
|
+
base, new = self.cap_.result, e.result
|
|
410
|
+
T_new = int(e.live[0].sum())
|
|
411
|
+
pcb, pcn = self.cap_.pc[0], e.pc[0]
|
|
412
|
+
n = min(self.T, T_new)
|
|
413
|
+
diff = torch.nonzero(pcb[:n] != pcn[:n]).flatten()
|
|
414
|
+
ctrl = int(diff[0]) if len(diff) else (None if T_new == self.T else n)
|
|
415
|
+
y_changed = (base.y[0], int(base.exit_code[0])) != (new.y[0], int(new.exit_code[0])) \
|
|
416
|
+
or new.stop_kind(0) != "exit"
|
|
417
|
+
body = {"schema": "mdb-machine-whatif-result-v1", "whatif": sealed["id"],
|
|
418
|
+
"verdict": verdict_of(new.stop_kind(0), ctrl is not None, y_changed),
|
|
419
|
+
"down_native": hx(native), "down_predicted": hx(pred),
|
|
420
|
+
"down_prediction": "confirmed" if native == pred else "not confirmed",
|
|
421
|
+
"total_effect": "effect" if y_changed else "no effect",
|
|
422
|
+
"frozen_effect": "not measured", "path_diverged_at": f"{ctrl}", "stop": new.stop_kind(0),
|
|
423
|
+
"y": new.y[0].hex(), "exit_code": f"{int(new.exit_code[0])}"}
|
|
424
|
+
res = seal_record(session_id=ident[0], kind="machine-whatif-result", model_identity=ident[1],
|
|
425
|
+
execution=ident[2], authority="measured", body=body)
|
|
426
|
+
return {**body, "records": [sealed["id"], res["id"]]}
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
__all__ = ["MlpRun", "Capture", "attribute", "attribute_capture", "bits_of", "capture", "classes",
|
|
430
|
+
"decoded_class", "purity", "sae_encode", "train_topk_sae", "usage", "value_split", "words_of"]
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Sealed records of a binary's recovered symbol table and circuit map.
|
|
2
|
+
|
|
3
|
+
``mdb-symbol-table-v1`` is extended minimally for machine bindings (docs/SYMBOL-TABLE-SCHEMA.md,
|
|
4
|
+
"Machine bindings"): a binding lists its **cells** as ``[site, def, kill, bits]`` (site in the
|
|
5
|
+
address grammar, ``def = "init"`` for the initial state, tick interval ``[def, kill)``), its
|
|
6
|
+
**slots** as ``[pc, operand]`` pairs, ``lifetime`` in instructions and loop iterations, and
|
|
7
|
+
``causal`` (donors whose aligned value differed, and how many of those changed y). ``unbound``
|
|
8
|
+
counts the dead cells. ``mdb-circuit-map-v1`` carries one slot per binding (``rows_rule`` is
|
|
9
|
+
``pc-operand``) and typed edges ``data`` / ``addr`` / ``ctrl`` with lane counts.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from mdb.core.bounded import put_json
|
|
19
|
+
from mdb.core.records import num, seal_record
|
|
20
|
+
|
|
21
|
+
from .binary import site_name
|
|
22
|
+
from .method import SPEC, Recovery
|
|
23
|
+
from .trace import INIT
|
|
24
|
+
|
|
25
|
+
PAGE = 16
|
|
26
|
+
INLINE = 8 # nested lists share mdb's 64-item budget; a page stays well under 64 KiB
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def identity(rec: Recovery) -> tuple[str, dict, dict]:
|
|
30
|
+
b = rec.binary
|
|
31
|
+
return (f"x86:{b.name}:{b.image_sha256[:12]}", {"kind": "x86-64-binary", "program": b.name,
|
|
32
|
+
"image_sha256": b.image_sha256},
|
|
33
|
+
{"backend": "torchx86", "lanes": "batched"})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _loop_prefix(tr) -> np.ndarray:
|
|
37
|
+
b = tr.b
|
|
38
|
+
nxt = [int(tr.pc[t + 1]) if t + 1 < tr.T else -1 for t in range(tr.T)]
|
|
39
|
+
marks = np.array([int(b.head_row[b.row_of(p)] >= 0) if p >= 0 else 0 for p in nxt], np.int64)
|
|
40
|
+
return np.concatenate([[0], np.cumsum(marks)])
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def binding_rows(rec: Recovery, *, store=None) -> list[dict]:
|
|
44
|
+
tr = rec.base
|
|
45
|
+
lp = _loop_prefix(tr)
|
|
46
|
+
out = []
|
|
47
|
+
for k in range(rec.n_bindings):
|
|
48
|
+
cells = rec.members(k)
|
|
49
|
+
first = min(c.def_ for c in cells)
|
|
50
|
+
last = max(c.kill for c in cells)
|
|
51
|
+
full = [[site_name(c.site), "init" if c.def_ == INIT else c.def_, c.kill, c.bits] for c in cells]
|
|
52
|
+
defs = [tr.describe(c) for c in cells]
|
|
53
|
+
readers = sorted({f"{tr.ticks[t].pc:#x}#{tr.ticks[t].k}:{e}" for c in cells for t, e in c.readers})
|
|
54
|
+
idx = [c.id for c in cells]
|
|
55
|
+
row = {
|
|
56
|
+
"symbol": f"b{k}", "kind": "web", "status": "live",
|
|
57
|
+
"n_cells": len(cells), "weight": int(sum(c.weight for c in cells)),
|
|
58
|
+
"cells": [f"{n}:{d}..{e}:{w}" for n, d, e, w in full[:INLINE]],
|
|
59
|
+
"slots": [f"{p}.{o}" for p, o in rec.slots(k)][:INLINE],
|
|
60
|
+
"definitions": defs[:INLINE],
|
|
61
|
+
"lifetime": {"first": "init" if first == INIT else first, "last": last,
|
|
62
|
+
"instructions": last - max(first, 0),
|
|
63
|
+
"loop_iterations": int(lp[min(last, tr.T)] - lp[max(first, 0)])},
|
|
64
|
+
"readers": readers[:INLINE],
|
|
65
|
+
"causal": {"status": "intervened", "verdict": "effect",
|
|
66
|
+
"donors": num(int(rec.informative[idx].sum()), "measured"),
|
|
67
|
+
"effect_donors": num(int(rec.effect_donors[idx].sum()), "measured")},
|
|
68
|
+
}
|
|
69
|
+
if len(full) > INLINE or len(readers) > INLINE or len(rec.slots(k)) > INLINE:
|
|
70
|
+
row["cells_full"] = put_json({"cells": full, "definitions": defs, "readers": readers,
|
|
71
|
+
"slots": [list(s) for s in rec.slots(k)]}, store=store)
|
|
72
|
+
out.append(row)
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def symbol_table_records(rec: Recovery, *, store=None, where: str | None = None) -> list[dict]:
|
|
77
|
+
sid, ident, execu = identity(rec)
|
|
78
|
+
rows = binding_rows(rec, store=store)
|
|
79
|
+
tr = rec.base
|
|
80
|
+
dead = [c for c, lv in zip(tr.cells, rec.live) if not lv]
|
|
81
|
+
unbound = {"dead_cells": len(dead), "dead_weight": int(sum(c.weight for c in dead)),
|
|
82
|
+
"uninformative_cells": int((rec.informative == 0).sum()), "cells": len(tr.cells)}
|
|
83
|
+
out = []
|
|
84
|
+
for off in range(0, max(len(rows), 1), PAGE):
|
|
85
|
+
body = {"schema": "mdb-symbol-table-v1", "where": where or f"bin:{rec.binary.name}",
|
|
86
|
+
"consumer": "y = bytes of the last write syscall + exit code",
|
|
87
|
+
"bindings": rows[off:off + PAGE], "unbound": unbound,
|
|
88
|
+
"page": {"offset": off, "limit": PAGE, "total": len(rows)},
|
|
89
|
+
"machine": {"T": tr.T, "donors": len(rec.donors), "lanes": rec.lanes_run},
|
|
90
|
+
"method": {"spec": SPEC, "cell": "site byte (flag bit) x tick interval [def, kill)"}}
|
|
91
|
+
out.append(seal_record(session_id=sid, kind="symbol-table", model_identity=ident, execution=execu,
|
|
92
|
+
authority="measured", body=body))
|
|
93
|
+
return out
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def circuit_map(rec: Recovery) -> dict:
|
|
97
|
+
slots = [{"name": f"b{k}", "role": "web", "rows_rule": "pc-operand", "keys": [list(s) for s in rec.slots(k)]}
|
|
98
|
+
for k in range(rec.n_bindings)]
|
|
99
|
+
slots.append({"name": "y", "role": "consumer", "rows_rule": "consumer", "keys": []})
|
|
100
|
+
edges = [{"src": f"b{a}", "dst": "y" if b_ == -2 else f"b{b_}",
|
|
101
|
+
"kind": max(("ctrl", "addr", "data"), key=lambda e: (cnt[e] > 0, ("data", "addr", "ctrl").index(e))),
|
|
102
|
+
"counts": dict(cnt)} for (a, b_), cnt in sorted(rec.edges.items())]
|
|
103
|
+
return {"schema": "mdb-circuit-map-v1", "slots": slots, "edges": edges,
|
|
104
|
+
"consumer_rule": {"kind": "last-write-bytes+exit-code"}, "candidate_sets": {},
|
|
105
|
+
"constants": {"edge_rule": "total effect of single-cell aligned-resample patches; kind = ctrl if "
|
|
106
|
+
"the lane's pc path diverged before the target cell, addr if an effective "
|
|
107
|
+
"address did, else data"}}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def circuit_map_record(rec: Recovery, *, store=None) -> dict:
|
|
111
|
+
sid, ident, execu = identity(rec)
|
|
112
|
+
m = circuit_map(rec)
|
|
113
|
+
digest = hashlib.sha256(json.dumps(m, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
|
114
|
+
inline = [{**e, "counts": {k: num(v, "measured") for k, v in e["counts"].items()}} for e in m["edges"][:64]]
|
|
115
|
+
body = {"schema": "mdb-circuit-map-v1", "digest": digest,
|
|
116
|
+
"slots": [{k: v for k, v in s.items() if k != "keys"} for s in m["slots"][:64]],
|
|
117
|
+
"edges": inline, "edges_listed": "the first 64 (all in payload)", "payload": put_json(m, store=store)}
|
|
118
|
+
return seal_record(session_id=sid, kind="circuit-map", model_identity=ident, execution=execu,
|
|
119
|
+
authority="measured", body=body)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def table_text(rec: Recovery, limit: int = 40) -> str:
|
|
123
|
+
"""The recovered symbol table as text, one binding per line."""
|
|
124
|
+
tr = rec.base
|
|
125
|
+
lines = [f"symbol table bin:{rec.binary.name} T={tr.T} cells={len(tr.cells)} live={int(rec.live.sum())} "
|
|
126
|
+
f"bindings={rec.n_bindings} donors={len(rec.donors)} lanes={rec.lanes_run}",
|
|
127
|
+
f"{'sym':>5} {'cells':>5} {'bits*ticks':>10} {'life':>11} slots (pc.operand) / first definitions"]
|
|
128
|
+
rows = binding_rows(rec)
|
|
129
|
+
for row in rows[:limit]:
|
|
130
|
+
life = f"{row['lifetime']['first']}..{row['lifetime']['last']}"
|
|
131
|
+
slots = ", ".join(row["slots"][:3])
|
|
132
|
+
more = f" (+{len(rec.slots(int(row['symbol'][1:]))) - 3} slots)" if len(rec.slots(int(row['symbol'][1:]))) > 3 else ""
|
|
133
|
+
lines.append(f"{row['symbol']:>5} {row['n_cells']:>5} {row['weight']:>10} {life:>11} {slots}{more}")
|
|
134
|
+
if len(rows) > limit:
|
|
135
|
+
lines.append(f" ... {len(rows) - limit} more bindings")
|
|
136
|
+
dead = int((~rec.live).sum())
|
|
137
|
+
lines.append(f"unbound: {dead} dead cells ({int((rec.informative == 0).sum())} with no informative donor)")
|
|
138
|
+
return "\n".join(lines)
|