model-debugger 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
mdb/interop/tl.py ADDED
@@ -0,0 +1,149 @@
1
+ """TransformerLens (v4 ``TransformerBridge``) <-> mdb values.
2
+
3
+ - ``bridge(model, tokenizer)``: a bridge that wraps the SAME Hugging Face module mdb attaches to
4
+ (unprocessed: values are the native ones, bitwise; measured in ``tests/test_interop.py``).
5
+ - ``cache_values(cache, rows, ...)``: an ``ActivationCache`` (or any ``{hook: tensor}``) as mdb
6
+ occurrence values ``t<r>.L<l>.<port>`` for ``Debugger.import_values``.
7
+ - ``import_cache(dbg, name, cache, tokens)``: the same, registered as the origin ``name``.
8
+ - ``trace_cache(trace)``: an ``mdb.trace`` capture as ``{TL hook name: tensor}`` (and as a TL
9
+ ``ActivationCache`` when a bridge is given).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterable, Sequence
15
+ from typing import Any
16
+
17
+ from . import names
18
+ from .clone import shared_clone
19
+
20
+
21
+ def version() -> str:
22
+ from importlib.metadata import version as _v
23
+
24
+ return _v("transformer-lens")
25
+
26
+
27
+ def bridge(model: Any, tokenizer: Any, *, name: str | None = None,
28
+ in_place: bool = False) -> Any:
29
+ """``TransformerBridge.boot_transformers`` over ``model``'s weights, unprocessed.
30
+
31
+ By default the bridge wraps ``shared_clone(model)``: same tensors, separate module tree, so
32
+ mdb can stay attached to ``model``. ``in_place=True`` hands TL the module itself (TL then
33
+ rewrites its tree). Never call ``enable_compatibility_mode()`` on a bridge that shares
34
+ weights with a model in use: weight processing writes the shared parameters."""
35
+ from transformer_lens.model_bridge import TransformerBridge
36
+
37
+ param = next(model.parameters())
38
+ target = model if in_place else shared_clone(model)
39
+ return TransformerBridge.boot_transformers(
40
+ name or getattr(model.config, "_name_or_path", None) or "hf-model", hf_model=target,
41
+ tokenizer=tokenizer, device=param.device, dtype=param.dtype)
42
+
43
+
44
+ def _bridge_of(bridge_or_cache: Any) -> Any:
45
+ """The bridge behind a bridge or an ``ActivationCache`` (whose ``.model`` is the bridge).
46
+
47
+ Never ``getattr(bridge, "model")``: ``TransformerBridge.__getattr__`` falls through to the
48
+ wrapped Hugging Face module, so ``bridge.model`` is the HF ``Qwen3Model``, which has no
49
+ ``_weights_processed`` (the old ``processed()`` read it there and always said False)."""
50
+ if "_weights_processed" in getattr(bridge_or_cache, "__dict__", {}):
51
+ return bridge_or_cache
52
+ inner = getattr(bridge_or_cache, "__dict__", {}).get("model")
53
+ if inner is not None and "_weights_processed" in getattr(inner, "__dict__", {}):
54
+ return inner
55
+ return None
56
+
57
+
58
+ def processed(bridge_or_cache: Any) -> bool:
59
+ """True when TransformerLens weight processing ran on the bridge (``process_weights``, called
60
+ by ``enable_compatibility_mode()`` unless ``no_processing=True``). TL sets
61
+ ``self._weights_processed`` on the bridge itself (``bridge_core.py``, TL 4.4.0)."""
62
+ found = _bridge_of(bridge_or_cache)
63
+ return bool(found is not None and found.__dict__["_weights_processed"])
64
+
65
+
66
+ def processing(bridge_or_cache: Any) -> dict[str, Any]:
67
+ """What TL weight processing did to this bridge, as far as TL 4.4.0's own gates decide it
68
+ (``ProcessWeights.process_weights``, ``weight_processing.py``): ``fold_ln`` folds the norm
69
+ gains into the next linear layers for LN and RMS; centring of the writing weights (and the
70
+ centred-output value-bias fold) runs only for ``normalization_type`` LN/LNPre without
71
+ ``final_rms``, so on RMSNorm models (Qwen2/Qwen3, Llama) the residual stream is NOT centred.
72
+ Assumes the default flags of ``enable_compatibility_mode``; TL does not record the flags."""
73
+ found = _bridge_of(bridge_or_cache)
74
+ cfg = getattr(found, "cfg", None)
75
+ norm = getattr(cfg, "normalization_type", None)
76
+ final_rms = bool(getattr(cfg, "final_rms", False))
77
+ done = processed(bridge_or_cache)
78
+ return {"processed": done, "normalization_type": norm, "final_rms": final_rms,
79
+ "residual_centred": bool(done and norm in ("LN", "LNPre") and not final_rms),
80
+ "norm_gains_folded": bool(done and norm in ("LN", "LNPre", "RMS", "RMSPre"))}
81
+
82
+
83
+ def cache_values(cache: Any, rows: Iterable[int], *, layers: Iterable[int] | None = None,
84
+ ports: Sequence[str] | None = None, batch: int = 0) -> dict[str, Any]:
85
+ """``{t<r>.L<l>.<port>: tensor}`` from a TL cache (bridge-native names or aliases), one
86
+ batch element, mdb's single-row layout. Hooks with no mdb port are skipped."""
87
+ out: dict[str, Any] = {}
88
+ rows = list(rows)
89
+ keys = list(cache.keys()) if hasattr(cache, "keys") else list(cache)
90
+ for hook in keys:
91
+ try:
92
+ address = names.from_tl(hook)
93
+ except names.NoName:
94
+ continue
95
+ if "." not in address:
96
+ continue
97
+ layer, port = address[1:].split(".", 1)
98
+ layer = int(layer)
99
+ if layers is not None and layer not in set(layers):
100
+ continue
101
+ if ports is not None and port not in ports:
102
+ continue
103
+ spec = names.BY_PORT[port]
104
+ value = cache[hook][batch:batch + 1]
105
+ for row in rows:
106
+ key = f"t{row}.L{layer}.{port}"
107
+ if key not in out:
108
+ out[key] = names.to_mdb(spec.tl_layout, value, row).detach().clone()
109
+ return out
110
+
111
+
112
+ def import_cache(dbg: Any, name: str, cache: Any, tokens: Sequence[int], *,
113
+ rows: Iterable[int] | None = None, layers: Iterable[int] | None = None,
114
+ ports: Sequence[str] | None = None, batch: int = 0,
115
+ bridge_model: Any = None) -> Any:
116
+ """Register a TL cache as origin ``name`` of ``dbg`` (``Debugger.import_values``)."""
117
+ rows = range(len(tokens)) if rows is None else rows
118
+ values = cache_values(cache, rows, layers=layers, ports=ports, batch=batch)
119
+ state = processing(bridge_model if bridge_model is not None else cache)
120
+ if _bridge_of(bridge_model if bridge_model is not None else cache) is None:
121
+ # a plain {hook: tensor} dict carries no bridge: say so instead of claiming "unprocessed"
122
+ state["processed"] = None
123
+ provenance = {"tool": "transformer_lens", "version": version(), "processed": state["processed"],
124
+ "processing": state,
125
+ "program": "TransformerBridge full forward", "batch_index": batch}
126
+ return dbg.import_values(name, values, tokens=tokens, provenance=provenance)
127
+
128
+
129
+ def trace_cache(trace: Any, *, head_dim: int, call: int | None = None,
130
+ bridge_model: Any = None) -> Any:
131
+ """An ``mdb.trace`` capture as TL hook names (bridge-native), TL layouts. With
132
+ ``bridge_model`` the result is a ``transformer_lens.ActivationCache``."""
133
+ out: dict[str, Any] = {}
134
+ for address in trace.ports:
135
+ layer, port = names._split(address)
136
+ if layer is None or port not in names.BY_PORT:
137
+ continue
138
+ spec = names.BY_PORT[port]
139
+ if spec.tl is None:
140
+ continue
141
+ if trace.info(address, call)["state"] != "resolved":
142
+ continue
143
+ value = trace[address] if call is None else trace[address, call]
144
+ out[spec.tl.format(l=layer)] = names.to_tool(spec.tl_layout, value, head_dim=head_dim)
145
+ if bridge_model is None:
146
+ return out
147
+ from transformer_lens import ActivationCache
148
+
149
+ return ActivationCache(out, bridge_model)
mdb/interop/verify.py ADDED
@@ -0,0 +1,85 @@
1
+ """Re-measure another tool's claim natively in mdb.
2
+
3
+ A claim is an edit in mdb's language (what the other tool did, translated through
4
+ ``mdb.interop.names``), a consumer margin and the change the tool reported. ``verify`` runs
5
+ mdb's ``whatif`` for it (sealed prediction first, then the native batch-1 stepped measurement,
6
+ then the P20 verdict) and sets the claim beside it. The claim is ``supplied``; mdb's numbers
7
+ keep their own labels.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Sequence
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+
16
+
17
+ @dataclass
18
+ class Claim:
19
+ target: str # mdb address of the edit, e.g. "L22.A[h6]" or "cache.L22.v[kv1,row=11]"
20
+ value: Any # a number or "ORIGIN:ADDR" (an import or a named run)
21
+ op: str = "replace"
22
+ consumer: str = "" # "M[a,b]"
23
+ claimed: float | None = None
24
+ tool: str = ""
25
+ note: str = ""
26
+ extra: dict[str, Any] = field(default_factory=dict)
27
+
28
+
29
+ def _num(entry: Any) -> float | None:
30
+ if isinstance(entry, dict):
31
+ entry = entry.get("value", entry.get("v"))
32
+ try:
33
+ return None if entry is None else float(entry)
34
+ except (TypeError, ValueError):
35
+ return None
36
+
37
+
38
+ def summarise(report: dict[str, Any]) -> dict[str, Any]:
39
+ """The numbers of a ``whatif`` report that a comparison needs."""
40
+ prediction = report.get("prediction") or {}
41
+ measured = report.get("measured") or {}
42
+ effect = report.get("effect") or {}
43
+
44
+ def inner(entry: Any) -> float | None:
45
+ return _num(entry.get("value") if isinstance(entry, dict) and "value" in entry
46
+ and isinstance(entry["value"], dict) else entry)
47
+
48
+ return {
49
+ "linear": inner(prediction.get("linear")),
50
+ "exact": inner(prediction.get("exact")),
51
+ "native": _num(measured.get("delta")),
52
+ "base": _num(measured.get("base")),
53
+ "edited": _num(measured.get("edited")),
54
+ "verdict": effect.get("verdict"),
55
+ "floor": _num(effect.get("floor")),
56
+ }
57
+
58
+
59
+ def verify(dbg: Any, run: Any, claims: Sequence[Claim]) -> list[dict[str, Any]]:
60
+ """mdb's ``whatif`` for each claim on ``run`` (left where it was); one row per claim:
61
+ the claim (``supplied``), mdb's sealed linear/exact predictions, the native change, the
62
+ verdict and ``claim_minus_native``."""
63
+ from mdb.ops import dispatch
64
+ from mdb.ops.errors import OpError
65
+
66
+ ctx = dbg.ops(run)
67
+ rows = []
68
+ for claim in claims:
69
+ row: dict[str, Any] = {"target": claim.target, "value": claim.value, "op": claim.op,
70
+ "consumer": claim.consumer, "tool": claim.tool,
71
+ "claimed": claim.claimed, "claimed_authority": "supplied",
72
+ "note": claim.note, **claim.extra}
73
+ try:
74
+ report = dispatch(ctx, "whatif", {"target": claim.target, "value": claim.value,
75
+ "op": claim.op, "consumer": claim.consumer})
76
+ except OpError as error:
77
+ row.update(state="refused", reason=str(error))
78
+ rows.append(row)
79
+ continue
80
+ found = summarise(report)
81
+ row.update(found, state="resolved", report=report)
82
+ if claim.claimed is not None and found["native"] is not None:
83
+ row["claim_minus_native"] = claim.claimed - found["native"]
84
+ rows.append(row)
85
+ return rows
@@ -0,0 +1,53 @@
1
+ """Machine backends beside the decoder engine: programs that are not Hugging Face decoders.
2
+
3
+ The decoder engine (``mdb.engine``, ``ports.FAMILIES``) is specialised to transformer families and
4
+ stays that way. A machine here is an *addressed step machine*: sites
5
+ holding values, ops with typed read and write sets, a schedule, and a hierarchy of clock domains.
6
+ ``Program`` is the small protocol every backend implements; the verbs are defined once over it.
7
+
8
+ Backends: ``mdb.machines.x86`` (an x86-64 binary executed by torchx86, batched lanes).
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from typing import Any, Callable, Protocol
14
+
15
+ # verdicts a patch on a machine can end in (beside the engine's effect / no effect)
16
+ EFFECT, NO_EFFECT = "effect", "no effect"
17
+ PATH_DIVERGED, FAULT, NONTERMINATING = "path-diverged", "fault", "nonterminating"
18
+ VERDICTS = (EFFECT, NO_EFFECT, PATH_DIVERGED, FAULT, NONTERMINATING)
19
+ EDGE_TYPES = ("data", "addr", "ctrl")
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class ClockDomain:
24
+ """A unit for step / next / reverse-step: ``boundary(tick)`` is True when the tick ends a unit.
25
+ ``over`` names the coarser domain it nests in."""
26
+ name: str
27
+ boundary: Callable[[Any], bool]
28
+ over: str | None = None
29
+
30
+
31
+ class Program(Protocol):
32
+ """What a machine exposes to mdb's verbs.
33
+
34
+ sites() every addressable site (register bytes, flag bits, touched memory bytes)
35
+ step(n, unit) advance n units of a clock domain; next / reverse_step likewise
36
+ snapshot/restore the whole machine state, for checkpoints and forks
37
+ poke(site, value) the ``set`` primitive at the cursor
38
+ reads_of(t) typed read set of tick t: [(site, bits, edge)] with edge in EDGE_TYPES
39
+ writes_of(t) write set of tick t: [(site, role, value)]
40
+ domains()/define() the clock ladder, finest last, and user-defined domains
41
+ """
42
+
43
+ def sites(self) -> list[int]: ...
44
+ def step(self, n: int = 1, unit: str = "instruction") -> Any: ...
45
+ def next(self, n: int = 1, unit: str = "instruction") -> Any: ...
46
+ def reverse_step(self, n: int = 1, unit: str = "instruction") -> Any: ...
47
+ def snapshot(self) -> Any: ...
48
+ def restore(self, snap: Any) -> None: ...
49
+ def poke(self, site: Any, value: int) -> None: ...
50
+ def reads_of(self, t: int) -> list: ...
51
+ def writes_of(self, t: int) -> list: ...
52
+ def domains(self) -> list[ClockDomain]: ...
53
+ def define(self, domain: ClockDomain) -> None: ...
@@ -0,0 +1,13 @@
1
+ """x86-64 binaries as an mdb machine, executed by torchx86 in batched lanes (see ``binary``).
2
+
3
+ ``attach(program_dir, input)`` opens a debugger session (``session.BinRun``) with every verb."""
4
+ from .binary import Binary, torchx86
5
+
6
+
7
+ def attach(*args, **kwargs):
8
+ from .session import attach as _attach # noqa: PLC0415 (torch only when used)
9
+
10
+ return _attach(*args, **kwargs)
11
+
12
+
13
+ __all__ = ["Binary", "attach", "torchx86"]
@@ -0,0 +1,171 @@
1
+ """Address grammar for binaries (proposal §2), a sibling of mdb's decoder grammar (``core.address``).
2
+
3
+ ::
4
+
5
+ [origin:] TICK . SITE
6
+ TICK := i<t> state after tick t (instruction index, from 0)
7
+ | init the initial state (after input injection)
8
+ | <pc>#<k> after the k-th (0-based) execution of pc
9
+ | <pc>@<calls>/L<head>:<i> after the instance with this execution index
10
+ (``index.text``: call sites, then loop head:iteration)
11
+ SITE := <reg>[[lo:hi]] GPR bit range (rax, eax, al, ah, r8d, ...); default the whole register
12
+ | flags.<F> CF PF AF ZF SF OF
13
+ | mem[<expr>:<n>] n bytes at expr; expr = int | reg(+|-)disp, evaluated at the tick
14
+
15
+ ``origin`` names another run (a fork, a donor) or ``bin`` for the current binary. Examples:
16
+ ``i1042.rax[0:8]``, ``i1042.flags.CF``, ``i1042.mem[0x601040:8]``, ``0x401020#3.mem[rbp-0x10:8]``,
17
+ ``donor:0x40103e@0x401007/L0x401028:2.rdx``.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from dataclasses import dataclass
23
+
24
+ from .binary import FLAG0, FLAGS, GPRS
25
+
26
+ _SUB = {}
27
+ for _i, _r in enumerate(GPRS):
28
+ _SUB[_r] = (_i, 0, 64)
29
+ if _i < 8:
30
+ _SUB["e" + _r[1:]] = (_i, 0, 32)
31
+ _SUB[_r[1:]] = (_i, 0, 16)
32
+ _SUB[{"rax": "al", "rcx": "cl", "rdx": "dl", "rbx": "bl", "rsp": "spl", "rbp": "bpl", "rsi": "sil",
33
+ "rdi": "dil"}[_r]] = (_i, 0, 8)
34
+ if _i < 4:
35
+ _SUB[_r[1] + "h"] = (_i, 8, 16)
36
+ else:
37
+ _SUB.update({_r + "d": (_i, 0, 32), _r + "w": (_i, 0, 16), _r + "b": (_i, 0, 8)})
38
+ REGS = _SUB
39
+
40
+ _ORIGIN = re.compile(r"^([A-Za-z_][\w\-]*):")
41
+ _TICK = re.compile(r"^(?:i(?P<t>\d+)|(?P<init>init)|(?P<pc>0x[0-9a-fA-F]+)(?:#(?P<k>\d+)|@(?P<ctx>[0-9a-fA-FxL:/]+)))\.")
42
+ _REG = re.compile(r"^(?P<reg>[a-z][a-z0-9]*)(?:\[(?P<lo>\d+):(?P<hi>\d+)\])?$")
43
+ _MEM = re.compile(r"^mem\[(?P<expr>[^:\]]+):(?P<n>\d+)\]$")
44
+ _EXPR = re.compile(r"^(?:(?P<reg>[a-z][a-z0-9]*)(?:(?P<sign>[+-])(?P<d>0x[0-9a-fA-F]+|\d+))?|(?P<abs>0x[0-9a-fA-F]+|\d+))$")
45
+
46
+
47
+ class AddressError(ValueError):
48
+ pass
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Addr:
53
+ origin: str | None
54
+ tick: tuple # ("step", t) | ("init",) | ("inst", pc, k) | ("exec", pc, calls, loops)
55
+ site: tuple # ("reg", r, lo, hi) | ("flag", f) | ("mem", expr, n); expr = (reg|None, disp)
56
+
57
+ def text(self) -> str:
58
+ kind = self.tick[0]
59
+ t = {"step": lambda: f"i{self.tick[1]}", "init": lambda: "init",
60
+ "inst": lambda: f"{self.tick[1]:#x}#{self.tick[2]}"}.get(kind)
61
+ tick = t() if t else _exec_text(self.tick)
62
+ s = self.site
63
+ if s[0] == "reg":
64
+ site = f"{GPRS[s[1]]}[{s[2]}:{s[3]}]"
65
+ elif s[0] == "flag":
66
+ site = f"flags.{FLAGS[s[1]]}"
67
+ else:
68
+ reg, d = s[1]
69
+ e = f"{reg}{'-' if d < 0 else '+'}{abs(d):#x}" if reg else f"{d:#x}"
70
+ site = f"mem[{e}:{s[2]}]"
71
+ return (f"{self.origin}:" if self.origin else "") + f"{tick}.{site}"
72
+
73
+
74
+ def _exec_text(tick) -> str:
75
+ _, pc, calls, loops = tick
76
+ parts = [f"{c:#x}" for c in calls] + [f"L{h:#x}:{i}" for h, i in loops]
77
+ return f"{pc:#x}@" + "/".join(parts)
78
+
79
+
80
+ def parse(text: str) -> Addr:
81
+ s = text.strip()
82
+ origin = None
83
+ m = _ORIGIN.match(s)
84
+ if m:
85
+ origin, s = m.group(1), s[m.end():]
86
+ m = _TICK.match(s)
87
+ if not m:
88
+ raise AddressError(f"{text!r}: expected i<t>., init., <pc>#<k>. or <pc>@<index>. before the site")
89
+ if m.group("t") is not None:
90
+ tick = ("step", int(m.group("t")))
91
+ elif m.group("init"):
92
+ tick = ("init",)
93
+ elif m.group("k") is not None:
94
+ tick = ("inst", int(m.group("pc"), 16), int(m.group("k")))
95
+ else:
96
+ calls, loops = [], []
97
+ for part in m.group("ctx").split("/"):
98
+ if part.startswith("L"):
99
+ h, _, i = part[1:].partition(":")
100
+ loops.append((int(h, 16), int(i)))
101
+ elif part:
102
+ calls.append(int(part, 16))
103
+ tick = ("exec", int(m.group("pc"), 16), tuple(calls), tuple(loops))
104
+ return Addr(origin, tick, parse_site(s[m.end():], text))
105
+
106
+
107
+ def parse_site(s: str, text: str | None = None) -> tuple:
108
+ text = text or s
109
+ if s.startswith("flags."):
110
+ f = s[6:]
111
+ if f not in FLAGS:
112
+ raise AddressError(f"{text!r}: flag must be one of {FLAGS}")
113
+ return ("flag", FLAGS.index(f))
114
+ m = _MEM.match(s)
115
+ if m:
116
+ e = _EXPR.match(m.group("expr").replace(" ", ""))
117
+ if not e:
118
+ raise AddressError(f"{text!r}: memory expression is int or reg+-disp")
119
+ if e.group("abs"):
120
+ expr = (None, int(e.group("abs"), 0))
121
+ else:
122
+ if e.group("reg") not in GPRS:
123
+ raise AddressError(f"{text!r}: base register must be a 64-bit GPR")
124
+ d = int(e.group("d"), 0) if e.group("d") else 0
125
+ expr = (e.group("reg"), -d if e.group("sign") == "-" else d)
126
+ return ("mem", expr, int(m.group("n")))
127
+ m = _REG.match(s)
128
+ if m and m.group("reg") in REGS:
129
+ r, lo, hi = REGS[m.group("reg")]
130
+ if m.group("lo") is not None:
131
+ a, b = int(m.group("lo")), int(m.group("hi"))
132
+ if not 0 <= a < b <= hi - lo:
133
+ raise AddressError(f"{text!r}: bit range outside the register")
134
+ lo, hi = lo + a, lo + b
135
+ return ("reg", r, lo, hi)
136
+ raise AddressError(f"{text!r}: unknown site {s!r}")
137
+
138
+
139
+ def resolve_tick(addr: Addr, trace) -> int:
140
+ """The tick index of ``addr`` in ``trace`` (-1 for ``init``)."""
141
+ kind = addr.tick[0]
142
+ if kind == "init":
143
+ return -1
144
+ if kind == "step":
145
+ t = addr.tick[1]
146
+ if not 0 <= t < trace.T:
147
+ raise AddressError(f"tick {t} outside the run (T={trace.T})")
148
+ return t
149
+ for tk in trace.ticks:
150
+ if kind == "inst" and tk.pc == addr.tick[1] and tk.k == addr.tick[2]:
151
+ return tk.t
152
+ if kind == "exec" and tk.index == (addr.tick[2], addr.tick[3], addr.tick[1]):
153
+ return tk.t
154
+ raise AddressError(f"{addr.text()}: no such instance in this run")
155
+
156
+
157
+ def sites(addr: Addr, trace, t: int) -> tuple[list[int], int, int]:
158
+ """(byte/flag sites, low bit inside the first site, number of bits) of addr's site at tick t."""
159
+ s = addr.site
160
+ if s[0] == "flag":
161
+ return [FLAG0 + s[1]], 0, 1
162
+ if s[0] == "reg":
163
+ r, lo, hi = s[1:]
164
+ return [8 * r + b for b in range(lo // 8, (hi + 7) // 8)], lo % 8, hi - lo
165
+ reg, d = s[1]
166
+ base = trace.reg(t, GPRS.index(reg)) if reg else 0
167
+ a = (base + d) & ((1 << 64) - 1)
168
+ return list(range(a, a + s[2])), 0, 8 * s[2]
169
+
170
+
171
+ __all__ = ["Addr", "AddressError", "parse", "parse_site", "resolve_tick", "sites", "REGS"]