model-debugger 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
@@ -0,0 +1,374 @@
1
+ """Sparse-autoencoder feature bases on residual ports, with the error term always explicit.
2
+
3
+ A ``FeatureBasis`` is one SAE bound to one residual site of the port program: the output of
4
+ decoder layer ``L`` (``L<L>.h_out``; the same value is ``L<L+1>.h`` when no edit sits between
5
+ them). Qwen-Scope's ``hook_point: resid_post`` is that site. For a native value ``x`` at the
6
+ site the basis gives the exact identity
7
+
8
+ x = b_dec + sum_{f in S} a_f d_f + e
9
+
10
+ where ``S`` is the set of active features (top-k of ``relu(W_enc x + b_enc)``, the published
11
+ selection rule, computed in float32 exactly as the published encoder does: Qwen-Scope's
12
+ ``app.py`` ``topk_relu`` and SAELens ``TopK`` (top-k, then ReLU) give the same nonzero set; the
13
+ model-card snippet omits the ReLU; no ``b_dec`` is subtracted from the input and no input
14
+ normalisation is applied, as in SAELens's ``qwen_scope`` loader), ``a_f`` the
15
+ activations recomputed in float64 from the native bits (rows of ``W_enc`` sliced before the
16
+ cast), ``d_f = W_dec[:, f]`` the decoder directions (columns sliced before the cast) and
17
+ ``e = x - b_dec - sum a_f d_f`` the error, defined as the remainder so the identity closes to
18
+ float64 roundoff by construction. The error is a listed term everywhere: never dropped.
19
+
20
+ Direct effects on a margin ``M[a,b]``: the residual at the site reaches the final state through
21
+ the skip path unchanged, so ``M = rho c.x + sum_{l>L} rho c.(o_l + m_l) + gaps`` with ``rho c``
22
+ the readout of ``reads.readout`` (P19). Splitting ``rho c.x`` over the identity above gives each
23
+ feature's, the bias's and the error's direct share; the rest of the margin is the later layers'
24
+ terms and the measured remainder. ``margin_split`` returns all of it with the closure.
25
+
26
+ Labels: the native value is ``measured``; activations, directions, reconstruction, error and
27
+ direct effects are ``derived-exact`` (float64 identities over the native value and the SAE's
28
+ stored float32 weights, which are ``supplied``); logit-lens token lists are ``derived-local``
29
+ (float32 ranking only, never a decomposition).
30
+
31
+ Memory: weights stay in their stored float32 on the host; nothing is cast whole. A set of
32
+ layers (``SaeSet``) loads one layer file when it is first used and keeps at most ``cache``
33
+ layers loaded (least recently used dropped).
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import math
39
+ import re
40
+ from collections.abc import Sequence
41
+ from typing import Any
42
+
43
+ from ..numerics.labels import EXACT, LOCAL, MEASURED, SUPPLIED, f64
44
+ from .basis import Decomposition, FeatureBasis, SaeError, _torch
45
+
46
+ SCHEMA = "mdb-sae-v1"
47
+
48
+
49
+ # --------------------------------------------------------------------------- sets of layers
50
+
51
+
52
+
53
+
54
+ # --------------------------------------------------------------------------- analysis
55
+
56
+
57
+ def margin_split(run: Any, reader: Any, basis: FeatureBasis, layer: int, port: str,
58
+ dec: Decomposition | None = None) -> dict[str, Any]:
59
+ """Exact split of a scalar consumer (margin or logit of ``reader.row``) at the site value
60
+ ``L<layer>.<port>`` of that row.
61
+
62
+ ``consumer = rho c.x + sum over later residual terms + remainder``; ``rho c.x`` is split
63
+ over ``b_dec``, every active feature and the error. Returns float64 numbers (``direct``,
64
+ ``features`` (id, act, effect), ``bias``, ``error``, ``downstream`` list of
65
+ ``(name, address, value)``, ``remainder``, ``native``) — the caller labels them."""
66
+ torch = _torch()
67
+ row = reader.row
68
+ address = f"t{row}.L{layer}.{port}"
69
+ x = run.read(address)
70
+ dec = dec or basis.decompose(x)
71
+ w = reader.vector
72
+ direct = float(w @ dec.x)
73
+ effects = (w @ dec.D) * dec.acts # per feature, float64
74
+ bias = float(w @ dec.bias)
75
+ error = float(w @ dec.error)
76
+ last = run.adapter.layers - 1
77
+ downstream = []
78
+ first = layer + 1 if port == "h_out" else layer
79
+ for l in range(first, last + 1):
80
+ for part, name in (("o", "attn"), ("m", "mlp")):
81
+ value = float(reader.apply(run.read(f"t{row}.L{l}.{part}")))
82
+ downstream.append((f"L{l}.{name}", f"t{row}.L{l}.{part}", value))
83
+ native = float(reader.native)
84
+ listed = direct + sum(v for _, _, v in downstream) + float(reader.bias)
85
+ remainder = native - listed
86
+ return {"address": address, "decomposition": dec, "direct": direct,
87
+ "features": [(int(i), float(a), float(e))
88
+ for i, a, e in zip(dec.ids, dec.acts.tolist(), effects.tolist())],
89
+ "bias": bias, "error": error, "downstream": downstream,
90
+ "head_bias": float(reader.bias), "remainder": remainder, "native": native,
91
+ "identity_gap": direct - (bias + error + float(effects.sum())),
92
+ "torch": torch.__version__}
93
+
94
+
95
+ def edit_vector(basis: FeatureBasis, terms: Sequence[tuple], values: Any) -> Any:
96
+ """``sum_t scale_t * vector_t`` in float64. A term is ``(kind, feature, coef, scale,
97
+ origin)``: ``feature`` (``d_f``; with ``coef`` times the feature's float64 activation at the
98
+ site's value), ``error`` (``e``), ``recon`` (``b_dec + D a``) or ``bias`` (``b_dec``).
99
+ ``values`` maps an origin (None: this run) to the site's value there (a bare tensor stands
100
+ for ``{None: tensor}``); terms that need no value ignore it."""
101
+ torch = _torch()
102
+ if not isinstance(values, dict):
103
+ values = {None: values}
104
+ total = torch.zeros(basis.d_model, dtype=torch.float64)
105
+ decs: dict[Any, Decomposition] = {}
106
+ for term in terms:
107
+ kind, feature, coef, scale = term[:4]
108
+ origin = term[4] if len(term) > 4 else None
109
+ needs = kind in ("error", "recon") or coef
110
+ if needs and origin not in decs:
111
+ if values.get(origin) is None:
112
+ where = f"@{origin}" if origin else ""
113
+ raise SaeError(f"{kind}{where}{'(coef)' if coef else ''} needs the value at the "
114
+ "site")
115
+ decs[origin] = basis.decompose(values[origin])
116
+ dec = decs.get(origin)
117
+ if kind == "feature":
118
+ vector = basis.direction(feature)
119
+ if coef:
120
+ acts = dict(zip(dec.ids, dec.acts.tolist()))
121
+ vector = vector * float(acts.get(int(feature), 0.0))
122
+ elif kind == "error":
123
+ vector = dec.error
124
+ elif kind == "recon":
125
+ vector = dec.recon
126
+ elif kind == "bias":
127
+ vector = basis.bias()
128
+ else:
129
+ raise SaeError(f"unknown feature term {kind!r}")
130
+ total = total + float(scale) * vector
131
+ return total
132
+
133
+
134
+ _TERM = re.compile(
135
+ r"(?P<sign>[+-]?)(?:(?P<pre>[0-9.eE+-]+)\*)?"
136
+ r"(?:(?P<feat>feature)\[(?P<id>\d+)(?P<coef>,coef)?\]|(?P<word>error|recon|bias))"
137
+ r"(?:@(?P<origin>[A-Za-z_]\w*))?"
138
+ r"(?:\*(?P<post>[-+]?[0-9.]+(?:[eE][-+]?\d+)?))?")
139
+
140
+
141
+ def parse_terms(text: str) -> list[tuple]:
142
+ """``feature[ID]``, ``feature[ID,coef]``, ``error``, ``recon``, ``bias``, each optionally
143
+ ``@RUN`` (the value at the same address of the named run) and scaled ``X*`` / ``*X``,
144
+ joined by ``+`` or ``-``; no spaces, never evaluated. ``feature[12,coef]*-1`` is minus the
145
+ feature's own contribution ``a_12 d_12``; ``recon@rome-recon`` swaps in the other run's
146
+ reconstruction and keeps this run's error."""
147
+ text = text.strip()
148
+ terms, at = [], 0
149
+ while at < len(text):
150
+ match = _TERM.match(text, at)
151
+ if match is None or match.end() == at:
152
+ raise SaeError(f"cannot read feature term at {text[at:]!r}: write feature[ID], "
153
+ "feature[ID,coef], error, recon or bias, [@RUN], with *X, joined by "
154
+ "+ or -")
155
+ scale = 1.0
156
+ for key in ("pre", "post"):
157
+ if match[key]:
158
+ try:
159
+ scale *= float(match[key])
160
+ except ValueError:
161
+ raise SaeError(f"bad scale {match[key]!r}") from None
162
+ if match["sign"] == "-":
163
+ scale = -scale
164
+ if not math.isfinite(scale):
165
+ raise SaeError("a feature scale must be finite")
166
+ kind = "feature" if match["feat"] else match["word"]
167
+ if kind == "bias" and match["origin"]:
168
+ raise SaeError("bias@RUN is the same b_dec: drop @RUN")
169
+ terms.append((kind, int(match["id"]) if match["id"] else None, bool(match["coef"]),
170
+ scale, match["origin"]))
171
+ at = match.end()
172
+ if not terms:
173
+ raise SaeError("empty feature expression")
174
+ return terms
175
+
176
+
177
+ def is_expression(value: Any) -> bool:
178
+ return isinstance(value, str) and bool(re.match(r"[+-]?([0-9.eE+-]+\*)?"
179
+ r"(feature\[|error\b|recon\b|bias\b)",
180
+ value.strip()))
181
+
182
+
183
+ def circuit(run: Any, reader: Any, split: dict[str, Any], basis: FeatureBasis, *, top: int = 4,
184
+ session_id: str | None = None) -> Any:
185
+ """A circuit record (kind ``circuit``, ``circuits.ledger``) of a scalar consumer with the
186
+ site's residual expanded over the SAE: consumer -> [site residual -> features (top, ``+N
187
+ more``), SAE bias, SAE error], the later layers' attn/mlp terms (top, ``+N more``), the
188
+ head bias and the measured remainder. The error node is fixed: never folded or dropped."""
189
+ from mdb.core.pointers import RecordError, check_bounded
190
+ from mdb.core.records import num, seal_record
191
+
192
+ from ..circuits import build as C
193
+ from ..measure.readout import claim, size
194
+ from ..predict.consumers import Refusal, run_session_id
195
+
196
+ if not 1 <= top <= 8:
197
+ raise Refusal("top must be in 1..8")
198
+ address = split["address"]
199
+ feats = [C.Node(f"f{i}", "feature", f"{address}{{sae={basis.name},feature={i}}}",
200
+ _scalar(e), EXACT, "P19",
201
+ note=f"a_f {a:.6g} x rho c.d_f (SAE {basis.name} L{basis.layer})")
202
+ for i, a, e in split["features"]]
203
+ children = C._group(feats, top, f"{address} features")
204
+ children.append(C.Node("sae bias", "bias", f"{address}{{sae={basis.name},b_dec}}",
205
+ _scalar(split["bias"]), EXACT, "P19", note="rho c.b_dec"))
206
+ children.append(C.Node("sae error", "error", f"{address}{{sae={basis.name},error}}",
207
+ _scalar(split["error"]), EXACT, "P19",
208
+ note="rho c.(native - reconstruction): what the SAE drops"))
209
+ site = C.Node(f"{address.split('.', 1)[1]} via SAE", "residual", address,
210
+ _scalar(split["direct"]), EXACT, "P19", children=children,
211
+ note="the site's residual on the skip path: rho c.x")
212
+ later = [C.Node(name, "attn" if name.endswith("attn") else "mlp", addr, _scalar(v), EXACT,
213
+ "P19", port=addr, index=()) for name, addr, v in split["downstream"]]
214
+ nodes = [site] + C._group(later, top, f"after {address}")
215
+ if split["head_bias"]:
216
+ nodes.append(C.Node("head bias", "bias", "lm_head.bias", _scalar(split["head_bias"]),
217
+ EXACT, "P19"))
218
+ nodes.append(C._remainder("remainder", reader.text, _scalar(split["remainder"]),
219
+ "native consumer minus the listed terms: rounding of the residual "
220
+ "adds after the site, final norm and head (not bounded here; "
221
+ "explain bounds them)"))
222
+ native = _scalar(split["native"])
223
+ root = C.Node(reader.text, "consumer", reader.text, native,
224
+ reader.native_authority or MEASURED, children=nodes)
225
+ total = sum((n.value for n in nodes[1:]), nodes[0].value)
226
+ closure = native - total
227
+ scale = sum(size(n.value) for n in nodes) + size(native)
228
+ entries = C.ledger(run)
229
+ ident = max(entries, default=0) + 1
230
+ ids = [0]
231
+ tree = root.view(ids)
232
+ body = {"schema": C.SCHEMA, "consumer": reader.text, "kind": reader.kind,
233
+ "where": run.where, "k": top, "depth": 1, "count": ids[0], "root": tree,
234
+ "sae": {"name": basis.name, "site": address,
235
+ "revision": basis.source.get("revision"),
236
+ "file_sha256": basis.source.get("sha256")
237
+ or basis.source.get("sha256_manifest")},
238
+ "closure": {"value": claim(closure, EXACT, "P19"),
239
+ "bound": num(float(64 * 2.0 ** -53 * scale), "bound"),
240
+ "within": bool(size(closure) <= 64 * 2.0 ** -53 * scale),
241
+ "by_construction": True,
242
+ "meaning": "native consumer minus the sum of the depth-1 nodes (float64 "
243
+ "summation only); the SAE identity closes by defining the "
244
+ "error as native minus reconstruction"},
245
+ "remainders_within": None,
246
+ "edits": {"count": 0, "meaning": "edit displacements stay inside the terms that "
247
+ "carry them in an SAE circuit"},
248
+ "premises": list(reader.premises)}
249
+ try:
250
+ check_bounded(body, "circuit record")
251
+ record = seal_record(session_id=session_id or run_session_id(run), kind="circuit",
252
+ model_identity=run.adapter.model_identity,
253
+ execution=dict(run.adapter.execution), authority=EXACT, body=body, run=run)
254
+ except RecordError as error:
255
+ raise Refusal(f"the SAE circuit record does not fit one record ({error})") from None
256
+ built = C.Circuit(ident, record, root, reader.target, run.where, complement=None)
257
+ entries[ident] = built
258
+ return built
259
+
260
+
261
+ def _scalar(value: float) -> Any:
262
+ return _torch().tensor(float(value), dtype=_torch().float64)
263
+
264
+
265
+ def unit_vector(run: Any, row: int, text: str) -> tuple[Any, str]:
266
+ """The residual-stream write of one mdb unit, float64: ``L<l>.f[i=N]`` the neuron's
267
+ ``W_down[:, N]`` (a weight column: per unit of ``f``), ``L<l>.A[hH]`` head ``H``'s write
268
+ ``W_o,h A_h`` at ``row``, ``L<l>.A[hH,src=S]`` the part of it read from source row ``S``
269
+ (``p[h,S] W_o,h v[kappa(h),S]``, P06/P07). Returns ``(vector, meaning)``."""
270
+ from ..measure.readout import head_mix, layer_module
271
+
272
+ torch = _torch()
273
+ match = re.fullmatch(r"L(?P<l>\d+)\.(?:f\[i=(?P<i>\d+)\]|A\[h(?P<h>\d+)(?:,src=(?P<s>\d+))?\])",
274
+ text.strip())
275
+ if match is None:
276
+ raise SaeError(f"match= takes L<l>.f[i=N], L<l>.A[hH] or L<l>.A[hH,src=S], not {text!r}")
277
+ layer = int(match["l"])
278
+ if not 0 <= layer < run.adapter.layers:
279
+ raise SaeError(f"no layer {layer}")
280
+ module = layer_module(run.adapter, layer)
281
+ if match["i"] is not None:
282
+ weight = module.mlp.down_proj.weight
283
+ i = int(match["i"])
284
+ if not 0 <= i < int(weight.shape[1]):
285
+ raise SaeError(f"neuron {i} is outside 0..{int(weight.shape[1]) - 1}")
286
+ return weight[:, i].detach().to("cpu").to(torch.float64), \
287
+ f"W_down[:, {i}] of L{layer} (the write per unit of f[i={i}])"
288
+ mix = head_mix(run, row, layer)
289
+ h = int(match["h"])
290
+ if not 0 <= h < int(mix.p.shape[0]):
291
+ raise SaeError(f"head {h} is outside 0..{int(mix.p.shape[0]) - 1}")
292
+ if match["s"] is None:
293
+ return mix.o_parts()[h].sum(dim=0).to("cpu"), f"W_o,h{h} A_h{h} of L{layer} at t{row}"
294
+ s = int(match["s"])
295
+ if not 0 <= s < int(mix.p.shape[1]):
296
+ raise SaeError(f"source {s} is outside 0..{int(mix.p.shape[1]) - 1}")
297
+ return mix.o_parts()[h, s].to("cpu"), \
298
+ f"p[h{h},{s}] W_o,h{h} v[kv{mix.kappa[h]},{s}] of L{layer} at t{row}"
299
+
300
+
301
+ def match_unit(basis: FeatureBasis, vector: Any, top: int = 8) -> dict[str, Any]:
302
+ """Decoder directions closest to ``vector``: float32 cosine ranking over all features, then
303
+ float64 cosines of the top ones (columns sliced, then cast) and the fraction of ``vector``
304
+ left outside their span (least squares, float64)."""
305
+ torch = _torch()
306
+ v = f64(vector).reshape(-1)
307
+ v32 = v.to(torch.float32)
308
+ norms = basis.W_dec.norm(dim=0)
309
+ cos32 = (v32 @ basis.W_dec) / (norms * v32.norm()).clamp_min(1e-30)
310
+ order = torch.topk(cos32.abs(), top).indices.tolist()
311
+ D = basis.directions(order) # (d, top) float64
312
+ cos = (v @ D) / (D.norm(dim=0) * v.norm())
313
+ coef = torch.linalg.lstsq(D, v.unsqueeze(1)).solution.reshape(-1)
314
+ residual = v - D @ coef
315
+ return {"ids": [int(i) for i in order], "cos": cos.tolist(), "coef": coef.tolist(),
316
+ "outside_fraction": float(residual.norm() / v.norm()) if float(v.norm()) else 0.0,
317
+ "norm": float(v.norm())}
318
+
319
+
320
+ def trace_feature(run: Any, basis: FeatureBasis, feature: int, row: int, *,
321
+ top: int = 4) -> dict[str, Any]:
322
+ """A feature's life along one token row, read with its encoder row as a linear probe
323
+ ``pre_f(x) = W_enc[f].x + b_enc[f]`` (float64; the row sliced, then cast) at every residual
324
+ port ``h``, ``r``, ``h_out`` of every layer, and its writers: the exact linear shares
325
+ ``W_enc[f].o_l`` (attention) and ``W_enc[f].m_l`` (MLP) of each layer, the top heads
326
+ (``W_enc[f].W_o,h A_h``) of the strongest attention writer and the top neurons
327
+ (``W_enc[f].W_down[:, i] f_i``) of the strongest MLP writer. ``cutoff`` is the smallest
328
+ active pre-activation at the SAE's own site (the top-k threshold there): above it at the
329
+ site means active. Off the site the probe is the same linear map on another layer's
330
+ stream (no claim that the SAE is trained there)."""
331
+ from ..measure.readout import head_mix, layer_module
332
+
333
+ torch = _torch()
334
+ w = basis.W_enc[int(feature)].to(torch.float64)
335
+ b = float(basis.b_enc[int(feature)].to(torch.float64))
336
+ layers = run.adapter.layers
337
+ probe, writers = [], []
338
+ for layer in range(layers):
339
+ ports = {name: f64(run.read(f"t{row}.L{layer}.{name}")).reshape(-1)
340
+ for name in ("h", "r", "h_out", "o", "m")}
341
+ probe.append({"layer": layer, **{name: float(w @ ports[name]) + b
342
+ for name in ("h", "r", "h_out")}})
343
+ writers.append({"layer": layer, "attn": float(w @ ports["o"]),
344
+ "mlp": float(w @ ports["m"])})
345
+ site_x = run.read(f"t{row}.L{basis.layer}.{basis.port}")
346
+ ids, pre32 = basis.select(site_x)
347
+ cutoff = float(pre32[-1]) if len(ids) else 0.0
348
+ active = int(feature) in ids
349
+ order = ["h", "r", "h_out"]
350
+ above = [(p["layer"], name) for p in probe for name in order if p[name] > cutoff]
351
+ attn_layer = max(writers, key=lambda x: abs(x["attn"]))["layer"]
352
+ mlp_layer = max(writers, key=lambda x: abs(x["mlp"]))["layer"]
353
+ mix = head_mix(run, row, attn_layer)
354
+ head_parts = mix.o_parts().sum(dim=1).to("cpu") @ w # (H,)
355
+ heads = sorted(((int(h), float(v)) for h, v in enumerate(head_parts.tolist())),
356
+ key=lambda x: -abs(x[1]))[:top]
357
+ down = layer_module(run.adapter, mlp_layer).mlp.down_proj.weight
358
+ f_act = f64(run.read(f"t{row}.L{mlp_layer}.f")).reshape(-1)
359
+ unit = (w.to(down.device).to(torch.float32) @ down.to(torch.float32)).to("cpu") # ranking
360
+ approx = unit.to(torch.float64) * f_act
361
+ cand = torch.topk(approx.abs(), min(4 * top, approx.numel())).indices.tolist()
362
+ exact = [(int(i), float(w @ down[:, i].detach().to("cpu").to(torch.float64)) * float(f_act[i]))
363
+ for i in cand]
364
+ neurons = sorted(exact, key=lambda x: -abs(x[1]))[:top]
365
+ return {"feature": int(feature), "site": basis.site, "cutoff": cutoff, "active": active,
366
+ "enc_bias": b, "probe": probe, "writers": writers,
367
+ "first_above": above[0] if above else None,
368
+ "last_above": above[-1] if above else None,
369
+ "attn_layer": attn_layer, "heads": heads, "mlp_layer": mlp_layer,
370
+ "neurons": neurons}
371
+
372
+
373
+ __all__ = ["circuit", "match_unit", "trace_feature", "unit_vector", "edit_vector", "is_expression",
374
+ "margin_split", "parse_terms", "SCHEMA", "SUPPLIED", "LOCAL"]
@@ -0,0 +1,268 @@
1
+ """Derived feature addresses and feature watch predicates.
2
+
3
+ Address forms (``parse_feature_address``):
4
+
5
+ * ``feature[f]@t<r>.L<l>.h``: the activation ``a_f`` of feature ``f`` of a residual basis whose
6
+ site holds ``t<r>.L<l>.h`` (0 when ``f`` is not active; float64, ``derived-exact`` over the
7
+ native residual);
8
+ * ``feature[f]@cache.L<l>.v[kv<g>,row=<r>]``: feature ``f``'s component of that value cell
9
+ (``analysis.symbols.components``): its value (d_h,) or, with a ``CellTarget``-style token pair,
10
+ its content readout ``d . W_g v_f``.
11
+
12
+ ``FeatureCondition`` is a watch/break predicate (an ``engine.breakpoints.Condition``) that also
13
+ understands ``feature[f]`` (activation at the context's site), ``best_feature(SET)`` (the label
14
+ of the most active feature of a declared set, -1 when none is active; the label is the
15
+ feature's declared name token, else its id), ``content(SET)`` (the best token of a declared
16
+ candidate set read from the context cell's current value through ``gamma_F * W_U`` and the
17
+ KV group's ``W_O``; rho-free, a ranking) and declared numeric constants (``truth``). It reads
18
+ the run it is evaluated on (``ConditionEnv.run``), so it fires on edited values as well.
19
+
20
+ Multi-site watches: a ``FeatureContext`` is tied to one site (one basis,
21
+ one layer). ``FeatureCondition(text, contexts)`` also takes several contexts (a sequence, or
22
+ ``{layer: context}``; ``feature_sites`` builds one per layer from a ``{layer: basis}``): the
23
+ condition then reads, at each stop, the context of that stop's layer (``ConditionEnv.site``),
24
+ the item stops only at those layers, keeps one watch memory per layer and reports the stop
25
+ (``hit["site"]``, ``hit["layer"]``). A watch ``t4.L*.h`` over contexts for L0..Ln equals n
26
+ single-site watches ``t4.L<l>.h`` run one by one, in edge, level and change modes alike. Named
27
+ sets, labels, candidates and constants are per context, so every context must declare the
28
+ names the text uses.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import ast
34
+ import re
35
+ from dataclasses import dataclass, field
36
+ from typing import Any
37
+
38
+ from mdb.engine.breakpoints import Condition, ConditionError
39
+
40
+ from ..numerics.labels import f64
41
+ from ..predict.consumers import Refusal
42
+
43
+ _ADDRESS = re.compile(r"^feature\[(\d+)\]@(?:t(\d+)\.L(\d+)\.h|cache\.L(\d+)\.v\[kv(\d+),row=(\d+)\])$")
44
+ FUNCTIONS = ("best_feature", "content")
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class FeatureAddress:
49
+ feature: int
50
+ row: int
51
+ layer: int
52
+ form: str # "h" | "cell"
53
+ kv: int | None = None
54
+
55
+ @property
56
+ def text(self) -> str:
57
+ if self.form == "h":
58
+ return f"feature[{self.feature}]@t{self.row}.L{self.layer}.h"
59
+ return f"feature[{self.feature}]@cache.L{self.layer}.v[kv{self.kv},row={self.row}]"
60
+
61
+ @property
62
+ def site(self) -> str:
63
+ """The residual the basis reads: ``t<r>.L<l>.h`` (also for the cell form)."""
64
+ return f"t{self.row}.L{self.layer}.h"
65
+
66
+
67
+ def parse_feature_address(text: str) -> FeatureAddress:
68
+ m = _ADDRESS.match(text.replace(" ", ""))
69
+ if not m:
70
+ raise Refusal(f"a feature address is feature[f]@t<r>.L<l>.h or "
71
+ f"feature[f]@cache.L<l>.v[kv<g>,row=<r>], not {text!r}")
72
+ f = int(m[1])
73
+ if m[2] is not None:
74
+ return FeatureAddress(f, int(m[2]), int(m[3]), "h")
75
+ return FeatureAddress(f, int(m[6]), int(m[4]), "cell", int(m[5]))
76
+
77
+
78
+ def activations(run: Any, basis: Any, row: int, layer: int) -> dict[int, float]:
79
+ """``{feature: a_f}`` of the active set at ``t<row>.L<layer>.h`` (float64); for a transcoder
80
+ (``read_port`` ``n``) at its read site ``t<row>.L<layer>.n``."""
81
+ port = getattr(basis, "read_port", "h")
82
+ if not basis.covers(layer, port):
83
+ raise Refusal(f"basis {basis.name} at {basis.site} does not hold L{layer}.{port}")
84
+ if row == 0 and port == "h":
85
+ from ..symbols.components import FIRST_ROW_CAVEAT
86
+
87
+ raise Refusal(f"t0: {FIRST_ROW_CAVEAT}")
88
+ enc = basis.encode(run.read(f"t{row}.L{layer}.{port}"))
89
+ return {int(f): float(a) for f, a in zip(enc["ids"], enc["acts"].tolist())}
90
+
91
+
92
+ def feature_value(run: Any, address: FeatureAddress | str, basis: Any, *,
93
+ target: Any = None) -> Any:
94
+ """The value at a feature address (module docstring). ``target``: a ``symbols.hop.CellTarget``
95
+ for the cell form's scalar content readout."""
96
+ if isinstance(address, str):
97
+ address = parse_feature_address(address)
98
+ if address.form == "h":
99
+ return activations(run, basis, address.row, address.layer).get(address.feature, 0.0)
100
+ from ..symbols.components import component_binding
101
+
102
+ cb = component_binding(run, "watch", f"cache.L{address.layer}.v[kv{address.kv},"
103
+ f"row={address.row}]", basis, features=[address.feature])
104
+ value = cb.components[0].value
105
+ if target is None:
106
+ return value
107
+ from ..symbols.hop import _cell_direction
108
+
109
+ return float(_cell_direction(run, target) @ value)
110
+
111
+
112
+ @dataclass
113
+ class FeatureContext:
114
+ """What a ``FeatureCondition`` reads: the basis, the site row/layer, optionally the cell's KV
115
+ group for ``content``, named feature sets, labels, candidate token sets and constants."""
116
+
117
+ basis: Any
118
+ row: int
119
+ layer: int
120
+ kv: int | None = None
121
+ sets: dict[str, list[int]] = field(default_factory=dict)
122
+ labels: dict[int, int] = field(default_factory=dict)
123
+ candidates: dict[str, list[int]] = field(default_factory=dict)
124
+ constants: dict[str, float] = field(default_factory=dict)
125
+ _memo: Any = field(default=None, repr=False) # (run, run.stage_key, acts): the last read
126
+
127
+ def acts(self, run: Any) -> dict[int, float]:
128
+ key = run.stage_key
129
+ memo = self._memo
130
+ if memo is not None and memo[0] is run and memo[1][:2] == key[:2] and all(
131
+ len(a) == len(b) and all(x is y for x, y in zip(a, b))
132
+ for a, b in zip(memo[1][2:], key[2:])):
133
+ return memo[2]
134
+ acts = activations(run, self.basis, self.row, self.layer)
135
+ self._memo = (run, key, acts) # holds run and the edits: their ids cannot be reused
136
+ return acts
137
+
138
+ def best_feature(self, run: Any, name: str) -> int:
139
+ acts = self.acts(run)
140
+ live = [(acts[f], f) for f in self.sets[name] if acts.get(f, 0.0) > 0]
141
+ if not live:
142
+ return -1
143
+ f = max(live)[1]
144
+ return int(self.labels.get(f, f))
145
+
146
+ def content(self, run: Any, name: str) -> int:
147
+ """Best token of candidate set ``name`` read from the cell's current value (ranking:
148
+ ``gamma_F * W_U[t] . W_g v``, rho-free)."""
149
+ from ..measure.readout import layer_module
150
+ from ..symbols.circuit_map import group_writers
151
+
152
+ if self.kv is None:
153
+ raise ConditionError("content(SET) needs a context cell (kv)")
154
+ ad = run.adapter
155
+ v = f64(run.read_cache(self.layer, "v", staged=False)[0, self.kv, self.row]).cpu()
156
+ w_g = group_writers(layer_module(ad, self.layer).self_attn.o_proj.weight,
157
+ ad.num_heads, ad.num_kv_heads)[self.kv]
158
+ write = f64(w_g).cpu() @ v
159
+ final = getattr(ad.backbone, ad.spec.final_norm)
160
+ gamma = f64(final.weight).reshape(-1).cpu()
161
+ toks = self.candidates[name]
162
+ import torch
163
+
164
+ rows = f64(ad.model.lm_head.weight.index_select(
165
+ 0, torch.tensor(toks, device=ad.model.lm_head.weight.device))).cpu()
166
+ scores = (rows * gamma) @ write
167
+ return int(toks[int(scores.argmax())])
168
+
169
+
170
+ def feature_sites(bases: Any, row: int, layers: Any = None, **shared: Any) -> dict[int, FeatureContext]:
171
+ """``{layer: FeatureContext}`` for a multi-site ``FeatureCondition``: one context per layer of
172
+ ``bases`` (``{layer: basis}``, or a callable ``layer -> basis``; ``layers`` then names them),
173
+ all at ``row``, sharing ``kv``, ``sets``, ``labels``, ``candidates`` and ``constants``."""
174
+ if callable(bases):
175
+ if layers is None:
176
+ raise Refusal("feature_sites(callable) needs layers=")
177
+ found = {int(layer): bases(int(layer)) for layer in layers}
178
+ else:
179
+ found = {int(layer): basis for layer, basis in dict(bases).items()
180
+ if layers is None or layer in set(layers)}
181
+ return {layer: FeatureContext(basis, row, layer, **shared) for layer, basis in
182
+ sorted(found.items())}
183
+
184
+
185
+ class FeatureCondition(Condition):
186
+ """A ``Condition`` that also reads features (module docstring). ``context``: one
187
+ ``FeatureContext`` (a single-site condition), or several (a sequence, or ``{layer:
188
+ context}``; one per distinct layer): a multi-site condition (``sites`` = their layers)."""
189
+
190
+ def __init__(self, text: str, context: Any):
191
+ if isinstance(context, FeatureContext):
192
+ self.contexts = {context.layer: context}
193
+ self.sites = None
194
+ else:
195
+ items = list(context.values()) if isinstance(context, dict) else list(context)
196
+ if not items or not all(isinstance(c, FeatureContext) for c in items):
197
+ raise ConditionError("a feature condition takes a FeatureContext or several")
198
+ layers = [c.layer for c in items]
199
+ if len(set(layers)) != len(layers):
200
+ raise ConditionError("one context per layer in a multi-site feature condition")
201
+ if isinstance(context, dict) and any(int(k) != c.layer for k, c in context.items()):
202
+ raise ConditionError("a context dict is keyed by its context's layer")
203
+ self.contexts = {c.layer: c for c in items}
204
+ self.sites = frozenset(layers)
205
+ self.context = next(iter(self.contexts.values()))
206
+ super().__init__(text)
207
+
208
+ def _context(self, env: Any = None) -> FeatureContext:
209
+ """The context of the stop ``env`` is at (a single-site condition: its only one)."""
210
+ if self.sites is None:
211
+ return self.context
212
+ match = re.search(r"\.L(\d+)\.", getattr(env, "site", None) or "")
213
+ if match is None or int(match[1]) not in self.contexts:
214
+ raise ConditionError(f"no feature context for the stop "
215
+ f"{getattr(env, 'site', None)!r} (sites: L"
216
+ f"{', L'.join(map(str, sorted(self.sites)))})")
217
+ return self.contexts[int(match[1])]
218
+
219
+ def _check(self, node: ast.AST, *, value_ok: bool = False) -> None:
220
+ contexts = list(self.contexts.values())
221
+ if isinstance(node, ast.Name) and any(node.id in c.constants for c in contexts):
222
+ if not all(node.id in c.constants for c in contexts):
223
+ raise ConditionError(f"constant {node.id!r} is not declared at every site")
224
+ return
225
+ if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and \
226
+ node.value.id == "feature":
227
+ idx = node.slice
228
+ if not (isinstance(idx, ast.Constant) and type(idx.value) is int):
229
+ raise ConditionError("feature[...] takes one integer feature id")
230
+ return
231
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and \
232
+ node.func.id in FUNCTIONS:
233
+ if node.keywords or len(node.args) != 1 or not isinstance(node.args[0], ast.Name):
234
+ raise ConditionError(f"{node.func.id}(SET) takes one declared set name")
235
+ name = node.args[0].id
236
+ for ctx in contexts:
237
+ pool = ctx.sets if node.func.id == "best_feature" else ctx.candidates
238
+ if name not in pool:
239
+ raise ConditionError(f"{node.func.id}: no declared set {name!r}"
240
+ + ("" if self.sites is None else f" at L{ctx.layer}"))
241
+ return
242
+ super()._check(node, value_ok=value_ok)
243
+
244
+ def _eval(self, node: ast.AST, env: Any) -> Any:
245
+ ctx = self._context(env)
246
+ run = getattr(env, "run", None)
247
+ if isinstance(node, ast.Name) and node.id in ctx.constants:
248
+ return ctx.constants[node.id]
249
+ if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and \
250
+ node.value.id == "feature":
251
+ return ctx.acts(self._need(run)).get(int(node.slice.value), 0.0)
252
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and \
253
+ node.func.id in FUNCTIONS:
254
+ name = node.args[0].id
255
+ if node.func.id == "best_feature":
256
+ return ctx.best_feature(self._need(run), name)
257
+ return ctx.content(self._need(run), name)
258
+ return super()._eval(node, env)
259
+
260
+ @staticmethod
261
+ def _need(run: Any) -> Any:
262
+ if run is None:
263
+ raise ConditionError("a feature predicate needs the run (ConditionEnv.run)")
264
+ return run
265
+
266
+
267
+ __all__ = ["FeatureAddress", "FeatureCondition", "FeatureContext", "activations",
268
+ "feature_sites", "feature_value", "parse_feature_address"]
@@ -0,0 +1,7 @@
1
+ """Measure: native measurement harnesses: who reads a row (``reads``), several edits or
2
+ checkpoints on one consumer (``compare``, ``branches``, ``sweep``), multi-donor runners
3
+ (``donors``), pooled measurements (``pools``), paired paths (``paths``) and ``changes``.
4
+
5
+ Sublayer above ``predict`` (``numerics < predict < measure < circuits < symbols < features``):
6
+ module-level imports reach only ``numerics``, ``predict`` and ``measure``.
7
+ """