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,285 @@
|
|
|
1
|
+
"""Static facts of one x86-64 binary: decoded micro-op table, CFG, dominator loops, sites, operands.
|
|
2
|
+
|
|
3
|
+
The executor is torchx86 (isa-bench ``models/torchx86``), an optional dependency imported normally,
|
|
4
|
+
never copied and never put on ``sys.path`` by mdb. It and ``isa_bench`` (for ``isa_bench.state``)
|
|
5
|
+
must be importable: install isa-bench (``pip install -e <isa-bench checkout>``) and put torchx86's
|
|
6
|
+
``src`` directory on ``PYTHONPATH`` (it has no packaging of its own), plus ``pip install capstone``.
|
|
7
|
+
|
|
8
|
+
Sites are integers, one per byte (the binctr web-key convention): register byte ``8*gpr + byte``
|
|
9
|
+
(0..127), flag ``128 + f`` (CF PF AF ZF SF OF), memory byte = its address (>= 0x1000).
|
|
10
|
+
Write slots are the fixed per-tick positions a write can land in (``SLOTS``): the destination
|
|
11
|
+
register's 8 bytes, the second destination (RDX of mul/div), RSP, the stored memory bytes, the six
|
|
12
|
+
flags, and the three registers a ``write`` syscall returns in.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
GPRS = ("rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
|
|
23
|
+
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15")
|
|
24
|
+
FLAGS = ("CF", "PF", "AF", "ZF", "SF", "OF")
|
|
25
|
+
RAX, RCX, RDX, RSP, RBP, RSI, RDI, R11 = 0, 1, 2, 4, 5, 6, 7, 11
|
|
26
|
+
FLAG0 = 128
|
|
27
|
+
# write slots: 0-7 dst reg bytes, 8-15 d2 (RDX), 16-23 RSP, 24-31 stored bytes, 32-37 flags,
|
|
28
|
+
# 38-61 syscall returns (RAX, RCX, R11); lanes record slots 0..37 only
|
|
29
|
+
S_DST, S_D2, S_SP, S_MEM, S_FL, S_SYS = 0, 8, 16, 24, 32, 38
|
|
30
|
+
NSLOT_LANE, NSLOT = 38, 62
|
|
31
|
+
SLOT_ROLE = (["dst"] * 8 + ["d2"] * 8 + ["sp"] * 8 + ["mem"] * 8 + [f"flags.{f}" for f in FLAGS]
|
|
32
|
+
+ ["sys.rax"] * 8 + ["sys.rcx"] * 8 + ["sys.r11"] * 8)
|
|
33
|
+
KINDS = ("op", "call", "ret", "jmp", "jcc", "syscall", "stop")
|
|
34
|
+
# condition code -> flags it reads (torchx86 cc numbering: o no b ae e ne be a s ns p np l ge le g)
|
|
35
|
+
CC_FLAGS = {0: "OF", 1: "OF", 2: "CF", 3: "CF", 4: "ZF", 5: "ZF", 6: "CF ZF", 7: "CF ZF", 8: "SF", 9: "SF",
|
|
36
|
+
10: "PF", 11: "PF", 12: "SF OF", 13: "SF OF", 14: "ZF SF OF", 15: "ZF SF OF"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def torchx86():
|
|
40
|
+
"""The torchx86 package (an optional dependency, see the module docstring)."""
|
|
41
|
+
try:
|
|
42
|
+
import torchx86 as tx # noqa: PLC0415
|
|
43
|
+
from torchx86 import decode, machine # noqa: F401, PLC0415
|
|
44
|
+
except ImportError as why:
|
|
45
|
+
raise ImportError("mdb.machines.x86 needs the optional torchx86 package (isa-bench "
|
|
46
|
+
"models/torchx86/src) and capstone: `pip install capstone`, "
|
|
47
|
+
"`pip install -e <isa-bench checkout>` and add "
|
|
48
|
+
"<isa-bench>/models/torchx86/src to PYTHONPATH") from why
|
|
49
|
+
return tx
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def site_name(site: int) -> str:
|
|
53
|
+
if site < FLAG0:
|
|
54
|
+
return f"{GPRS[site // 8]}[{8 * (site % 8)}:{8 * (site % 8) + 8}]"
|
|
55
|
+
if site < FLAG0 + 6:
|
|
56
|
+
return f"flags.{FLAGS[site - FLAG0]}"
|
|
57
|
+
return f"mem[{site:#x}:1]"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def site_bits(site: int) -> int:
|
|
61
|
+
return 1 if FLAG0 <= site < FLAG0 + 6 else 8
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class Loop:
|
|
66
|
+
id: int
|
|
67
|
+
head: int
|
|
68
|
+
body: frozenset
|
|
69
|
+
function: int
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class Binary:
|
|
74
|
+
name: str
|
|
75
|
+
table: object # torchx86 Table
|
|
76
|
+
pages: dict
|
|
77
|
+
perms: dict
|
|
78
|
+
regs: list # initial GPRs (uint64 values)
|
|
79
|
+
eflags: int
|
|
80
|
+
entry: int
|
|
81
|
+
input_addr: int | None = None
|
|
82
|
+
input_size: int = 0
|
|
83
|
+
image_sha256: str = ""
|
|
84
|
+
# derived in __post_init__
|
|
85
|
+
rows: np.ndarray = field(init=False, repr=False)
|
|
86
|
+
pcs: list = field(init=False, repr=False)
|
|
87
|
+
kind: list = field(init=False, repr=False)
|
|
88
|
+
loops: list = field(init=False, repr=False)
|
|
89
|
+
functions: dict = field(init=False, repr=False)
|
|
90
|
+
|
|
91
|
+
def __post_init__(self):
|
|
92
|
+
from torchx86.decode import FIELDS # noqa: PLC0415
|
|
93
|
+
|
|
94
|
+
self.F = {n: i for i, n in enumerate(FIELDS)}
|
|
95
|
+
self.rows = self.table.rows.cpu().numpy()
|
|
96
|
+
self.pcs = [int(p) for p in self.table.pcs.tolist()]
|
|
97
|
+
self.row_index = {pc: i + 1 for i, pc in enumerate(self.pcs)}
|
|
98
|
+
self.kind = [self._kind(r) for r in range(len(self.rows))]
|
|
99
|
+
self._flag_tables()
|
|
100
|
+
self._cfg()
|
|
101
|
+
|
|
102
|
+
# ------------------------------------------------------------------ loading
|
|
103
|
+
@classmethod
|
|
104
|
+
def load(cls, program_dir, *, input_symbol: str = "gt_input", name: str | None = None) -> Binary:
|
|
105
|
+
"""A program directory of the isa-bench reference store: ``mem.bin`` (image), ``trace.npz``
|
|
106
|
+
(native row 0 = initial state) and optionally ``prog.elf`` (symbol table only, for the input
|
|
107
|
+
buffer address and size; debug sections are never read)."""
|
|
108
|
+
torchx86()
|
|
109
|
+
from isa_bench.state import load_image # noqa: PLC0415
|
|
110
|
+
from torchx86.decode import decode # noqa: PLC0415
|
|
111
|
+
|
|
112
|
+
d = Path(program_dir)
|
|
113
|
+
pages, perms = load_image(d / "mem.bin")
|
|
114
|
+
row = [int(v) for v in np.load(d / "trace.npz")["steps"][0]]
|
|
115
|
+
addr, size = None, 0
|
|
116
|
+
if (d / "prog.elf").exists():
|
|
117
|
+
addr, size = elf_symbol(d / "prog.elf", input_symbol)
|
|
118
|
+
table = decode(pages, perms, row[0])
|
|
119
|
+
sha = hashlib.sha256((d / "mem.bin").read_bytes()).hexdigest()
|
|
120
|
+
return cls(name or d.name, table, pages, perms, row[1:17], row[17] & ~0x100, row[0], addr, size, sha)
|
|
121
|
+
|
|
122
|
+
@classmethod
|
|
123
|
+
def from_image(cls, pages: dict, perms: dict, *, regs, eflags: int, entry: int, input_addr=None,
|
|
124
|
+
input_size: int = 0, name: str = "image") -> Binary:
|
|
125
|
+
torchx86()
|
|
126
|
+
from torchx86.decode import decode # noqa: PLC0415
|
|
127
|
+
|
|
128
|
+
sha = hashlib.sha256(b"".join(bytes(pages[p]) for p in sorted(pages))).hexdigest()
|
|
129
|
+
return cls(name, decode(pages, perms, entry), pages, perms, list(regs), eflags, entry, input_addr,
|
|
130
|
+
input_size, sha)
|
|
131
|
+
|
|
132
|
+
# ------------------------------------------------------------------ rows
|
|
133
|
+
def g(self, r: int, f: str) -> int:
|
|
134
|
+
return int(self.rows[r, self.F[f]])
|
|
135
|
+
|
|
136
|
+
def row_of(self, pc: int) -> int:
|
|
137
|
+
return self.row_index.get(int(pc), 0)
|
|
138
|
+
|
|
139
|
+
def text(self, pc: int) -> str:
|
|
140
|
+
return self.table.text[self.row_of(pc)]
|
|
141
|
+
|
|
142
|
+
def mnemonic(self, pc: int) -> str:
|
|
143
|
+
return self.table.mnemonic[self.row_of(pc)]
|
|
144
|
+
|
|
145
|
+
def _kind(self, r: int) -> str:
|
|
146
|
+
if r == 0 or self.g(r, "stop"):
|
|
147
|
+
return "stop"
|
|
148
|
+
mn = self.table.mnemonic[r]
|
|
149
|
+
if mn in ("call", "ret", "jmp", "syscall"):
|
|
150
|
+
return mn
|
|
151
|
+
return "jcc" if mn.startswith("j") else "op"
|
|
152
|
+
|
|
153
|
+
def _flag_tables(self) -> None:
|
|
154
|
+
"""Per row: flag bits written (fmask), and the subset that is architecturally defined."""
|
|
155
|
+
from isa_bench.state import flag_effects # noqa: PLC0415
|
|
156
|
+
|
|
157
|
+
R = len(self.rows)
|
|
158
|
+
self.fwrite = np.zeros(R, np.int64)
|
|
159
|
+
self.fdef = np.zeros(R, np.int64)
|
|
160
|
+
for r in range(1, R):
|
|
161
|
+
fm = self.g(r, "fmask")
|
|
162
|
+
eff = flag_effects(self.table.mnemonic[r])
|
|
163
|
+
defined = set(FLAGS) if eff is None else set(eff[0])
|
|
164
|
+
self.fwrite[r] = fm
|
|
165
|
+
self.fdef[r] = fm & sum(1 << i for i, f in enumerate(FLAGS) if f in defined)
|
|
166
|
+
from torchx86.decode import CLASSES # noqa: PLC0415
|
|
167
|
+
|
|
168
|
+
cls = self.rows[:, self.F["cls"]]
|
|
169
|
+
self.shift_row = (cls >= CLASSES.index("shl")) & (cls <= CLASSES.index("ror")) & (self.rows[:, self.F["fmask"]] != 0)
|
|
170
|
+
|
|
171
|
+
# ------------------------------------------------------------------ CFG, dominators, loops
|
|
172
|
+
def successors(self, pc: int) -> list[int]:
|
|
173
|
+
r = self.row_of(pc)
|
|
174
|
+
k = self.kind[r]
|
|
175
|
+
nxt, tgt, pck = self.g(r, "next"), self.g(r, "target"), self.g(r, "pck")
|
|
176
|
+
if k in ("stop", "ret") or (k == "jmp" and pck == 2):
|
|
177
|
+
return []
|
|
178
|
+
if k == "jmp":
|
|
179
|
+
return [tgt]
|
|
180
|
+
if k == "jcc":
|
|
181
|
+
return [nxt, tgt]
|
|
182
|
+
return [nxt] # op, syscall, call (intraprocedural fallthrough)
|
|
183
|
+
|
|
184
|
+
def _cfg(self) -> None:
|
|
185
|
+
entries = {self.entry} | {self.g(r, "target") for r in range(1, len(self.rows)) if self.kind[r] == "call"}
|
|
186
|
+
self.functions, self.loops = {}, []
|
|
187
|
+
heads: dict[int, set] = {}
|
|
188
|
+
func_of_head = {}
|
|
189
|
+
for e in sorted(entries):
|
|
190
|
+
if self.row_of(e) == 0:
|
|
191
|
+
continue
|
|
192
|
+
nodes, work = set(), [e]
|
|
193
|
+
while work:
|
|
194
|
+
n = work.pop()
|
|
195
|
+
if n in nodes or self.row_of(n) == 0:
|
|
196
|
+
continue
|
|
197
|
+
nodes.add(n)
|
|
198
|
+
work.extend(self.successors(n))
|
|
199
|
+
self.functions[e] = nodes
|
|
200
|
+
preds = {n: [] for n in nodes}
|
|
201
|
+
for n in nodes:
|
|
202
|
+
for s in self.successors(n):
|
|
203
|
+
if s in nodes:
|
|
204
|
+
preds[s].append(n)
|
|
205
|
+
dom = {n: set(nodes) for n in nodes}
|
|
206
|
+
dom[e] = {e}
|
|
207
|
+
changed = True
|
|
208
|
+
while changed:
|
|
209
|
+
changed = False
|
|
210
|
+
for n in sorted(nodes):
|
|
211
|
+
if n == e:
|
|
212
|
+
continue
|
|
213
|
+
ps = [dom[p] for p in preds[n]]
|
|
214
|
+
new = (set.intersection(*ps) if ps else set()) | {n}
|
|
215
|
+
if new != dom[n]:
|
|
216
|
+
dom[n], changed = new, True
|
|
217
|
+
for n in nodes:
|
|
218
|
+
for h in self.successors(n):
|
|
219
|
+
if h in nodes and h in dom[n]: # back edge n -> h
|
|
220
|
+
body, work = {h}, [n]
|
|
221
|
+
while work:
|
|
222
|
+
x = work.pop()
|
|
223
|
+
if x not in body:
|
|
224
|
+
body.add(x)
|
|
225
|
+
work.extend(preds[x])
|
|
226
|
+
heads.setdefault(h, set()).update(body)
|
|
227
|
+
func_of_head[h] = e
|
|
228
|
+
R = len(self.rows)
|
|
229
|
+
self.head_row = np.full(R, -1, np.int64)
|
|
230
|
+
for i, h in enumerate(sorted(heads)):
|
|
231
|
+
self.loops.append(Loop(i, h, frozenset(heads[h]), func_of_head[h]))
|
|
232
|
+
self.head_row[self.row_of(h)] = i
|
|
233
|
+
self.inbody = np.zeros((max(len(self.loops), 1), R), bool)
|
|
234
|
+
for lp in self.loops:
|
|
235
|
+
for pc in lp.body:
|
|
236
|
+
self.inbody[lp.id, self.row_of(pc)] = True
|
|
237
|
+
self.leaders = {self.entry} | set(entries)
|
|
238
|
+
for r in range(1, R):
|
|
239
|
+
if self.kind[r] in ("jcc", "jmp", "call", "ret", "syscall"):
|
|
240
|
+
self.leaders.add(self.g(r, "next"))
|
|
241
|
+
if self.g(r, "pck") == 1:
|
|
242
|
+
self.leaders.add(self.g(r, "target"))
|
|
243
|
+
|
|
244
|
+
# ------------------------------------------------------------------ operands
|
|
245
|
+
def operand_text(self, pc: int, slot: int) -> str:
|
|
246
|
+
"""The written operand of a slot at pc, in the address grammar (``rax[0:8]``, ``mem[rbp-0x8:8]``)."""
|
|
247
|
+
role = SLOT_ROLE[slot]
|
|
248
|
+
k = slot % 8
|
|
249
|
+
if role == "dst":
|
|
250
|
+
r = self.row_of(pc)
|
|
251
|
+
if self.g(r, "dk") == 2:
|
|
252
|
+
return f"mem[{self.mem_operand(pc)}]"
|
|
253
|
+
return f"{GPRS[self.g(r, 'dreg')]}[{8 * k}:{8 * k + 8}]"
|
|
254
|
+
if role == "d2":
|
|
255
|
+
return f"rdx[{8 * k}:{8 * k + 8}]"
|
|
256
|
+
if role == "sp":
|
|
257
|
+
return f"rsp[{8 * k}:{8 * k + 8}]"
|
|
258
|
+
if role == "mem":
|
|
259
|
+
return f"mem[{self.mem_operand(pc)}+{k}:1]" if k else f"mem[{self.mem_operand(pc)}:1]"
|
|
260
|
+
if role.startswith("flags."):
|
|
261
|
+
return role
|
|
262
|
+
reg = role.split(".")[1]
|
|
263
|
+
return f"{reg}[{8 * k}:{8 * k + 8}]"
|
|
264
|
+
|
|
265
|
+
def mem_operand(self, pc: int) -> str:
|
|
266
|
+
r = self.row_of(pc)
|
|
267
|
+
b, i, s, d = self.g(r, "mbase"), self.g(r, "midx"), self.g(r, "mscale"), self.g(r, "mdisp")
|
|
268
|
+
parts = ([GPRS[b]] if b >= 0 else []) + ([f"{GPRS[i]}*{s}"] if i >= 0 else [])
|
|
269
|
+
txt = "+".join(parts)
|
|
270
|
+
if d or not parts:
|
|
271
|
+
txt = f"{txt}{'-' if d < 0 else '+'}{abs(d):#x}" if parts else f"{d & ((1 << 64) - 1):#x}"
|
|
272
|
+
return txt
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def elf_symbol(path, name: str) -> tuple[int | None, int]:
|
|
276
|
+
"""(address, size) of a symbol from the ELF ``.symtab`` (no debug section is read)."""
|
|
277
|
+
try:
|
|
278
|
+
from elftools.elf.elffile import ELFFile # noqa: PLC0415
|
|
279
|
+
except ImportError:
|
|
280
|
+
return None, 0
|
|
281
|
+
with open(path, "rb") as fh:
|
|
282
|
+
sec = ELFFile(fh).get_section_by_name(".symtab")
|
|
283
|
+
for sym in (sec.get_symbol_by_name(name) or []) if sec is not None else []:
|
|
284
|
+
return int(sym["st_value"]), int(sym["st_size"])
|
|
285
|
+
return None, 0
|
mdb/machines/x86/grid.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Run-2 machinery: a patch grid {zero, unaligned resample, aligned resample} x {step index, execution
|
|
2
|
+
index} over cells of a base run, executed as lanes, one row per (cell, rule, alignment, donor).
|
|
3
|
+
|
|
4
|
+
The cell list is the base run's (``Trace.cells``; every live cell is patched). For a cell c
|
|
5
|
+
defined at tick t on site s, the patched value is:
|
|
6
|
+
|
|
7
|
+
- ``zero``: 0. The alignment does not enter (the base run is the reference), so both alignments
|
|
8
|
+
share one lane.
|
|
9
|
+
- ``unaligned`` resample: the value of a cell on the same site in donor run d, drawn uniformly over
|
|
10
|
+
that site's cells in d (seeded by (seed, cell, donor)): the right kind of value from the wrong
|
|
11
|
+
time. Both alignments share one lane.
|
|
12
|
+
- ``aligned`` resample, ``step`` index: the value of site s in donor d after tick t (same step
|
|
13
|
+
index, same site), i.e. activation patching by position.
|
|
14
|
+
- ``aligned`` resample, ``exec`` index: the value of the donor cell with c's alignment key
|
|
15
|
+
(execution index of the defining tick + write slot).
|
|
16
|
+
|
|
17
|
+
Each patch runs on two lanes from the base input: free, and held (branch outcomes and effective
|
|
18
|
+
addresses frozen to the base run, ``lanes`` hold). Per row: ``verdict`` of the free lane (``fault``
|
|
19
|
+
> ``nonterminating`` > ``path-diverged`` > ``effect`` / ``no effect``; ``no-donor`` when the donor
|
|
20
|
+
has no such cell; a donor value equal to the base value is not run: ``noop``), the total effect
|
|
21
|
+
(``y_changed``) and the frozen-selection effect (``frozen_effect``) as the paired column, the
|
|
22
|
+
divergence ticks, the consumer delta (changed y bytes, exit-code change), and the structural copy
|
|
23
|
+
web (``Trace.web_labels``, this backend's own) of the base cell and of the donor cell, so type
|
|
24
|
+
coherence can be read as base_web == donor_web. No scoring happens here.
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import random
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
import torch
|
|
32
|
+
|
|
33
|
+
from .binary import site_name
|
|
34
|
+
from .lanes import Lanes, reference
|
|
35
|
+
from .method import _take, resident_pages
|
|
36
|
+
from .session import verdict_of
|
|
37
|
+
from .trace import INIT, record
|
|
38
|
+
|
|
39
|
+
RULES = ("zero", "unaligned", "aligned")
|
|
40
|
+
ALIGNS = ("step", "exec")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _web(key) -> str:
|
|
44
|
+
return f"init:{key[1]:#x}" if key[0] == "init" else f"{key[0]:x}/{key[1]}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def run_grid(binary, base_input, donor_inputs, *, cells=None, device="cpu", chunk: int = 4096, seed: int = 0,
|
|
48
|
+
hold: bool = True, cap_factor: int = 4, log=print, traces=None) -> dict:
|
|
49
|
+
dev = torch.device(device)
|
|
50
|
+
if traces is None:
|
|
51
|
+
traces, res = record(binary, [base_input, *donor_inputs], device=device)
|
|
52
|
+
else:
|
|
53
|
+
traces, res = traces
|
|
54
|
+
base, donors = traces[0], traces[1:]
|
|
55
|
+
ref = reference(binary, _take(res, 0), dev)
|
|
56
|
+
resident = resident_pages(binary, traces)
|
|
57
|
+
bweb = [_web(k) for k in base.web_labels()]
|
|
58
|
+
dweb = [[_web(k) for k in d.web_labels()] for d in donors]
|
|
59
|
+
by_site = [{} for _ in donors]
|
|
60
|
+
for j, d in enumerate(donors):
|
|
61
|
+
for c in d.cells:
|
|
62
|
+
by_site[j].setdefault(c.site, []).append(c.id)
|
|
63
|
+
first_div = []
|
|
64
|
+
for d in donors:
|
|
65
|
+
T = min(d.T, base.T)
|
|
66
|
+
first_div.append(next((t for t in range(T) if d.pc[t] != base.pc[t]), T))
|
|
67
|
+
cells = list(range(len(base.cells))) if cells is None else list(cells)
|
|
68
|
+
rows, lane_of = [], {}
|
|
69
|
+
|
|
70
|
+
def lane(at, site, value):
|
|
71
|
+
return lane_of.setdefault((at, site, value), len(lane_of))
|
|
72
|
+
|
|
73
|
+
for i in cells:
|
|
74
|
+
c = base.cells[i]
|
|
75
|
+
at = 0 if c.def_ == INIT else c.def_ + 1
|
|
76
|
+
common = {"cell": i, "site": c.site, "def": c.def_, "pc": c.pc, "slot": c.slot, "base_value": c.value,
|
|
77
|
+
"base_web": bweb[i]}
|
|
78
|
+
|
|
79
|
+
def add(rule, align, donor, value, dtick, web):
|
|
80
|
+
row = {**common, "rule": rule, "align": align, "donor": donor, "value": -1 if value is None else value,
|
|
81
|
+
"donor_tick": dtick, "donor_web": web,
|
|
82
|
+
"after_divergence": donor >= 0 and c.def_ >= first_div[donor]}
|
|
83
|
+
if value is None:
|
|
84
|
+
row["status"] = "no-donor"
|
|
85
|
+
elif value == c.value:
|
|
86
|
+
row["status"] = "noop"
|
|
87
|
+
else:
|
|
88
|
+
row["status"], row["lane"] = "run", lane(at, c.site, value)
|
|
89
|
+
rows.append(row)
|
|
90
|
+
|
|
91
|
+
for align in ALIGNS:
|
|
92
|
+
add("zero", align, -1, 0, -1, "")
|
|
93
|
+
for j, d in enumerate(donors):
|
|
94
|
+
pool = by_site[j].get(c.site, [])
|
|
95
|
+
rng = random.Random(hash((seed, i, j)) & 0xFFFFFFFF)
|
|
96
|
+
u = d.cells[rng.choice(pool)] if pool else None
|
|
97
|
+
for align in ALIGNS:
|
|
98
|
+
add("unaligned", align, j, None if u is None else u.value, -2 if u is None else u.def_,
|
|
99
|
+
"" if u is None else dweb[j][u.id])
|
|
100
|
+
k = d.by_key.get(c.key)
|
|
101
|
+
add("aligned", "exec", j, None if k is None else d.cells[k].value, -2 if k is None else d.cells[k].def_,
|
|
102
|
+
"" if k is None else dweb[j][k])
|
|
103
|
+
if c.def_ < d.T:
|
|
104
|
+
dc = d.cell_at(c.site, c.def_)
|
|
105
|
+
add("aligned", "step", j, d.value(c.site, c.def_), -2 if dc is None else dc.def_,
|
|
106
|
+
"" if dc is None else dweb[j][dc.id])
|
|
107
|
+
else:
|
|
108
|
+
add("aligned", "step", j, None, -2, "")
|
|
109
|
+
patches = sorted(lane_of, key=lane_of.get)
|
|
110
|
+
log(f"{binary.name}: grid rows {len(rows)} unique patches {len(patches)} lanes {len(patches) * (2 if hold else 1)}")
|
|
111
|
+
base_y = (base.y, base.exit_code)
|
|
112
|
+
free = {k: [] for k in ("stop", "ctrl_at", "addr_at", "y", "exit")}
|
|
113
|
+
held = {k: [] for k in ("stop", "y", "exit", "moved_at")}
|
|
114
|
+
cap = cap_factor * base.T + 64
|
|
115
|
+
per = max(1, chunk // (2 if hold else 1))
|
|
116
|
+
for s in range(0, len(patches), per):
|
|
117
|
+
part = patches[s:s + per]
|
|
118
|
+
n = len(part)
|
|
119
|
+
B = 2 * n if hold else n
|
|
120
|
+
lanes = Lanes(binary, [base_input] * B, device=dev, cap=cap, resident=resident)
|
|
121
|
+
at = torch.tensor([p[0] for p in part], dtype=torch.int64, device=dev)
|
|
122
|
+
site = torch.tensor([p[1] for p in part], dtype=torch.int64, device=dev)
|
|
123
|
+
val = torch.tensor([p[2] for p in part], dtype=torch.int64, device=dev)
|
|
124
|
+
rep = (lambda x: torch.cat([x, x])) if hold else (lambda x: x)
|
|
125
|
+
lanes.patch(rep(at), rep(site), rep(val))
|
|
126
|
+
rix = torch.zeros(B, dtype=torch.int64, device=dev)
|
|
127
|
+
if hold:
|
|
128
|
+
lanes.hold_to(ref, rix, torch.arange(B, device=dev) >= n)
|
|
129
|
+
else:
|
|
130
|
+
lanes.compare_to(ref, rix)
|
|
131
|
+
r = lanes.run()
|
|
132
|
+
for q in range(n):
|
|
133
|
+
free["stop"].append(r.stop_kind(q))
|
|
134
|
+
free["ctrl_at"].append(int(r.ctrl_at[q]))
|
|
135
|
+
free["addr_at"].append(int(r.addr_at[q]))
|
|
136
|
+
free["y"].append(r.y[q])
|
|
137
|
+
free["exit"].append(int(r.exit_code[q]))
|
|
138
|
+
if hold:
|
|
139
|
+
held["stop"].append(r.stop_kind(n + q))
|
|
140
|
+
held["y"].append(r.y[n + q])
|
|
141
|
+
held["exit"].append(int(r.exit_code[n + q]))
|
|
142
|
+
held["moved_at"].append(int(r.moved_at[n + q]))
|
|
143
|
+
log(f" patches {s + n}/{len(patches)}")
|
|
144
|
+
out = {k: [] for k in ("cell", "site", "def", "pc", "slot", "rule", "align", "donor", "donor_tick", "value",
|
|
145
|
+
"base_value", "status", "verdict", "y_changed", "path_diverged", "ctrl_at", "addr_at",
|
|
146
|
+
"stop", "frozen_effect", "frozen_stop", "moved_at", "y_diff_bytes", "y_diff_mask",
|
|
147
|
+
"exit_delta", "base_web", "donor_web", "after_divergence")}
|
|
148
|
+
for row in rows:
|
|
149
|
+
for k in ("cell", "site", "def", "pc", "slot", "rule", "align", "donor", "donor_tick", "value", "base_value",
|
|
150
|
+
"status", "base_web", "donor_web", "after_divergence"):
|
|
151
|
+
out[k].append(row[k])
|
|
152
|
+
if row["status"] != "run":
|
|
153
|
+
out["verdict"].append(row["status"] if row["status"] == "no-donor" else "no effect")
|
|
154
|
+
for k, v in (("y_changed", False), ("path_diverged", False), ("ctrl_at", -1), ("addr_at", -1),
|
|
155
|
+
("stop", ""), ("frozen_effect", False), ("frozen_stop", ""), ("moved_at", -1),
|
|
156
|
+
("y_diff_bytes", 0), ("y_diff_mask", ""), ("exit_delta", 0)):
|
|
157
|
+
out[k].append(v)
|
|
158
|
+
continue
|
|
159
|
+
q = row["lane"]
|
|
160
|
+
y, e, st = free["y"][q], free["exit"][q], free["stop"][q]
|
|
161
|
+
yc = (y, e) != base_y or st != "exit"
|
|
162
|
+
div = free["ctrl_at"][q] >= 0 or free["addr_at"][q] >= 0
|
|
163
|
+
out["verdict"].append(verdict_of(st, div, yc))
|
|
164
|
+
out["y_changed"].append(yc)
|
|
165
|
+
out["path_diverged"].append(div)
|
|
166
|
+
out["ctrl_at"].append(free["ctrl_at"][q])
|
|
167
|
+
out["addr_at"].append(free["addr_at"][q])
|
|
168
|
+
out["stop"].append(st)
|
|
169
|
+
mask = [i for i in range(max(len(y), len(base.y))) if i >= len(y) or i >= len(base.y) or y[i] != base.y[i]]
|
|
170
|
+
out["y_diff_bytes"].append(len(mask))
|
|
171
|
+
out["y_diff_mask"].append(f"{sum(1 << i for i in mask):x}" if mask else "")
|
|
172
|
+
out["exit_delta"].append(e - base.exit_code)
|
|
173
|
+
if hold:
|
|
174
|
+
fy = (held["y"][q], held["exit"][q]) != base_y or held["stop"][q] != "exit"
|
|
175
|
+
out["frozen_effect"].append(fy)
|
|
176
|
+
out["frozen_stop"].append(held["stop"][q])
|
|
177
|
+
out["moved_at"].append(held["moved_at"][q])
|
|
178
|
+
else:
|
|
179
|
+
out["frozen_effect"].append(False)
|
|
180
|
+
out["frozen_stop"].append("")
|
|
181
|
+
out["moved_at"].append(-1)
|
|
182
|
+
meta = {"program": binary.name, "T": base.T, "cells": len(cells), "rows": len(rows), "patches": len(patches),
|
|
183
|
+
"donors": len(donors), "first_pc_divergence_per_donor": first_div, "hold": hold, "seed": seed,
|
|
184
|
+
"site_names": {str(s): site_name(s) for s in sorted(set(out["site"]))}}
|
|
185
|
+
return {"columns": {k: np.array(v) for k, v in out.items()}, "meta": meta}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
__all__ = ["run_grid", "RULES", "ALIGNS"]
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Execution index: the input-invariant name of a dynamic instruction instance.
|
|
2
|
+
|
|
3
|
+
An instance is named by (call string, iteration count of every enclosing loop, pc) (Xin/Sumner/Zhang, PLDI 2008).
|
|
4
|
+
Loops are natural loops of the static CFG, headed by a node that
|
|
5
|
+
dominates its back edge's source (``Binary.loops``), not merely targets of backward jumps.
|
|
6
|
+
|
|
7
|
+
Rule per tick, in this order:
|
|
8
|
+
1. leave loops: pop the top loop while it belongs to the current frame and pc is outside its body;
|
|
9
|
+
2. arrive at a loop head: the top loop is this loop in this frame -> iteration + 1, else push it at 0;
|
|
10
|
+
3. the key is a 64-bit mix of (pc, call-string hash, the loop stack's (loop, iteration) pairs);
|
|
11
|
+
4. after the key: ``call`` pushes the call site into the call string; ``ret`` pops it and drops the
|
|
12
|
+
callee's loops.
|
|
13
|
+
|
|
14
|
+
Two implementations, one rule: ``readable`` (Python, one lane, tuples for display) and ``keys``
|
|
15
|
+
(torch, B lanes at once, used for alignment). ``key_of`` hashes a readable index exactly as
|
|
16
|
+
``keys`` does; the tests check they agree.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import torch
|
|
21
|
+
|
|
22
|
+
# Two independent polynomial hashes modulo 31-bit primes, packed as h1 << 31 | h2: no intermediate
|
|
23
|
+
# exceeds 2^62, so the torch version never relies on signed-overflow wraparound.
|
|
24
|
+
P1, P2 = 2147483647, 2147483629
|
|
25
|
+
A1, A2 = 1103515245, 69069
|
|
26
|
+
SEED, SEED_L = (12345, 54321), (271828, 314159)
|
|
27
|
+
MAX_LOOPS, MAX_CALLS = 8, 32
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def mix(h: tuple, x: int) -> tuple:
|
|
31
|
+
return ((h[0] * A1 + x % P1) % P1, (h[1] * A2 + x % P2) % P2)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def pack(h: tuple) -> int:
|
|
35
|
+
return (h[0] << 31) | h[1]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def readable(binary, pcs) -> list[tuple]:
|
|
39
|
+
"""Per tick: (call sites, ((loop head pc, iteration), ...), pc)."""
|
|
40
|
+
depth, calls, stack, out = 0, [], [], []
|
|
41
|
+
for pc in pcs:
|
|
42
|
+
pc = int(pc)
|
|
43
|
+
r = binary.row_of(pc)
|
|
44
|
+
while stack and stack[-1][2] == depth and not binary.inbody[stack[-1][0], r]:
|
|
45
|
+
stack.pop()
|
|
46
|
+
h = int(binary.head_row[r])
|
|
47
|
+
if h >= 0:
|
|
48
|
+
if stack and stack[-1][0] == h and stack[-1][2] == depth:
|
|
49
|
+
stack[-1][1] += 1
|
|
50
|
+
else:
|
|
51
|
+
stack.append([h, 0, depth])
|
|
52
|
+
out.append((tuple(calls), tuple((binary.loops[s[0]].head, s[1]) for s in stack), pc))
|
|
53
|
+
k = binary.kind[r]
|
|
54
|
+
if k == "call":
|
|
55
|
+
calls.append(pc)
|
|
56
|
+
depth += 1
|
|
57
|
+
elif k == "ret" and calls:
|
|
58
|
+
calls.pop()
|
|
59
|
+
depth -= 1
|
|
60
|
+
while stack and stack[-1][2] > depth:
|
|
61
|
+
stack.pop()
|
|
62
|
+
return out
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def key_of(binary, index: tuple) -> int:
|
|
66
|
+
calls, loops, pc = index
|
|
67
|
+
ch = SEED
|
|
68
|
+
for c in calls:
|
|
69
|
+
ch = mix(ch, c)
|
|
70
|
+
head_id = {lp.head: lp.id for lp in binary.loops}
|
|
71
|
+
lh = SEED_L
|
|
72
|
+
for head, it in loops:
|
|
73
|
+
lh = mix(mix(lh, head_id[head]), it)
|
|
74
|
+
return pack(mix(mix(mix(SEED, pc), pack(ch)), pack(lh)))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def text(index: tuple) -> str:
|
|
78
|
+
"""``0x401030@0x401005/L0x401010:3`` (pc @ call sites / loop head:iteration)."""
|
|
79
|
+
calls, loops, pc = index
|
|
80
|
+
parts = [f"{c:#x}" for c in calls] + [f"L{h:#x}:{i}" for h, i in loops]
|
|
81
|
+
return f"{pc:#x}" + ("@" + "/".join(parts) if parts else "")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _tmix(h, x):
|
|
85
|
+
x = x.remainder(P1), x.remainder(P2)
|
|
86
|
+
return (h[0] * A1 + x[0]).remainder(P1), (h[1] * A2 + x[1]).remainder(P2)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _tpack(h):
|
|
90
|
+
return (h[0] << 31) | h[1]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _full(B, v, dev):
|
|
94
|
+
return (torch.full((B,), v[0], dtype=torch.int64, device=dev), torch.full((B,), v[1], dtype=torch.int64, device=dev))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _where(c, a, b):
|
|
98
|
+
return torch.where(c, a[0], b[0]), torch.where(c, a[1], b[1])
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def keys(binary, pcs: torch.Tensor, valid: torch.Tensor) -> torch.Tensor:
|
|
102
|
+
"""Execution-index keys int64 [B, T] for pc rows [B, T] (``valid`` False -> key -1)."""
|
|
103
|
+
dev = pcs.device
|
|
104
|
+
B, T = pcs.shape
|
|
105
|
+
sorted_pcs = torch.tensor(binary.pcs, dtype=torch.int64, device=dev)
|
|
106
|
+
kind = torch.tensor([1 if k == "call" else 2 if k == "ret" else 0 for k in binary.kind], device=dev)
|
|
107
|
+
inbody = torch.tensor(binary.inbody, device=dev)
|
|
108
|
+
head = torch.tensor(binary.head_row, device=dev)
|
|
109
|
+
L = MAX_LOOPS
|
|
110
|
+
lid = torch.zeros(B, L, dtype=torch.int64, device=dev)
|
|
111
|
+
it = torch.zeros(B, L, dtype=torch.int64, device=dev)
|
|
112
|
+
ld = torch.zeros(B, L, dtype=torch.int64, device=dev)
|
|
113
|
+
lsp = torch.zeros(B, dtype=torch.int64, device=dev)
|
|
114
|
+
depth = torch.zeros(B, dtype=torch.int64, device=dev)
|
|
115
|
+
ch = _full(B, SEED, dev)
|
|
116
|
+
chs = torch.zeros(B, MAX_CALLS, dtype=torch.int64, device=dev) # packed call-string hashes
|
|
117
|
+
out = torch.full((B, T), -1, dtype=torch.int64, device=dev)
|
|
118
|
+
ar = torch.arange(L, device=dev)
|
|
119
|
+
overflow = torch.zeros(B, dtype=torch.bool, device=dev)
|
|
120
|
+
|
|
121
|
+
def top():
|
|
122
|
+
i = (lsp - 1).clamp(min=0)[:, None]
|
|
123
|
+
return i, lid.gather(1, i)[:, 0], ld.gather(1, i)[:, 0]
|
|
124
|
+
|
|
125
|
+
for t in range(T):
|
|
126
|
+
pc, v = pcs[:, t].contiguous(), valid[:, t]
|
|
127
|
+
j = torch.searchsorted(sorted_pcs, pc).clamp(max=len(binary.pcs) - 1)
|
|
128
|
+
r = torch.where(sorted_pcs[j] == pc, j + 1, 0)
|
|
129
|
+
for _ in range(L):
|
|
130
|
+
i, tl, td = top()
|
|
131
|
+
pop = v & (lsp > 0) & (td == depth) & ~inbody[tl, r]
|
|
132
|
+
if not bool(pop.any()):
|
|
133
|
+
break
|
|
134
|
+
lsp = lsp - pop.long()
|
|
135
|
+
h = head[r]
|
|
136
|
+
i, tl, td = top()
|
|
137
|
+
same = (lsp > 0) & (tl == h) & (td == depth)
|
|
138
|
+
inc = v & (h >= 0) & same
|
|
139
|
+
push = v & (h >= 0) & ~same
|
|
140
|
+
it = it + (inc[:, None] & (ar == i)).long()
|
|
141
|
+
overflow |= push & (lsp >= L)
|
|
142
|
+
at = (ar == lsp.clamp(max=L - 1)[:, None]) & push[:, None]
|
|
143
|
+
lid = torch.where(at, h[:, None], lid)
|
|
144
|
+
it = torch.where(at, 0, it)
|
|
145
|
+
ld = torch.where(at, depth[:, None], ld)
|
|
146
|
+
lsp = (lsp + push.long()).clamp(max=L)
|
|
147
|
+
lh = _full(B, SEED_L, dev)
|
|
148
|
+
for q in range(L):
|
|
149
|
+
if not bool((lsp > q).any()):
|
|
150
|
+
break
|
|
151
|
+
lh = _where(lsp > q, _tmix(_tmix(lh, lid[:, q]), it[:, q]), lh)
|
|
152
|
+
key = _tpack(_tmix(_tmix(_tmix(_full(B, SEED, dev), pc), _tpack(ch)), _tpack(lh)))
|
|
153
|
+
out[:, t] = torch.where(v, key, -1)
|
|
154
|
+
k = kind[r]
|
|
155
|
+
call, ret = v & (k == 1), v & (k == 2) & (depth > 0)
|
|
156
|
+
overflow |= call & (depth >= MAX_CALLS - 1)
|
|
157
|
+
slot = depth.clamp(max=MAX_CALLS - 1)[:, None]
|
|
158
|
+
chs = chs.scatter(1, slot, torch.where(call, _tpack(ch), chs.gather(1, slot)[:, 0])[:, None])
|
|
159
|
+
ch = _where(call, _tmix(ch, pc), ch)
|
|
160
|
+
depth = depth + call.long() - ret.long()
|
|
161
|
+
back = chs.gather(1, depth.clamp(max=MAX_CALLS - 1)[:, None])[:, 0]
|
|
162
|
+
ch = _where(ret, (back >> 31, back & P1), ch)
|
|
163
|
+
if bool(ret.any()):
|
|
164
|
+
for _ in range(L):
|
|
165
|
+
i, tl, td = top()
|
|
166
|
+
pop = ret & (lsp > 0) & (td > depth)
|
|
167
|
+
if not bool(pop.any()):
|
|
168
|
+
break
|
|
169
|
+
lsp = lsp - pop.long()
|
|
170
|
+
if bool(overflow.any()):
|
|
171
|
+
raise ValueError(f"loop nesting deeper than {MAX_LOOPS} or calls deeper than {MAX_CALLS} "
|
|
172
|
+
f"on {int(overflow.sum())} lanes")
|
|
173
|
+
return out
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def instances(pcs) -> list[int]:
|
|
177
|
+
"""Per tick: k such that this tick is the k-th (0-based) execution of its pc."""
|
|
178
|
+
seen: dict[int, int] = {}
|
|
179
|
+
out = []
|
|
180
|
+
for pc in pcs:
|
|
181
|
+
pc = int(pc)
|
|
182
|
+
out.append(seen.get(pc, 0))
|
|
183
|
+
seen[pc] = out[-1] + 1
|
|
184
|
+
return out
|