model-debugger 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
@@ -0,0 +1,252 @@
1
+ """Symbol-table recovery on a binary by intervention (the frozen run-1 method).
2
+
3
+ Frozen specification, and how each clause is implemented here:
4
+
5
+ 1. **Cells from write events.** The base run's cells (``trace.Trace``): every byte (flag bit) a tick
6
+ writes starts a cell that lasts until the site is rewritten; the injected input and sites read
7
+ before any write are initial cells. Undefined flags start no cell.
8
+ 2. **Liveness by aligned-resample interchange over the 32 donors.** For every cell and donor, the
9
+ donor value is the donor run's cell with the same alignment key (execution index of the defining
10
+ tick + write slot; ``init`` + site for initial cells). Each donor whose value differs from the
11
+ base's is one lane: the base input runs, the cell is overwritten with the donor value right
12
+ after its defining tick, and the program runs to its end. The cell is **live** if at least one
13
+ lane changes y (the last ``write``'s bytes or the exit code; a fault or the step cap counts as a
14
+ change). A donor that lacks the aligned cell, or holds the same value, is not run (no evidence);
15
+ every cell reports how many donors were informative.
16
+ 3. **Merge by identical transfer.** Live cells a, b merge when, on every donor lane of a in which
17
+ b's aligned instance exists, b takes exactly a's patched value, b's base value equals a's, and
18
+ b exists in at least one such lane. Merging is transitive (union-find).
19
+ 4. **Slots keyed by (pc, operand).** A binding's slot is the set of (defining pc, written operand)
20
+ of its cells; initial cells key by (``init``, site).
21
+
22
+ Output: ``Recovery`` (bindings over live cells, dead cells, per-cell arrays) and records
23
+ ``mdb-symbol-table-v1`` (one page per 16 bindings) and ``mdb-circuit-map-v1``. Circuit edges come
24
+ from the same patch lanes: binding A -> B when patching a cell of A changes a cell of B; each lane's
25
+ change is typed ``ctrl`` (the lane's pc path had diverged before B's cell was defined), ``addr`` (an
26
+ effective address had), or ``data``. These are total effects, so the edges are transitive.
27
+
28
+ Baselines on the same cell universe: ``b1`` site-as-symbol (one label per register,
29
+ EFLAGS, or 8-byte memory slot, over the whole run) and ``b2`` value-equality clustering (cells with
30
+ equal values on the base and every donor input).
31
+ """
32
+ from __future__ import annotations
33
+
34
+ from dataclasses import dataclass, field
35
+
36
+ import numpy as np
37
+ import torch
38
+
39
+ from . import index as xi
40
+ from .binary import FLAG0, NSLOT_LANE, Binary, site_name
41
+ from .lanes import Lanes, reference
42
+ from .trace import INIT, Trace, record
43
+
44
+ SPEC = ("cells from write events; liveness by aligned-resample interchange (live if >= 1 of the donors "
45
+ "changes y); merge when patching one cell transfers identically to the other on every donor "
46
+ "where the other's aligned instance exists; slots keyed by (pc, operand)")
47
+
48
+
49
+ @dataclass
50
+ class Recovery:
51
+ binary: Binary
52
+ base: Trace
53
+ donors: list
54
+ live: np.ndarray # bool [N]
55
+ informative: np.ndarray # int [N]: donors whose aligned value differed (lanes run)
56
+ effect_donors: np.ndarray # int [N]: lanes that changed y
57
+ binding: np.ndarray # int [N]: binding id, -1 dead
58
+ edges: dict = field(default_factory=dict) # (a_binding, b_binding|-2 for y) -> {data, addr, ctrl}
59
+ lanes_run: int = 0
60
+ result: object = None # the recorded lanes.Result of [base, *donors]
61
+ b1: np.ndarray | None = None
62
+ b2: np.ndarray | None = None
63
+
64
+ @property
65
+ def n_bindings(self) -> int:
66
+ return int(self.binding.max()) + 1 if len(self.binding) else 0
67
+
68
+ def members(self, k: int) -> list:
69
+ return [self.base.cells[i] for i in np.nonzero(self.binding == k)[0]]
70
+
71
+ def slots(self, k: int) -> list[tuple]:
72
+ out = []
73
+ for c in self.members(k):
74
+ key = ("init", site_name(c.site)) if c.def_ == INIT else (f"{c.pc:#x}", self.binary.operand_text(c.pc, c.slot))
75
+ if key not in out:
76
+ out.append(key)
77
+ return out
78
+
79
+
80
+ def resident_pages(binary: Binary, traces: list) -> list[int]:
81
+ """Writable pages any run touched, plus one neighbour on each side (patched pointers)."""
82
+ pages = set()
83
+ for tr in traces:
84
+ for _t, a, _o, _n in tr.mem_writes:
85
+ pages.add(a & ~0xFFF)
86
+ if binary.input_addr is not None:
87
+ pages.add(binary.input_addr & ~0xFFF)
88
+ out = set()
89
+ for p in pages:
90
+ out |= {p - 4096, p, p + 4096}
91
+ return sorted(p for p in out if p in binary.perms and "w" in binary.perms[p])
92
+
93
+
94
+ def aligned_values(base: Trace, other: Trace) -> np.ndarray:
95
+ """Per base cell: the value of the cell with the same alignment key in ``other`` (-1 absent)."""
96
+ out = np.full(len(base.cells), -1, np.int64)
97
+ for i, c in enumerate(base.cells):
98
+ j = other.by_key.get(c.key)
99
+ if j is not None:
100
+ out[i] = other.cells[j].value
101
+ return out
102
+
103
+
104
+ def lane_alignment(base: Trace, keys: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
105
+ """For B lanes' execution keys [B, T]: per base (non-initial) cell, the lane tick holding the same
106
+ execution instance (tick [B, N], found [B, N])."""
107
+ dev = keys.device
108
+ q = torch.tensor([c.key[0] if c.def_ != INIT else -2 for c in base.cells], dtype=torch.int64, device=dev)
109
+ sk, order = keys.sort(dim=1)
110
+ pos = torch.searchsorted(sk, q.expand(keys.shape[0], -1).contiguous()).clamp(max=keys.shape[1] - 1)
111
+ found = sk.gather(1, pos) == q
112
+ return order.gather(1, pos), found
113
+
114
+
115
+ def recover(binary: Binary, base_input: bytes | None, donor_inputs: list, *, device="cpu", chunk: int = 2048,
116
+ cap_factor: int = 4, log=print) -> Recovery:
117
+ dev = torch.device(device)
118
+ traces, res = record(binary, [base_input, *donor_inputs], device=device)
119
+ base, donors = traces[0], traces[1:]
120
+ if base.stop != "exit":
121
+ raise ValueError(f"the base run did not exit ({base.stop})")
122
+ resident = resident_pages(binary, traces)
123
+ cells = base.cells
124
+ N = len(cells)
125
+ V = np.stack([aligned_values(base, d) for d in donors]) if donors else np.zeros((0, N), np.int64)
126
+ bval = np.array([c.value for c in cells], np.int64)
127
+ plan = [(i, j) for i in range(N) for j in range(len(donors)) if V[j, i] >= 0 and V[j, i] != bval[i]]
128
+ informative = np.zeros(N, np.int64)
129
+ for i, _j in plan:
130
+ informative[i] += 1
131
+ log(f"{binary.name}: T={base.T} cells={N} patch lanes={len(plan)}")
132
+
133
+ ref = reference(binary, _take(res, 0), dev)
134
+ cap = cap_factor * base.T + 64
135
+ base_y = (base.y, base.exit_code)
136
+ is_init = torch.tensor([c.def_ == INIT for c in cells], device=dev)
137
+ slot = torch.tensor([max(c.slot, 0) for c in cells], dtype=torch.int64, device=dev)
138
+ lane_slot_ok = torch.tensor([0 <= c.slot < NSLOT_LANE for c in cells], device=dev)
139
+ defs = torch.tensor([c.def_ for c in cells], dtype=torch.int64, device=dev)
140
+ bv = torch.tensor(bval, device=dev)
141
+ patched = sorted({i for i, _ in plan})
142
+ row_of = {a: r for r, a in enumerate(patched)}
143
+ A = len(patched)
144
+ ident = torch.ones(A, N, dtype=torch.uint8, device=dev)
145
+ seen = torch.zeros(A, N, dtype=torch.uint8, device=dev)
146
+ changed = {e: torch.zeros(A, N, dtype=torch.uint8, device=dev) for e in ("data", "addr", "ctrl")}
147
+ ychanged = {e: torch.zeros(A, dtype=torch.uint8, device=dev) for e in ("data", "addr", "ctrl")}
148
+ effect = np.zeros(N, np.int64)
149
+ for s in range(0, len(plan), chunk):
150
+ part = plan[s:s + chunk]
151
+ B = len(part)
152
+ ai = torch.tensor([i for i, _ in part], dtype=torch.int64, device=dev)
153
+ pv = torch.tensor([int(V[j, i]) for i, j in part], dtype=torch.int64, device=dev)
154
+ lanes = Lanes(binary, [base_input] * B, device=dev, cap=cap, resident=resident)
155
+ lanes.patch(defs[ai] + 1, torch.tensor([cells[i].site for i, _ in part], device=dev), pv)
156
+ lanes.compare_to(ref, torch.zeros(B, dtype=torch.int64, device=dev))
157
+ r = lanes.run(record="slots")
158
+ yc = torch.tensor([(y, int(e)) != base_y or int(st) != 1 for y, e, st in
159
+ zip(r.y, r.exit_code.tolist(), r.stop.tolist())], device=dev)
160
+ for (i, _j), c in zip(part, yc.tolist()):
161
+ effect[i] += int(c)
162
+ keys = xi.keys(binary, r.pc, r.pc >= 0)
163
+ tick, found = lane_alignment(base, keys)
164
+ val = r.slots.reshape(B, -1).gather(1, tick * NSLOT_LANE + slot[None, :]).long()
165
+ present = found & lane_slot_ok & (val >= 0)
166
+ # initial cells: unchanged except the patched one itself
167
+ val = torch.where(is_init, bv, val)
168
+ present = present | is_init
169
+ own = torch.arange(N, device=dev) == ai[:, None]
170
+ val = torch.where(own, pv[:, None], val)
171
+ ok = (~present | (val == pv[:, None])).to(torch.uint8)
172
+ rows = torch.tensor([row_of[i] for i, _ in part], device=dev)
173
+ ident.index_reduce_(0, rows, ok, "amin")
174
+ seen.index_reduce_(0, rows, present.to(torch.uint8), "amax")
175
+ diff = present & (val != bv) & ~own
176
+ ctrl_before = (r.ctrl_at[:, None] >= 0) & (r.ctrl_at[:, None] < defs)
177
+ addr_before = (r.addr_at[:, None] >= 0) & (r.addr_at[:, None] < defs) & ~ctrl_before
178
+ for e, m in (("ctrl", diff & ctrl_before), ("addr", diff & addr_before),
179
+ ("data", diff & ~ctrl_before & ~addr_before)):
180
+ changed[e].index_reduce_(0, rows, m.to(torch.uint8), "amax")
181
+ ctl_y, adr_y = r.ctrl_at >= 0, (r.addr_at >= 0) & (r.ctrl_at < 0)
182
+ for e, m in (("ctrl", yc & ctl_y), ("addr", yc & adr_y), ("data", yc & ~ctl_y & ~adr_y)):
183
+ ychanged[e].index_reduce_(0, rows, m.to(torch.uint8), "amax")
184
+ log(f" lanes {s + B}/{len(plan)}")
185
+ live = effect > 0
186
+ # merge by identical transfer
187
+ parent = list(range(N))
188
+
189
+ def find(x):
190
+ while parent[x] != x:
191
+ parent[x] = parent[parent[x]]
192
+ x = parent[x]
193
+ return x
194
+
195
+ live_t = torch.tensor(live, device=dev)
196
+ if A:
197
+ pr = torch.tensor(patched, device=dev)
198
+ merge = (ident.bool() & seen.bool() & live_t[None, :] & live_t[pr][:, None]
199
+ & (bv[None, :] == bv[pr][:, None]))
200
+ merge[torch.arange(A, device=dev), pr] = False
201
+ for ra, b_ in torch.nonzero(merge).tolist():
202
+ x, y = find(patched[ra]), find(b_)
203
+ if x != y:
204
+ parent[max(x, y)] = min(x, y)
205
+ roots = sorted({find(i) for i in range(N) if live[i]}, key=lambda i: (cells[i].def_, i))
206
+ bid = {r_: k for k, r_ in enumerate(roots)}
207
+ binding = np.array([bid[find(i)] if live[i] else -1 for i in range(N)], np.int64)
208
+ # typed edges between bindings, and to the consumer
209
+ edges: dict = {}
210
+ if A:
211
+ for e in ("data", "addr", "ctrl"):
212
+ for ra, b_ in torch.nonzero(changed[e]).tolist():
213
+ ka, kb = binding[patched[ra]], binding[b_]
214
+ if ka >= 0 and kb >= 0 and ka != kb:
215
+ edges.setdefault((int(ka), int(kb)), {"data": 0, "addr": 0, "ctrl": 0})[e] += 1
216
+ for ra in torch.nonzero(ychanged[e])[:, 0].tolist():
217
+ ka = binding[patched[ra]]
218
+ if ka >= 0:
219
+ edges.setdefault((int(ka), -2), {"data": 0, "addr": 0, "ctrl": 0})[e] += 1
220
+ rec = Recovery(binary, base, donors, live, informative, effect, binding, edges, len(plan), res)
221
+ rec.b1, rec.b2 = baselines(base, V)
222
+ return rec
223
+
224
+
225
+ def _take(res, lane: int):
226
+ """One lane of a fully recorded ``Result`` as a one-lane Result."""
227
+ from .lanes import Result # noqa: PLC0415
228
+
229
+ sl = slice(lane, lane + 1)
230
+ out = Result(res.stop[sl], res.T[sl], res.exit_code[sl], res.y[sl])
231
+ out.pc = res.pc[sl]
232
+ out.full = {k: v[sl] for k, v in res.full.items()}
233
+ return out
234
+
235
+
236
+ def baselines(base: Trace, V: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
237
+ """B1 site-as-symbol and B2 value-equality labels per base cell (the run-1 baselines)."""
238
+ b1, b2, names, groups = [], [], {}, {}
239
+ for i, c in enumerate(base.cells):
240
+ if c.site < FLAG0:
241
+ key = ("reg", c.site // 8)
242
+ elif c.site < FLAG0 + 6:
243
+ key = ("eflags",)
244
+ else:
245
+ key = ("mem", c.site & ~7)
246
+ b1.append(names.setdefault(key, len(names)))
247
+ vec = (c.value, *V[:, i].tolist())
248
+ b2.append(groups.setdefault(vec, len(groups)))
249
+ return np.array(b1, np.int64), np.array(b2, np.int64)
250
+
251
+
252
+ __all__ = ["Recovery", "recover", "baselines", "SPEC", "resident_pages", "aligned_values", "lane_alignment"]
@@ -0,0 +1,105 @@
1
+ """Symbol-table method v2: the frozen run-1 method (``method.py``, 3d0baff, unchanged) plus two
2
+ lessons read off its score. POST HOC: both were chosen after the run-1 key was scored,
3
+ so any score of v2 is a post-hoc score, not a held-out one.
4
+
5
+ 1. **Multi-byte bindings.** The frozen method binds byte cells, so a u64 variable becomes eight
6
+ bindings (DWARF recall@0.5 was 0 on bigadd and bsort). v2 merges the bindings of two cells
7
+ when the same op instance wrote both (same defining tick), they are adjacent bytes of one site
8
+ (bytes b, b+1 of one general register, or addresses a, a+1), and their liveness is identical
9
+ (both live or both dead). Initial cells (no op instance) and flags are never merged this way.
10
+ 2. **Dead copies are bindings.** The frozen method leaves every cell that no donor showed to be
11
+ live unbound (70-85% of def-use-live occurrences). v2 lists each copy web (``Trace.webs``,
12
+ this backend's own) that has at least two members as one binding over its not-live members,
13
+ with ``status`` ``dead``; rule 1 then merges dead bindings too. Live bindings keep the frozen
14
+ method's grouping (and gain rule 1's merges); a dead binding never absorbs a live cell.
15
+
16
+ ``lessons(rec, words=True, dead_copies=True)`` returns ``RecoveryV2``: ``binding`` per cell (-1
17
+ unbound), ``status`` per binding (``live`` / ``dead``), and the frozen ``rec`` untouched.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass
22
+
23
+ import numpy as np
24
+
25
+ from .binary import FLAG0
26
+ from .method import Recovery
27
+ from .trace import INIT
28
+
29
+ METHOD = "method_v2"
30
+ SPEC = ("method_v2 (post hoc): frozen run-1 method; + merge bindings of adjacent bytes written by the "
31
+ "same op instance with identical liveness; + dead copy-web members (webs of >= 2 cells) as "
32
+ "bindings with status dead")
33
+
34
+
35
+ @dataclass
36
+ class RecoveryV2:
37
+ rec: Recovery
38
+ binding: np.ndarray # int [N]: v2 binding id, -1 unbound
39
+ status: list # per v2 binding: "live" | "dead"
40
+ web: np.ndarray # int [N]: copy-web root cell id (Trace.webs)
41
+ rules: dict
42
+
43
+ @property
44
+ def n_bindings(self) -> int:
45
+ return len(self.status)
46
+
47
+
48
+ def _adjacent(a: int, b: int) -> bool:
49
+ """Sites a, b (a < b) are neighbouring bytes of one register or of memory."""
50
+ if b != a + 1:
51
+ return False
52
+ if a < FLAG0:
53
+ return a // 8 == b // 8
54
+ return a >= FLAG0 + 6
55
+
56
+
57
+ def lessons(rec: Recovery, *, words: bool = True, dead_copies: bool = True) -> RecoveryV2:
58
+ cells = rec.base.cells
59
+ n = len(cells)
60
+ web = np.array(rec.base.webs(), np.int64)
61
+ label = rec.binding.copy() # frozen live bindings 0..K-1
62
+ k = int(label.max()) + 1 if n and label.max() >= 0 else 0
63
+ live = rec.live.astype(bool)
64
+ if dead_copies:
65
+ size = np.bincount(web, minlength=n)
66
+ roots: dict[int, int] = {}
67
+ for i in range(n):
68
+ if not live[i] and size[web[i]] >= 2:
69
+ label[i] = roots.setdefault(int(web[i]), k + len(roots))
70
+ k += len(roots)
71
+ parent = list(range(k))
72
+
73
+ def find(x: int) -> int:
74
+ while parent[x] != x:
75
+ parent[x] = parent[parent[x]]
76
+ x = parent[x]
77
+ return x
78
+
79
+ if words:
80
+ by_tick: dict[int, list[int]] = {}
81
+ for i, c in enumerate(cells):
82
+ if c.def_ != INIT and label[i] >= 0:
83
+ by_tick.setdefault(c.def_, []).append(i)
84
+ for group in by_tick.values():
85
+ group.sort(key=lambda i: cells[i].site)
86
+ for x, y in zip(group, group[1:]):
87
+ if _adjacent(cells[x].site, cells[y].site) and live[x] == live[y]:
88
+ rx, ry = find(int(label[x])), find(int(label[y]))
89
+ if rx != ry:
90
+ parent[max(rx, ry)] = min(rx, ry)
91
+ first: dict[int, tuple[int, int]] = {} # root -> earliest (def, cell): binding order
92
+ for i in np.nonzero(label >= 0)[0]:
93
+ r = find(int(label[i]))
94
+ first[r] = min(first.get(r, (cells[i].def_, int(i))), (cells[i].def_, int(i)))
95
+ renum = {r: j for j, r in enumerate(sorted(first, key=first.get))}
96
+ binding = np.array([renum[find(int(b))] if b >= 0 else -1 for b in label], np.int64)
97
+ status = ["dead"] * len(renum)
98
+ for i in np.nonzero(binding >= 0)[0]:
99
+ if live[i]:
100
+ status[binding[i]] = "live"
101
+ return RecoveryV2(rec, binding, status, web, {"words": words, "dead_copies": dead_copies,
102
+ "spec": SPEC})
103
+
104
+
105
+ __all__ = ["METHOD", "RecoveryV2", "SPEC", "lessons"]