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
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Two verbs a CoT-faithfulness monitor needs on binaries: the answer's dependence cone,
|
|
2
|
+
and multi-donor interchange of a whole block (a buffer, a field) on many base runs at once.
|
|
3
|
+
|
|
4
|
+
``cone(trace)``: the backward dynamic dependence cone of the answer, the bytes the run's last ``write``
|
|
5
|
+
syscall emits. Rule, applied tick by tick from that syscall back to tick 0:
|
|
6
|
+
|
|
7
|
+
* the answer tick is in the cone and every site it reads is needed;
|
|
8
|
+
* a tick is in the cone when it writes a needed site, or (``control=True``) when it reads anything through a
|
|
9
|
+
``ctrl`` edge (a jcc's or cmov's flags, a ``ret``'s return address, an indirect jump, a syscall number):
|
|
10
|
+
every control decision before the answer is a root, with no post-dominator pruning (a conservative
|
|
11
|
+
upper bound on control dependence);
|
|
12
|
+
* a cone tick's written sites stop being needed and every site it reads becomes needed, except that a
|
|
13
|
+
``write`` syscall moves no buffer byte into a register: only its register reads count.
|
|
14
|
+
|
|
15
|
+
``reads`` lists every (tick, site, edge) read by a cone tick: "the answer's cone contains a read of X" is a
|
|
16
|
+
test on that list (the read-set existence monitor, the attention-mass analogue).
|
|
17
|
+
|
|
18
|
+
``interchange(binary, bases, donors, text)``: for every base run and donor run, overwrite the block named
|
|
19
|
+
by ``text`` (mdb's x86 address grammar: a tick part and a site of whole bytes, e.g.
|
|
20
|
+
``init.mem[0x40300c:1]`` or ``0x4010d3#0.mem[0x403010:10]``) in the base run, right after the address's
|
|
21
|
+
tick in the base run, with the donor run's bytes of the same address at the same tick instance in the
|
|
22
|
+
donor run, and run the base input to its end. One lane per informative (base, donor) pair, all in one
|
|
23
|
+
batch. A donor whose bytes equal the base's is not run (an identity patch, not informative); a donor
|
|
24
|
+
without the instance is ``unresolved``. Per base the donors are pooled by
|
|
25
|
+
``mdb.analysis.measure.donors.pooled`` on the answer: ``effect`` when at least one donor changes y
|
|
26
|
+
(the last write's bytes or the exit code; a fault or the step cap count as a change).
|
|
27
|
+
"""
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
|
|
32
|
+
import torch
|
|
33
|
+
|
|
34
|
+
from . import address as xa
|
|
35
|
+
from .binary import RAX, Binary
|
|
36
|
+
from .lanes import Lanes, reference
|
|
37
|
+
from .trace import CTRL, Trace
|
|
38
|
+
|
|
39
|
+
MEM0 = 0x1000
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Cone:
|
|
44
|
+
answer_tick: int
|
|
45
|
+
ticks: set = field(default_factory=set)
|
|
46
|
+
reads: list = field(default_factory=list) # [(tick, site, edge)] read by cone ticks
|
|
47
|
+
control: bool = True
|
|
48
|
+
|
|
49
|
+
def reads_of(self, sites) -> list:
|
|
50
|
+
"""The cone's reads of any of ``sites`` (tick, site, edge)."""
|
|
51
|
+
want = set(sites)
|
|
52
|
+
return [r for r in self.reads if r[1] in want]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _is_write(trace: Trace, t: int) -> bool:
|
|
56
|
+
return trace.ticks[t].kind == "syscall" and trace.reg(t - 1, RAX) == 1
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def cone(trace: Trace, *, control: bool = True, answer_tick: int | None = None) -> Cone:
|
|
60
|
+
"""The answer's backward dependence cone (module docstring)."""
|
|
61
|
+
if answer_tick is None:
|
|
62
|
+
writes = [t for t in range(trace.T) if _is_write(trace, t)]
|
|
63
|
+
if not writes:
|
|
64
|
+
raise ValueError("the run has no write syscall: no answer to take the cone of")
|
|
65
|
+
answer_tick = writes[-1]
|
|
66
|
+
out = Cone(answer_tick, control=control)
|
|
67
|
+
tk = trace.ticks[answer_tick]
|
|
68
|
+
need = {s for s, _ in tk.reads}
|
|
69
|
+
out.ticks.add(answer_tick)
|
|
70
|
+
out.reads += [(answer_tick, s, e) for s, e in tk.reads]
|
|
71
|
+
for t in range(answer_tick - 1, -1, -1):
|
|
72
|
+
tk = trace.ticks[t]
|
|
73
|
+
written = {s for s, _ in tk.writes}
|
|
74
|
+
if not (written & need or (control and any(e == CTRL for _, e in tk.reads))):
|
|
75
|
+
continue
|
|
76
|
+
out.ticks.add(t)
|
|
77
|
+
need -= written
|
|
78
|
+
reads = [(s, e) for s, e in tk.reads if not (tk.kind == "syscall" and s >= MEM0)]
|
|
79
|
+
need |= {s for s, _ in reads}
|
|
80
|
+
out.reads += [(t, s, e) for s, e in reads]
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _block(addr: xa.Addr, trace: Trace) -> tuple[int, list[int], list[int]]:
|
|
85
|
+
"""(tick, byte sites, byte values) of ``addr`` in ``trace``; raises AddressError when absent."""
|
|
86
|
+
t = xa.resolve_tick(addr, trace)
|
|
87
|
+
sites, lo, nbits = xa.sites(addr, trace, t)
|
|
88
|
+
if lo or (nbits % 8 and nbits != 1):
|
|
89
|
+
raise xa.AddressError(f"{addr.text()}: interchange takes whole bytes or one flag")
|
|
90
|
+
return t, sites, [trace.value(s, t) for s in sites]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def interchange(binary: Binary, bases: list, donors: list, text: str, *, device="cpu", res=None,
|
|
94
|
+
chunk: int = 8192, cap_factor: int = 4) -> list[dict]:
|
|
95
|
+
"""Multi-donor block interchange on many bases (module docstring). ``bases``/``donors`` are ``Trace``s
|
|
96
|
+
(``trace.record``); ``res`` is the bases' recorded ``Result`` (``record="full"``), which adds per-lane
|
|
97
|
+
path divergence against the base run. Returns one dict per base: the pooled verdict and ``per_donor``."""
|
|
98
|
+
from mdb.analysis.numerics.pooling import EFFECT, NO_EFFECT, UNRESOLVED, pooled # noqa: PLC0415
|
|
99
|
+
|
|
100
|
+
addr = xa.parse(text)
|
|
101
|
+
dev = torch.device(device)
|
|
102
|
+
dblocks = []
|
|
103
|
+
for d in donors:
|
|
104
|
+
try:
|
|
105
|
+
dblocks.append(_block(addr, d))
|
|
106
|
+
except xa.AddressError:
|
|
107
|
+
dblocks.append(None)
|
|
108
|
+
lanes_spec, rows = [], []
|
|
109
|
+
for i, b in enumerate(bases):
|
|
110
|
+
t, sites, bval = _block(addr, b)
|
|
111
|
+
at = 0 if t < 0 else t + 1
|
|
112
|
+
per = []
|
|
113
|
+
for j, db in enumerate(dblocks):
|
|
114
|
+
if db is None or len(db[2]) != len(bval):
|
|
115
|
+
per.append({"donor": j, "verdict": UNRESOLVED, "informative": None, "ran": False})
|
|
116
|
+
continue
|
|
117
|
+
info = db[2] != bval
|
|
118
|
+
row = {"donor": j, "verdict": NO_EFFECT, "informative": info, "ran": info, "path_diverged": False}
|
|
119
|
+
if info:
|
|
120
|
+
row["lane"] = len(lanes_spec)
|
|
121
|
+
lanes_spec.append((i, at, sites, db[2]))
|
|
122
|
+
per.append(row)
|
|
123
|
+
rows.append({"tick": t, "sites": sites, "base_bytes": bval, "per_donor": per})
|
|
124
|
+
ref = reference(binary, res, dev) if res is not None else None
|
|
125
|
+
out_lane: list[dict] = [None] * len(lanes_spec)
|
|
126
|
+
cap = cap_factor * max(b.T for b in bases) + 64
|
|
127
|
+
for s in range(0, len(lanes_spec), chunk):
|
|
128
|
+
part = lanes_spec[s:s + chunk]
|
|
129
|
+
lanes = Lanes(binary, [bases[i].input for i, *_ in part], device=dev, cap=cap)
|
|
130
|
+
n = max(len(p[2]) for p in part)
|
|
131
|
+
for k in range(n):
|
|
132
|
+
lanes.patch([p[1] if k < len(p[2]) else -1 for p in part],
|
|
133
|
+
[p[2][k] if k < len(p[2]) else -1 for p in part],
|
|
134
|
+
[p[3][k] if k < len(p[3]) else 0 for p in part])
|
|
135
|
+
if ref is not None:
|
|
136
|
+
lanes.compare_to(ref, [p[0] for p in part])
|
|
137
|
+
r = lanes.run()
|
|
138
|
+
for q, (i, *_rest) in enumerate(part):
|
|
139
|
+
b = bases[i]
|
|
140
|
+
stop = r.stop_kind(q)
|
|
141
|
+
changed = (r.y[q], int(r.exit_code[q])) != (b.y, b.exit_code) or stop != "exit"
|
|
142
|
+
div = ref is not None and (int(r.ctrl_at[q]) >= 0 or int(r.addr_at[q]) >= 0)
|
|
143
|
+
out_lane[s + q] = {"y_changed": changed, "y": r.y[q].hex(), "stop": stop, "path_diverged": bool(div)}
|
|
144
|
+
result = []
|
|
145
|
+
for rw in rows:
|
|
146
|
+
for row in rw["per_donor"]:
|
|
147
|
+
if "lane" in row:
|
|
148
|
+
lane = out_lane[row.pop("lane")]
|
|
149
|
+
row.update(lane, verdict=EFFECT if lane["y_changed"] else NO_EFFECT)
|
|
150
|
+
site_text = [f"{s:#x}" if s >= MEM0 else str(s) for s in rw["sites"]]
|
|
151
|
+
result.append({"address": text, "tick": rw["tick"], "sites": site_text, "base_bytes": rw["base_bytes"],
|
|
152
|
+
**pooled(rw["per_donor"]), "per_donor": rw["per_donor"]})
|
|
153
|
+
return result
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
__all__ = ["Cone", "cone", "interchange"]
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""B copies of one binary in lockstep on torchx86: inputs, patches, holds, divergence, recording.
|
|
2
|
+
|
|
3
|
+
One lane = one run. A **patch** writes a value into one site (register byte, flag, memory byte) of
|
|
4
|
+
one lane when that lane has retired ``at`` instructions (``at = t_def + 1`` patches the cell that
|
|
5
|
+
tick ``t_def`` defined; ``at = 0`` patches the initial state). A **hold** keeps a lane's selection
|
|
6
|
+
reads at a reference run's: after each instruction the next pc is forced to the reference's
|
|
7
|
+
(branch outcomes and returns frozen) and every memory access, and the ``write`` syscall's buffer,
|
|
8
|
+
use the reference's effective address. Value reads are left free. This is the binary form of
|
|
9
|
+
``hold p`` (frozen attention).
|
|
10
|
+
|
|
11
|
+
Divergence against a reference run is tracked per lane: the first tick whose pc differs (``ctrl``)
|
|
12
|
+
and the first tick whose computed effective address differs (``addr``), checked on the address the
|
|
13
|
+
lane computed, before any hold replaced it.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
import torch
|
|
20
|
+
|
|
21
|
+
from .binary import (FLAG0, NSLOT_LANE, RCX, RDX, RSI, RSP, S_D2, S_DST, S_FL, S_MEM, S_SP, Binary,
|
|
22
|
+
torchx86)
|
|
23
|
+
|
|
24
|
+
ALIVE = 0
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _held_machine_class():
|
|
28
|
+
from torchx86.machine import Machine # noqa: PLC0415
|
|
29
|
+
|
|
30
|
+
class HeldMachine(Machine):
|
|
31
|
+
"""torchx86 ``Machine`` whose memory accesses can be redirected to a reference run's."""
|
|
32
|
+
|
|
33
|
+
hold = None # bool [B] or None
|
|
34
|
+
ref = None # dict with ea [NR,T], acc [NR,T], rsi [NR,T], T [NR]; rix [B]
|
|
35
|
+
|
|
36
|
+
def _bytes(self, addr, last, k):
|
|
37
|
+
if self.hold is not None and (k is self.k8 or k is self.kout):
|
|
38
|
+
ref, rix = self.ref, self.ref["rix"]
|
|
39
|
+
t = self.steps.clamp(max=ref["ea"].shape[1] - 1)
|
|
40
|
+
inref = self.steps < ref["T"][rix]
|
|
41
|
+
if k is self.k8:
|
|
42
|
+
want, use = ref["ea"][rix, t], self.hold & inref & ref["acc"][rix, t]
|
|
43
|
+
self._moved = use & (want != addr)
|
|
44
|
+
else:
|
|
45
|
+
want, use = ref["rsi"][rix, t], self.hold & inref
|
|
46
|
+
last = torch.where(use, last + (want - addr), last)
|
|
47
|
+
addr = torch.where(use, want, addr)
|
|
48
|
+
return super()._bytes(addr, last, k)
|
|
49
|
+
|
|
50
|
+
return HeldMachine
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class Result:
|
|
55
|
+
"""Per lane: stop code and kind, ticks T (instructions incl. the final exit), exit code, y (the
|
|
56
|
+
last ``write``'s bytes), divergence ticks (-1 none), and the recordings asked for."""
|
|
57
|
+
stop: torch.Tensor
|
|
58
|
+
T: torch.Tensor
|
|
59
|
+
exit_code: torch.Tensor
|
|
60
|
+
y: list
|
|
61
|
+
ctrl_at: torch.Tensor | None = None
|
|
62
|
+
addr_at: torch.Tensor | None = None
|
|
63
|
+
moved_at: torch.Tensor | None = None # held lanes: first tick a hold replaced a moved address
|
|
64
|
+
pc: torch.Tensor | None = None # [B, T] pc per tick (-1 after the lane stopped)
|
|
65
|
+
slots: torch.Tensor | None = None # [B, T, 38] int16 written byte/bit per slot, -1 none
|
|
66
|
+
full: dict | None = None # per-tick regs / flags / ea / store bytes (``record="full"``)
|
|
67
|
+
|
|
68
|
+
def stop_kind(self, lane: int) -> str:
|
|
69
|
+
from torchx86.machine import STOP_KINDS # noqa: PLC0415
|
|
70
|
+
|
|
71
|
+
return STOP_KINDS.get(int(self.stop[lane]), "alive")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Lanes:
|
|
75
|
+
def __init__(self, binary: Binary, inputs: list, *, device="cpu", cap: int = 20000, resident=None,
|
|
76
|
+
extra_resident=()):
|
|
77
|
+
torchx86()
|
|
78
|
+
self.b, self.B, self.dev, self.cap = binary, len(inputs), torch.device(device), cap
|
|
79
|
+
Machine = _held_machine_class()
|
|
80
|
+
self.m = Machine(binary.table, binary.pages, binary.perms, regs=binary.regs, eflags=binary.eflags,
|
|
81
|
+
pc=binary.entry, batch=self.B, device=device, step_cap=cap,
|
|
82
|
+
resident=None if resident is None else sorted(set(resident) | set(extra_resident)))
|
|
83
|
+
self.rows = binary.table.rows.to(self.dev)
|
|
84
|
+
self.F = binary.F
|
|
85
|
+
self._inject(inputs)
|
|
86
|
+
self.patches: list[tuple] = []
|
|
87
|
+
self.hold = None
|
|
88
|
+
self.ref = None
|
|
89
|
+
|
|
90
|
+
# ------------------------------------------------------------------ setup
|
|
91
|
+
def _offsets(self, addr: torch.Tensor):
|
|
92
|
+
"""Flat offsets into lane memory for byte addresses (-1 when not resident)."""
|
|
93
|
+
m = self.m
|
|
94
|
+
eq = (addr >> 12)[..., None] == m.pbase
|
|
95
|
+
i = (eq.long() * m.pidx).sum(-1)
|
|
96
|
+
off = m.rw_off[i]
|
|
97
|
+
ok = eq.any(-1) & (off >= 0)
|
|
98
|
+
return torch.where(ok, off + (addr & 0xFFF), -1)
|
|
99
|
+
|
|
100
|
+
def _inject(self, inputs: list) -> None:
|
|
101
|
+
if all(x is None for x in inputs):
|
|
102
|
+
return
|
|
103
|
+
if self.b.input_addr is None:
|
|
104
|
+
raise ValueError("inputs given but the binary has no input buffer address")
|
|
105
|
+
n = max(len(x) for x in inputs if x is not None)
|
|
106
|
+
off = self._offsets(torch.arange(n, device=self.dev) + self.b.input_addr)
|
|
107
|
+
if bool((off < 0).any()):
|
|
108
|
+
raise ValueError("the input buffer is not on a resident writable page")
|
|
109
|
+
for lane, x in enumerate(inputs):
|
|
110
|
+
if x is not None:
|
|
111
|
+
self.m.mem[lane, off[:len(x)]] = torch.tensor(list(x), dtype=torch.uint8, device=self.dev)
|
|
112
|
+
|
|
113
|
+
def patch(self, at, site, value) -> None:
|
|
114
|
+
"""Queue one patch per lane (tensors [B]; ``at`` < 0 or ``site`` < 0 means none)."""
|
|
115
|
+
t = lambda v: torch.as_tensor(v, dtype=torch.int64, device=self.dev).expand(self.B).clone()
|
|
116
|
+
self.patches.append((t(at), t(site), t(value)))
|
|
117
|
+
|
|
118
|
+
def hold_to(self, ref: dict, rix, lanes) -> None:
|
|
119
|
+
"""Hold ``lanes`` (bool [B]) to reference runs ``ref`` (from ``reference``), lane -> ``rix``."""
|
|
120
|
+
self.ref = {**ref, "rix": torch.as_tensor(rix, device=self.dev)}
|
|
121
|
+
self.hold = torch.as_tensor(lanes, dtype=torch.bool, device=self.dev)
|
|
122
|
+
self.m.ref, self.m.hold = self.ref, self.hold
|
|
123
|
+
|
|
124
|
+
def compare_to(self, ref: dict, rix) -> None:
|
|
125
|
+
"""Track divergence against reference runs (no hold)."""
|
|
126
|
+
self.ref = {**ref, "rix": torch.as_tensor(rix, device=self.dev)}
|
|
127
|
+
|
|
128
|
+
def _apply(self) -> None:
|
|
129
|
+
m = self.m
|
|
130
|
+
for at, site, val in self.patches:
|
|
131
|
+
hit = (at >= 0) & (site >= 0) & (m.steps == at) & (m.stop == ALIVE)
|
|
132
|
+
if not bool(hit.any()):
|
|
133
|
+
continue
|
|
134
|
+
reg = hit & (site < FLAG0)
|
|
135
|
+
if bool(reg.any()):
|
|
136
|
+
r, k = (site // 8).clamp(0, 15), site % 8
|
|
137
|
+
old = m.regs.gather(1, r[:, None])[:, 0]
|
|
138
|
+
top = k == 7 # byte 7: keep every shift inside int64
|
|
139
|
+
mask = torch.where(top, -(1 << 56), torch.full_like(k, 0xFF) << (8 * k).clamp(max=48))
|
|
140
|
+
v = (val & 0xFF)
|
|
141
|
+
byte = torch.where(top, torch.where(v >= 128, v - 256, v) << 56, v << (8 * k).clamp(max=48))
|
|
142
|
+
m.regs.scatter_(1, r[:, None], torch.where(reg, (old & ~mask) | byte, old)[:, None])
|
|
143
|
+
fl = hit & (site >= FLAG0) & (site < FLAG0 + 6)
|
|
144
|
+
if bool(fl.any()):
|
|
145
|
+
f = (site - FLAG0).clamp(0, 5)
|
|
146
|
+
cur = m.flags.gather(1, f[:, None])[:, 0]
|
|
147
|
+
m.flags.scatter_(1, f[:, None], torch.where(fl, val != 0, cur)[:, None])
|
|
148
|
+
mem = hit & (site >= 0x1000)
|
|
149
|
+
if bool(mem.any()):
|
|
150
|
+
off = self._offsets(site)
|
|
151
|
+
ok = mem & (off >= 0)
|
|
152
|
+
flat = torch.where(ok, self.lane_base * m.NW + off, self.lane_base * m.NW + m.NW - 1)
|
|
153
|
+
cur = m.mem.view(-1)[flat]
|
|
154
|
+
m.mem.view(-1).index_put_((flat,), torch.where(ok, val.to(torch.uint8), cur))
|
|
155
|
+
|
|
156
|
+
# ------------------------------------------------------------------ run
|
|
157
|
+
def run(self, record: str = "none") -> Result:
|
|
158
|
+
"""Run every lane to its stop. ``record``: none | pc | slots | full."""
|
|
159
|
+
m, dev, B, F = self.m, self.dev, self.B, self.F
|
|
160
|
+
self.lane_base = torch.arange(B, device=dev)
|
|
161
|
+
last_start = torch.zeros(B, dtype=torch.int64, device=dev)
|
|
162
|
+
ctrl_at = torch.full((B,), -1, dtype=torch.int64, device=dev)
|
|
163
|
+
addr_at = torch.full_like(ctrl_at, -1)
|
|
164
|
+
moved_at = torch.full_like(ctrl_at, -1)
|
|
165
|
+
pcs, slots, full = [], [], {k: [] for k in ("regs", "flags", "ea", "store_n", "new", "old", "rsi")}
|
|
166
|
+
exit_tick = torch.zeros(B, dtype=torch.bool, device=dev)
|
|
167
|
+
fdef = torch.tensor(self.b.fdef, device=dev)
|
|
168
|
+
shift_row = torch.tensor(self.b.shift_row, device=dev)
|
|
169
|
+
k8 = torch.arange(8, device=dev)
|
|
170
|
+
with torch.inference_mode():
|
|
171
|
+
for i in range(self.cap + 1):
|
|
172
|
+
self._apply()
|
|
173
|
+
alive = m.stop == ALIVE
|
|
174
|
+
if not bool(alive.any()):
|
|
175
|
+
break
|
|
176
|
+
t = m.steps.clone()
|
|
177
|
+
regs_before = m.regs.clone() if record in ("slots", "full") else None
|
|
178
|
+
rsi_before = m.regs[:, RSI].clone()
|
|
179
|
+
out_len_before = m.out_len.clone()
|
|
180
|
+
m._moved = None
|
|
181
|
+
rec = m.step(record=True)
|
|
182
|
+
retired = rec["retired"]
|
|
183
|
+
exited = alive & (m.stop == 1)
|
|
184
|
+
exit_tick |= exited
|
|
185
|
+
ticked = retired | exited
|
|
186
|
+
last_start = torch.where(m.out_len != out_len_before, out_len_before, last_start)
|
|
187
|
+
row = rec["row"]
|
|
188
|
+
U = self.rows[row]
|
|
189
|
+
if self.ref is not None:
|
|
190
|
+
ref, rix = self.ref, self.ref["rix"]
|
|
191
|
+
Tr = ref["T"][rix]
|
|
192
|
+
tt = t.clamp(max=ref["pc"].shape[1] - 1)
|
|
193
|
+
inref = t < Tr
|
|
194
|
+
pc_bad = ticked & (~inref | (rec["pc"] != ref["pc"][rix, tt]))
|
|
195
|
+
acc = (U[:, F["mload"]] | U[:, F["mstore"]]) > 0
|
|
196
|
+
ea_bad = ticked & inref & acc & ref["acc"][rix, tt] & (rec["ea"] != ref["ea"][rix, tt])
|
|
197
|
+
ctrl_at = torch.where((ctrl_at < 0) & pc_bad, t, ctrl_at)
|
|
198
|
+
addr_at = torch.where((addr_at < 0) & ea_bad, t, addr_at)
|
|
199
|
+
if m._moved is not None:
|
|
200
|
+
moved_at = torch.where((moved_at < 0) & m._moved & ticked, t, moved_at)
|
|
201
|
+
if self.hold is not None:
|
|
202
|
+
nt = m.steps.clamp(max=ref["pc"].shape[1] - 1)
|
|
203
|
+
force = self.hold & retired & (m.steps < Tr)
|
|
204
|
+
want = ref["pc"][rix, nt]
|
|
205
|
+
moved_at = torch.where((moved_at < 0) & force & (m.pc != want), t, moved_at)
|
|
206
|
+
m.pc.copy_(torch.where(force, want, m.pc))
|
|
207
|
+
if record != "none":
|
|
208
|
+
pcs.append(torch.where(ticked, rec["pc"], -1))
|
|
209
|
+
if record == "slots":
|
|
210
|
+
slots.append(self._slots(U, row, retired, regs_before, rec, fdef, shift_row, k8))
|
|
211
|
+
if record == "full":
|
|
212
|
+
full["regs"].append(m.regs.clone())
|
|
213
|
+
full["flags"].append(m.flags.clone())
|
|
214
|
+
full["ea"].append(rec["ea"])
|
|
215
|
+
full["store_n"].append(rec["store_n"])
|
|
216
|
+
full["new"].append(rec["new"].long())
|
|
217
|
+
full["old"].append(rec["old"])
|
|
218
|
+
full["rsi"].append(rsi_before)
|
|
219
|
+
T = m.steps + exit_tick.long()
|
|
220
|
+
if self.ref is not None:
|
|
221
|
+
Tr = self.ref["T"][self.ref["rix"]]
|
|
222
|
+
ctrl_at = torch.where((ctrl_at < 0) & (T != Tr), torch.minimum(T, Tr), ctrl_at)
|
|
223
|
+
ys = []
|
|
224
|
+
out = m.out.cpu()
|
|
225
|
+
for lane, (s, ln) in enumerate(zip(last_start.tolist(), m.out_len.tolist())):
|
|
226
|
+
ys.append(bytes(out[lane, s:ln].numpy().tobytes()))
|
|
227
|
+
res = Result(m.stop.clone(), T, m.exit_code.clone(), ys)
|
|
228
|
+
if self.ref is not None:
|
|
229
|
+
res.ctrl_at, res.addr_at, res.moved_at = ctrl_at, addr_at, moved_at
|
|
230
|
+
if record != "none":
|
|
231
|
+
res.pc = torch.stack(pcs, 1) if pcs else torch.zeros(B, 0, dtype=torch.int64, device=dev)
|
|
232
|
+
if record == "slots":
|
|
233
|
+
res.slots = torch.stack(slots, 1) if slots else torch.zeros(B, 0, NSLOT_LANE, dtype=torch.int16)
|
|
234
|
+
if record == "full":
|
|
235
|
+
res.full = {k: torch.stack(v, 1) for k, v in full.items()}
|
|
236
|
+
return res
|
|
237
|
+
|
|
238
|
+
def _slots(self, U, row, retired, regs_before, rec, fdef, shift_row, k8):
|
|
239
|
+
"""Written value per lane-slot this tick (int16, -1 = slot not written)."""
|
|
240
|
+
F, m = self.F, self.m
|
|
241
|
+
B = self.B
|
|
242
|
+
out = torch.full((B, NSLOT_LANE), -1, dtype=torch.int16, device=self.dev)
|
|
243
|
+
wd, dsh = U[:, F["wd"]], U[:, F["dsh"]]
|
|
244
|
+
lo = dsh // 8
|
|
245
|
+
regmask = torch.where((wd >= 4)[:, None], True, (k8 >= lo[:, None]) & (k8 < (lo + wd)[:, None]))
|
|
246
|
+
|
|
247
|
+
def regbytes(reg):
|
|
248
|
+
v = m.regs.gather(1, reg.clamp(0, 15)[:, None])[:, 0]
|
|
249
|
+
return ((v[:, None] >> (8 * k8)) & 0xFF).to(torch.int16)
|
|
250
|
+
|
|
251
|
+
dst = (U[:, F["dk"]] == 1) & retired
|
|
252
|
+
out[:, S_DST:S_DST + 8] = torch.where(dst[:, None] & regmask, regbytes(U[:, F["dreg"]]), out[:, S_DST:S_DST + 8])
|
|
253
|
+
d2 = (U[:, F["d2"]] >= 0) & retired
|
|
254
|
+
d2mask = torch.where((wd >= 4)[:, None], True, k8 < wd[:, None])
|
|
255
|
+
out[:, S_D2:S_D2 + 8] = torch.where(d2[:, None] & d2mask, regbytes(torch.full_like(wd, RDX)), out[:, S_D2:S_D2 + 8])
|
|
256
|
+
sp = (U[:, F["spk"]] == 1) & retired
|
|
257
|
+
out[:, S_SP:S_SP + 8] = torch.where(sp[:, None], regbytes(torch.full_like(wd, RSP)), out[:, S_SP:S_SP + 8])
|
|
258
|
+
st = rec["store_n"]
|
|
259
|
+
out[:, S_MEM:S_MEM + 8] = torch.where(retired[:, None] & (k8 < st[:, None]), rec["new"].to(torch.int16),
|
|
260
|
+
out[:, S_MEM:S_MEM + 8])
|
|
261
|
+
fbits = fdef[row]
|
|
262
|
+
# a shift or rotate by zero writes no flags
|
|
263
|
+
cnt = torch.where(U[:, F["bk"]] == 1, regs_before[:, RCX], U[:, F["imm"]]) & torch.where(wd == 8, 63, 31)
|
|
264
|
+
fbits = torch.where(shift_row[row] & (cnt == 0), 0, fbits)
|
|
265
|
+
fw = ((fbits[:, None] >> torch.arange(6, device=self.dev)) & 1).bool() & retired[:, None]
|
|
266
|
+
out[:, S_FL:S_FL + 6] = torch.where(fw, m.flags.to(torch.int16), out[:, S_FL:S_FL + 6])
|
|
267
|
+
return out
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def reference(binary: Binary, res: Result, device=None) -> dict:
|
|
271
|
+
"""Reference arrays for ``hold_to`` / ``compare_to`` from runs recorded with ``record="full"``."""
|
|
272
|
+
dev = device or res.pc.device
|
|
273
|
+
F = binary.F
|
|
274
|
+
rows = torch.tensor(binary.rows, device=dev)
|
|
275
|
+
pcs = res.pc.to(dev)
|
|
276
|
+
sorted_pcs = torch.tensor(binary.pcs, dtype=torch.int64, device=dev)
|
|
277
|
+
j = torch.searchsorted(sorted_pcs, pcs).clamp(max=len(binary.pcs) - 1)
|
|
278
|
+
r = torch.where(sorted_pcs[j] == pcs, j + 1, 0)
|
|
279
|
+
acc = ((rows[r, F["mload"]] | rows[r, F["mstore"]]) > 0) & (pcs >= 0)
|
|
280
|
+
return {"pc": pcs, "ea": res.full["ea"].to(dev), "acc": acc, "rsi": res.full["rsi"].to(dev),
|
|
281
|
+
"T": res.T.to(dev)}
|