model-runtime 0.5.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.
@@ -0,0 +1,1198 @@
1
+ """Native edge test for Anthropic / Decode Research `circuit-tracer` attribution graphs.
2
+
3
+ `circuit-tracer` builds an *attribution graph* on a transcoder **replacement** model: it
4
+ decomposes each MLP into sparse transcoder features and reports which feature nodes (and
5
+ transcoder *error* nodes) influence a target logit. A graph edge is a candidate, not a
6
+ verdict. This module takes such a graph, turns each selected feature into a native
7
+ intervention on the **real** model weights at the residual-stream point the transcoder
8
+ writes to, runs the native continuation, and lets the unchanged native consumer decide
9
+ whether the edge *survives* or *collapses* -- using Saturn's :mod:`saturn.trial`
10
+ seam (``Reading.from_external`` + the frozen :class:`~saturn.trial.DecisionRule`).
11
+
12
+ Operators (both use the real weights and a native greedy continuation):
13
+
14
+ * ``carrier`` -- the Saturn transaction path. For a feature whose transcoder writes at
15
+ one layer (a per-layer transcoder) and whose node sits at the **last** prompt position,
16
+ step a :class:`~saturn.Session` to that write boundary, subtract the feature's
17
+ decoder contribution with an :class:`~saturn.Act`, and arbitrate it with
18
+ :func:`saturn.trial.arbitrate`. This yields a sealed :class:`~saturn.Receipt` and
19
+ a cut that replays in a fresh process.
20
+ * ``residual_hook`` -- a position-general native re-test. For a feature at any position,
21
+ add its decoder contribution to the real model's residual stream at each write layer with
22
+ a forward hook, run the native forward, and grade the target-logit effect under the same
23
+ frozen rule. This covers the subject-position features an attribution graph cares about.
24
+
25
+ Transcoder **error** nodes carry influence the transcoders do not reconstruct as a feature
26
+ direction; they are reported as *uncovered*, never silently dropped.
27
+
28
+ `circuit_tracer` itself is an **optional** dependency and is imported lazily -- importing
29
+ this module needs only torch (for the native path) and the stdlib. The offline tests and
30
+ the shipped notebook drive it with a synthetic graph object and re-derive the sealed
31
+ verdict table with :func:`verify_edge_bundle` (stdlib only, no torch, no model).
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import hashlib
37
+ import json
38
+ import platform
39
+ from collections.abc import Callable, Mapping, Sequence
40
+ from dataclasses import dataclass, field
41
+ from pathlib import Path
42
+ from typing import Any
43
+
44
+ from ..core import Act, Receipt
45
+ from ..trial import DecisionRule, Reading, grade
46
+ from ..values import canonical, describe, digest
47
+
48
+ # A decoder-write provider maps (feature_layer, feature_idx) -> [(write_layer, direction), ...].
49
+ # A per-layer transcoder returns one pair at its own layer; a cross-layer transcoder returns
50
+ # one pair per layer it writes to. ``direction`` is a 1-D residual-space tensor (d_model).
51
+ DecoderWrites = Callable[[int, int], Sequence[tuple[int, Any]]]
52
+
53
+ # Neutral native-necessity labels. The native drop measures only whether removing *this*
54
+ # feature's contribution is individually load-bearing on the real model -- it is NOT a verdict
55
+ # on the attribution graph. Agreement with the graph is a separate axis (``graph_vs_native``,
56
+ # which needs the graph's own predicted drop); see :func:`classify_graph_vs_native`.
57
+ _VERDICT_FROM_TRIAL = {
58
+ "agree": "native_necessary",
59
+ "invert": "native_effect_absent",
60
+ "inconclusive": "inconclusive",
61
+ }
62
+
63
+
64
+ def default_edge_rule() -> DecisionRule:
65
+ """The frozen rule the native edge test labels every edge under.
66
+
67
+ ``consumer_logprob_drop`` is ``logprob(target | clean) - logprob(target | intervention)``
68
+ in nats: higher means the intervention hurt the answer more. The label is about the
69
+ *native* model only: ``native_necessary`` (drop >= 0.5 nats, removing this contribution is
70
+ individually load-bearing), ``native_effect_absent`` (drop <= 0.1 nats, no individual
71
+ effect), or ``inconclusive``. A single feature showing ``native_effect_absent`` is NOT by
72
+ itself evidence against the graph -- under a redundant circuit many features each carry
73
+ little alone. Whether that disagrees with the graph is the separate ``graph_vs_native``
74
+ axis, which compares this drop to the replacement model's own predicted drop.
75
+ """
76
+ return DecisionRule(
77
+ name="circuit-tracer-native-edge",
78
+ version="1",
79
+ metric="consumer_logprob_drop",
80
+ present_threshold=0.5,
81
+ absent_threshold=0.1,
82
+ require_exact_gate=True,
83
+ description=(
84
+ "Native-necessity of one transcoder feature on the real model: native_necessary iff "
85
+ "removing its decoder contribution drops the target log-prob by >= 0.5 nats; "
86
+ "native_effect_absent iff the drop is <= 0.1 nats; inconclusive between. This labels "
87
+ "the native model's response to the intervention, not the attribution graph."
88
+ ),
89
+ )
90
+
91
+
92
+ def classify_graph_vs_native(
93
+ graph_delta: float | None, native_delta: float | None, rule: DecisionRule
94
+ ) -> str:
95
+ """Compare the graph's predicted target-logprob drop to the native one, same intervention.
96
+
97
+ This is the scientific axis the single native label cannot answer: does the replacement
98
+ model (where the graph lives) *predict* a large effect where the real model shows none (a
99
+ genuine ``invert``, i.e. the graph is wrong), or do both show a small effect (``agree_small``
100
+ -- redundancy, not a graph failure), or both large (``agree_large``)?
101
+ """
102
+ if graph_delta is None or native_delta is None:
103
+ return "no_graph_prediction"
104
+ present, absent = rule.present_threshold, rule.absent_threshold
105
+ g_large, g_small = graph_delta >= present, graph_delta <= absent
106
+ n_large, n_small = native_delta >= present, native_delta <= absent
107
+ if g_small and n_small:
108
+ return "agree_small"
109
+ if g_large and n_large:
110
+ return "agree_large"
111
+ if g_large and n_small:
112
+ return "invert" # graph predicts necessity the native model does not show
113
+ return "mixed"
114
+
115
+
116
+ # --------------------------------------------------------------------------------------
117
+ # Graph reading + edge selection (circuit-tracer's own influence algorithm, reimplemented).
118
+ # --------------------------------------------------------------------------------------
119
+
120
+
121
+ def _node_influence(adjacency: Any, logit_weights: Any, *, max_iter: int = 2000) -> Any:
122
+ """Total node influence on the logits: ``w @ (A + A^2 + ...)`` over the normalised graph.
123
+
124
+ This reproduces circuit-tracer's ``compute_node_influence`` (``normalize_matrix`` then the
125
+ truncated Neumann series) so the edge ranking matches the tool, without importing it.
126
+ """
127
+
128
+ a = adjacency.abs()
129
+ a = a / a.sum(dim=1, keepdim=True).clamp(min=1e-10)
130
+ current = logit_weights @ a
131
+ influence = current.clone()
132
+ for _ in range(max_iter):
133
+ if not bool(current.any()):
134
+ break
135
+ current = current @ a
136
+ influence = influence + current
137
+ return influence
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class _GraphView:
142
+ """Normalised view of the fields the edge test reads from an attribution graph."""
143
+
144
+ active_features: Any # [n_active, 3] int: (layer, pos, feature_idx)
145
+ selected_features: Any # [n_sel] int: indices into active_features
146
+ activation_values: Any # [n_active] float: clean activation, aligned with active_features
147
+ adjacency_matrix: Any # [n_nodes, n_nodes]
148
+ logit_probabilities: Any # [n_logit]
149
+ n_pos: int
150
+ n_layers: int
151
+ input_tokens: list[int]
152
+
153
+
154
+ def _as_view(graph: Any) -> _GraphView:
155
+ import torch
156
+
157
+ def _t(x: Any) -> Any:
158
+ return x if isinstance(x, torch.Tensor) else torch.as_tensor(x)
159
+
160
+ cfg = getattr(graph, "cfg", None)
161
+ n_layers = int(getattr(cfg, "n_layers", 0) or getattr(graph, "n_layers", 0))
162
+ if n_layers <= 0:
163
+ raise ValueError("attribution graph must expose cfg.n_layers (or n_layers)")
164
+ tokens = getattr(graph, "input_tokens")
165
+ tokens = tokens.tolist() if hasattr(tokens, "tolist") else list(tokens)
166
+ active = _t(graph.active_features).long()
167
+ values = _t(graph.activation_values).float()
168
+ # circuit-tracer stores one activation per *active* feature (the sparse activation
169
+ # matrix's values), not one per selected node; index it through selected_features.
170
+ if int(values.shape[0]) != int(active.shape[0]):
171
+ raise ValueError(
172
+ "attribution graph activation_values must align with active_features "
173
+ f"({int(values.shape[0])} values for {int(active.shape[0])} active features)"
174
+ )
175
+ return _GraphView(
176
+ active_features=active,
177
+ selected_features=_t(graph.selected_features).long(),
178
+ activation_values=values,
179
+ adjacency_matrix=_t(graph.adjacency_matrix).float(),
180
+ logit_probabilities=_t(graph.logit_probabilities).float(),
181
+ n_pos=int(getattr(graph, "n_pos", len(tokens))),
182
+ n_layers=n_layers,
183
+ input_tokens=[int(t) for t in tokens],
184
+ )
185
+
186
+
187
+ @dataclass(frozen=True)
188
+ class _SelectedEdge:
189
+ rank: int
190
+ layer: int
191
+ position: int
192
+ feature: int
193
+ activation: float
194
+ graph_weight: float
195
+ # The replacement model's own predicted target-logprob drop for this feature's zero
196
+ # ablation, measured with circuit-tracer's feature_intervention (filled by the caller that
197
+ # still holds the replacement model). ``None`` when not supplied.
198
+ graph_predicted_delta: float | None = None
199
+
200
+
201
+ @dataclass(frozen=True)
202
+ class GraphInfluence:
203
+ """Influence summary over the graph's feature and transcoder-error nodes."""
204
+
205
+ edges: tuple[_SelectedEdge, ...]
206
+ n_feature_nodes: int
207
+ n_error_nodes: int
208
+ feature_influence_total: float
209
+ error_influence_total: float
210
+
211
+ @property
212
+ def error_node_influence_share(self) -> float:
213
+ total = self.feature_influence_total + self.error_influence_total
214
+ return float(self.error_influence_total / total) if total else 0.0
215
+
216
+
217
+ def select_edges(graph: Any, *, top_k: int, influence: Any | None = None) -> GraphInfluence:
218
+ """Rank selected feature nodes by influence on the target logit; summarise error nodes.
219
+
220
+ ``influence`` may be supplied (e.g. circuit-tracer's own ``compute_node_influence``
221
+ output over the same node ordering); otherwise it is recomputed here identically.
222
+ """
223
+ import torch
224
+
225
+ view = _as_view(graph)
226
+ n_feat = int(view.selected_features.shape[0])
227
+ n_err = view.n_layers * view.n_pos
228
+ n_logit = int(view.logit_probabilities.shape[0])
229
+ a = view.adjacency_matrix
230
+ if influence is None:
231
+ logit_weights = torch.zeros(a.shape[0], dtype=a.dtype)
232
+ logit_weights[-n_logit:] = view.logit_probabilities.to(a.dtype)
233
+ influence = _node_influence(a, logit_weights)
234
+ influence = influence.float()
235
+ feat_infl = influence[:n_feat]
236
+ err_infl = influence[n_feat : n_feat + n_err]
237
+ af = view.active_features[view.selected_features] # [n_feat, 3]
238
+ order = torch.argsort(feat_infl, descending=True).tolist()
239
+ edges = []
240
+ for rank, i in enumerate(order[: int(top_k)]):
241
+ layer, pos, feat = (int(x) for x in af[i].tolist())
242
+ active_index = int(view.selected_features[i])
243
+ edges.append(
244
+ _SelectedEdge(
245
+ rank=rank,
246
+ layer=layer,
247
+ position=pos,
248
+ feature=feat,
249
+ activation=float(view.activation_values[active_index]),
250
+ graph_weight=float(feat_infl[i]),
251
+ )
252
+ )
253
+ return GraphInfluence(
254
+ edges=tuple(edges),
255
+ n_feature_nodes=n_feat,
256
+ n_error_nodes=n_err,
257
+ feature_influence_total=float(feat_infl.clamp(min=0).sum()),
258
+ error_influence_total=float(err_infl.clamp(min=0).sum()),
259
+ )
260
+
261
+
262
+ # --------------------------------------------------------------------------------------
263
+ # Verdict row + table.
264
+ # --------------------------------------------------------------------------------------
265
+
266
+
267
+ @dataclass(frozen=True)
268
+ class EdgeRow:
269
+ """One attribution edge tested natively (or reported uncovered)."""
270
+
271
+ node_kind: str # "feature" | "error"
272
+ layer: int | None
273
+ position: int | None
274
+ feature: int | None
275
+ graph_weight: float
276
+ activation: float | None
277
+ write_layers: tuple[int, ...]
278
+ feature_type: str
279
+ operator: str # "carrier+arbitrate" | "residual_hook" | "uncovered"
280
+ covered: bool
281
+ verdict: str # "survives" | "collapses" | "inconclusive" | "uncovered"
282
+ native_logit_delta: float | None
283
+ clean_logprob: float | None
284
+ ablated_logprob: float | None
285
+ top_token_clean: int | None
286
+ top_token_ablated: int | None
287
+ top_token_flip: bool | None
288
+ reason: str
289
+ reading_fingerprint: str | None
290
+ rule_fingerprint: str | None
291
+ receipt: str | None
292
+ measurements: Mapping[str, Any] = field(default_factory=dict)
293
+ # Graph side: the replacement model's predicted drop for the same intervention, and how it
294
+ # compares to the native drop (see :func:`classify_graph_vs_native`). ``None`` when the
295
+ # caller did not supply a graph prediction.
296
+ graph_predicted_delta: float | None = None
297
+ graph_vs_native: str | None = None
298
+
299
+ def to_dict(self) -> dict[str, Any]:
300
+ body = {
301
+ "node_kind": self.node_kind,
302
+ "layer": self.layer,
303
+ "position": self.position,
304
+ "feature": self.feature,
305
+ "graph_weight": self.graph_weight,
306
+ "activation": self.activation,
307
+ "write_layers": list(self.write_layers),
308
+ "feature_type": self.feature_type,
309
+ "operator": self.operator,
310
+ "covered": self.covered,
311
+ "verdict": self.verdict,
312
+ "native_logit_delta": self.native_logit_delta,
313
+ "graph_predicted_delta": self.graph_predicted_delta,
314
+ "graph_vs_native": self.graph_vs_native,
315
+ "clean_logprob": self.clean_logprob,
316
+ "ablated_logprob": self.ablated_logprob,
317
+ "top_token_clean": self.top_token_clean,
318
+ "top_token_ablated": self.top_token_ablated,
319
+ "top_token_flip": self.top_token_flip,
320
+ "reason": self.reason,
321
+ "reading_fingerprint": self.reading_fingerprint,
322
+ "rule_fingerprint": self.rule_fingerprint,
323
+ "receipt": self.receipt,
324
+ "measurements": dict(self.measurements),
325
+ }
326
+ body["fingerprint"] = digest(body)
327
+ return body
328
+
329
+
330
+ @dataclass(frozen=True)
331
+ class EdgeVerdictTable:
332
+ """The native verdict for every selected edge, plus honest uncovered accounting."""
333
+
334
+ model_identity: str
335
+ execution: Mapping[str, Any]
336
+ prompt: str
337
+ tokens: tuple[int, ...]
338
+ target_token: int
339
+ target_text: str
340
+ subject_position: int | None
341
+ top_k: int
342
+ decision_rule: Mapping[str, Any]
343
+ rows: tuple[EdgeRow, ...]
344
+ graph_summary: Mapping[str, Any]
345
+ environment: Mapping[str, Any]
346
+ custody: Mapping[str, Any]
347
+ # Group interventions (joint ablation / steering of a supernode or the top-k feature set);
348
+ # each dict carries native_delta, graph_predicted_delta, verdict, graph_vs_native, members.
349
+ group_interventions: tuple[Mapping[str, Any], ...] = ()
350
+
351
+ def summary(self) -> dict[str, Any]:
352
+ covered = [r for r in self.rows if r.covered]
353
+ necessary = [r for r in covered if r.verdict == "native_necessary"]
354
+ absent = [r for r in covered if r.verdict == "native_effect_absent"]
355
+ inconclusive = [r for r in covered if r.verdict == "inconclusive"]
356
+ n_feature = sum(1 for r in self.rows if r.node_kind == "feature")
357
+ with_graph = [r for r in covered if r.graph_vs_native not in (None, "no_graph_prediction")]
358
+ agree = [r for r in with_graph if r.graph_vs_native in ("agree_small", "agree_large")]
359
+ invert = [r for r in with_graph if r.graph_vs_native == "invert"]
360
+ mixed = [r for r in with_graph if r.graph_vs_native == "mixed"]
361
+ return {
362
+ "n_edges": len(self.rows),
363
+ "n_feature_edges": n_feature,
364
+ "n_error_nodes_reported": sum(1 for r in self.rows if r.node_kind == "error"),
365
+ "n_covered": len(covered),
366
+ "n_native_necessary": len(necessary),
367
+ "n_native_effect_absent": len(absent),
368
+ "n_inconclusive": len(inconclusive),
369
+ "n_uncovered": sum(1 for r in self.rows if not r.covered),
370
+ "covered_fraction": (len(covered) / n_feature) if n_feature else 0.0,
371
+ "native_necessary_fraction": (len(necessary) / len(covered)) if covered else 0.0,
372
+ "n_with_graph_prediction": len(with_graph),
373
+ "n_agree_with_graph": len(agree),
374
+ "n_invert_vs_graph": len(invert),
375
+ "n_mixed_vs_graph": len(mixed),
376
+ "graph_agreement_fraction": (len(agree) / len(with_graph)) if with_graph else None,
377
+ "error_node_influence_share": self.graph_summary.get("error_node_influence_share"),
378
+ }
379
+
380
+ def to_dict(self) -> dict[str, Any]:
381
+ body = {
382
+ "schema": "saturn-pub-circuit-tracer-edge-verdicts-v1",
383
+ "model_identity": self.model_identity,
384
+ "execution": dict(self.execution),
385
+ "prompt": self.prompt,
386
+ "tokens": list(self.tokens),
387
+ "target_token": self.target_token,
388
+ "target_text": self.target_text,
389
+ "subject_position": self.subject_position,
390
+ "top_k": self.top_k,
391
+ "decision_rule": dict(self.decision_rule),
392
+ "graph_summary": dict(self.graph_summary),
393
+ "summary": self.summary(),
394
+ "rows": [r.to_dict() for r in self.rows],
395
+ "group_interventions": [dict(g) for g in self.group_interventions],
396
+ "environment": dict(self.environment),
397
+ "custody": dict(self.custody),
398
+ "arbiter": "unchanged native consumer; an attribution edge is a candidate, not a verdict",
399
+ }
400
+ body["fingerprint"] = digest(body)
401
+ return body
402
+
403
+ def seal(self, directory: str | Path) -> dict[str, Any]:
404
+ """Write a hash-pinned bundle: ``edge_verdicts.json`` + ``manifest.json``.
405
+
406
+ Returns the bundle fingerprint and manifest. :func:`verify_edge_bundle` re-derives
407
+ every covered verdict from the sealed scalars offline (stdlib only).
408
+ """
409
+ directory = Path(directory)
410
+ directory.mkdir(parents=True, exist_ok=True)
411
+ body = canonical(self.to_dict())
412
+ (directory / "edge_verdicts.json").write_bytes(body)
413
+ manifest = {"edge_verdicts.json": hashlib.sha256(body).hexdigest()}
414
+ (directory / "manifest.json").write_bytes(canonical(manifest))
415
+ return {
416
+ "bundle": str(directory),
417
+ "fingerprint": self.to_dict()["fingerprint"],
418
+ "manifest": manifest,
419
+ }
420
+
421
+
422
+ # --------------------------------------------------------------------------------------
423
+ # The native edge test.
424
+ # --------------------------------------------------------------------------------------
425
+
426
+
427
+ def _target_logprob(logits: Any, target: int) -> tuple[float, int]:
428
+ import torch
429
+
430
+ lp = torch.log_softmax(logits.reshape(-1).float(), dim=-1)
431
+ return float(lp[target]), int(logits.reshape(-1).argmax())
432
+
433
+
434
+ def _residual_hook_effect(
435
+ adapter: Any,
436
+ tokens: Sequence[int],
437
+ writes: Sequence[tuple[int, Any]],
438
+ activation: float,
439
+ target: int,
440
+ clean_logits: Any,
441
+ ) -> dict[str, Any]:
442
+ """Native re-test: add ``-activation * direction`` at each write layer's resid_post, forward."""
443
+ import torch
444
+
445
+ handles = []
446
+
447
+ def _hook_for(position: int, direction: Any):
448
+ vec = (-float(activation)) * direction.to(adapter.dtype).reshape(-1)
449
+
450
+ def hook(_module, _inputs, output):
451
+ hidden = output[0] if isinstance(output, tuple) else output
452
+ hidden = hidden.clone()
453
+ hidden[:, position, :] = hidden[:, position, :] + vec.to(hidden.device)
454
+ if isinstance(output, tuple):
455
+ return (hidden, *output[1:])
456
+ return hidden
457
+
458
+ return hook
459
+
460
+ position = len(tokens) - 1
461
+ # a feature node lives at one position; the write layers share it
462
+ try:
463
+ for write_layer, direction in writes:
464
+ handle = adapter._layer_modules[write_layer].register_forward_hook(
465
+ _hook_for(position, direction)
466
+ )
467
+ handles.append(handle)
468
+ with torch.inference_mode():
469
+ ablated = adapter.model(torch.tensor([list(tokens)], device=adapter.device)).logits[
470
+ :, -1
471
+ ]
472
+ finally:
473
+ for handle in handles:
474
+ handle.remove()
475
+ clean_lp, clean_top = _target_logprob(clean_logits, target)
476
+ ablated_lp, ablated_top = _target_logprob(ablated, target)
477
+ return {
478
+ "clean_logprob": clean_lp,
479
+ "ablated_logprob": ablated_lp,
480
+ "consumer_logprob_drop": clean_lp - ablated_lp,
481
+ "top_token_clean": clean_top,
482
+ "top_token_ablated": ablated_top,
483
+ "top_token_flip": clean_top != ablated_top,
484
+ }
485
+
486
+
487
+ def _carrier_effect(
488
+ adapter: Any,
489
+ edge: _SelectedEdge,
490
+ direction: Any,
491
+ target: int,
492
+ rule: DecisionRule,
493
+ reading: Reading,
494
+ tokens: Sequence[int],
495
+ ) -> tuple[Any, dict[str, Any]]:
496
+ """Arbitrate a last-position per-layer feature through the Session carrier."""
497
+
498
+ from ..trial import arbitrate
499
+
500
+ write_boundary_steps = 1 + (edge.layer + 1) # embed + (layer+1) decoder layers
501
+ session = adapter.session(list(tokens))
502
+ session.continue_(write_boundary_steps) # now at layer:(L+1); hidden == resid_post[L], last pos
503
+ parent = session.capture(retain=False)
504
+ vec = direction.to(adapter.dtype).reshape(1, 1, -1)
505
+ act = Act.add(
506
+ "hidden", vec, dose=-float(edge.activation), name="circuit-tracer-feature-ablation"
507
+ )
508
+
509
+ def native_driver(branch: Any) -> None:
510
+ adapter.generate(branch, 1)
511
+
512
+ def candidate_driver(branch: Any) -> None:
513
+ branch.apply(act)
514
+ adapter.generate(branch, 1)
515
+
516
+ def effect(branches: Mapping[str, Any]) -> dict[str, Any]:
517
+ nat_logits = branches["native"].read("logits")[0]
518
+ cand_logits = branches["candidate"].read("logits")[0]
519
+ clean_lp, clean_top = _target_logprob(nat_logits, target)
520
+ ablated_lp, ablated_top = _target_logprob(cand_logits, target)
521
+ return {
522
+ "consumer_logprob_drop": clean_lp - ablated_lp,
523
+ "clean_logprob": clean_lp,
524
+ "ablated_logprob": ablated_lp,
525
+ "top_token_clean": clean_top,
526
+ "top_token_ablated": ablated_top,
527
+ "top_token_flip": clean_top != ablated_top,
528
+ }
529
+
530
+ row = arbitrate(
531
+ adapter,
532
+ reading,
533
+ rule,
534
+ effect=effect,
535
+ candidate=candidate_driver,
536
+ native=native_driver,
537
+ parent=parent,
538
+ )
539
+ return row, dict(row.measurements)
540
+
541
+
542
+ def native_group_intervention(
543
+ adapter: Any,
544
+ tokens: Sequence[int],
545
+ members: Sequence[Mapping[str, Any]],
546
+ target_token: int,
547
+ *,
548
+ name: str,
549
+ multiplier: float,
550
+ graph_predicted_delta: float | None = None,
551
+ decision_rule: DecisionRule | None = None,
552
+ clean_logits: Any | None = None,
553
+ ) -> dict[str, Any]:
554
+ """Jointly intervene on a whole feature set (a supernode / the top-k) on the real model.
555
+
556
+ This matches the attribution-graphs paper's group interventions: instead of zeroing one
557
+ feature, we steer the whole set at once. ``members`` is a list of
558
+ ``{layer, position, feature, activation, writes:[(write_layer, direction), ...]}``. The
559
+ ``multiplier`` m sets each feature's new value to ``m * activation`` (``m = 0`` ablates the
560
+ set; ``m = -2`` steers it to minus twice its natural activation, as the paper does); the
561
+ change added to the residual at each member's write layer and position is therefore
562
+ ``(m - 1) * activation * direction``. The group is graded for native necessity under the
563
+ frozen rule and compared to the replacement model's own predicted drop.
564
+ """
565
+ import torch
566
+
567
+ rule = decision_rule or default_edge_rule()
568
+ tokens = [int(t) for t in tokens]
569
+ if clean_logits is None:
570
+ with torch.inference_mode():
571
+ clean_logits = adapter.model(torch.tensor([tokens], device=adapter.device)).logits[
572
+ :, -1
573
+ ]
574
+
575
+ by_layer: dict[int, list[tuple[int, Any]]] = {}
576
+ member_ids = []
577
+ for m in members:
578
+ act = float(m["activation"])
579
+ pos = int(m["position"])
580
+ member_ids.append(
581
+ {
582
+ "layer": int(m["layer"]),
583
+ "position": pos,
584
+ "feature": int(m["feature"]),
585
+ "activation": act,
586
+ }
587
+ )
588
+ for write_layer, direction in m["writes"]:
589
+ vec = (float(multiplier) - 1.0) * act * direction.to(adapter.dtype).reshape(-1)
590
+ by_layer.setdefault(int(write_layer), []).append((pos, vec))
591
+
592
+ def _hook_for(entries: list[tuple[int, Any]]):
593
+ def hook(_module, _inputs, output):
594
+ hidden = output[0] if isinstance(output, tuple) else output
595
+ hidden = hidden.clone()
596
+ for pos, vec in entries:
597
+ hidden[:, pos, :] = hidden[:, pos, :] + vec.to(hidden.device)
598
+ if isinstance(output, tuple):
599
+ return (hidden, *output[1:])
600
+ return hidden
601
+
602
+ return hook
603
+
604
+ handles = []
605
+ try:
606
+ for write_layer, entries in by_layer.items():
607
+ handles.append(
608
+ adapter._layer_modules[write_layer].register_forward_hook(_hook_for(entries))
609
+ )
610
+ with torch.inference_mode():
611
+ steered = adapter.model(torch.tensor([tokens], device=adapter.device)).logits[:, -1]
612
+ finally:
613
+ for h in handles:
614
+ h.remove()
615
+
616
+ clean_lp, clean_top = _target_logprob(clean_logits, target_token)
617
+ steered_lp, steered_top = _target_logprob(steered, target_token)
618
+ drop = clean_lp - steered_lp
619
+ reading = Reading.from_external(
620
+ "circuit-tracer",
621
+ claim=f"group '{name}' ({len(member_ids)} features, multiplier {multiplier}) "
622
+ "is jointly load-bearing for the target logit",
623
+ asserts_effect=True,
624
+ detail={"name": name, "multiplier": multiplier, "n_members": len(member_ids)},
625
+ )
626
+ verdict, _classification, reason = grade(reading, rule, drop)
627
+ return {
628
+ "name": name,
629
+ "multiplier": float(multiplier),
630
+ "operator": "group_residual_hook",
631
+ "n_members": len(member_ids),
632
+ "members": member_ids,
633
+ "verdict": _VERDICT_FROM_TRIAL[verdict],
634
+ "native_logit_delta": drop,
635
+ "graph_predicted_delta": graph_predicted_delta,
636
+ "graph_vs_native": classify_graph_vs_native(graph_predicted_delta, drop, rule),
637
+ "clean_logprob": clean_lp,
638
+ "steered_logprob": steered_lp,
639
+ "top_token_clean": clean_top,
640
+ "top_token_steered": steered_top,
641
+ "top_token_flip": clean_top != steered_top,
642
+ "reason": reason,
643
+ "reading_fingerprint": reading.fingerprint,
644
+ "rule_fingerprint": rule.fingerprint,
645
+ }
646
+
647
+
648
+ def native_edge_test(
649
+ graph: Any,
650
+ adapter: Any,
651
+ *,
652
+ prompt_tokens: Sequence[int],
653
+ target_token: int,
654
+ decoder_writes: DecoderWrites,
655
+ top_k: int = 20,
656
+ decision_rule: DecisionRule | None = None,
657
+ operators: Sequence[str] = ("carrier", "residual_hook"),
658
+ max_carrier_edges: int | None = None,
659
+ influence: Any | None = None,
660
+ selection: GraphInfluence | None = None,
661
+ prompt_text: str = "",
662
+ target_text: str = "",
663
+ subject_position: int | None = None,
664
+ graph_scores: Mapping[str, Any] | None = None,
665
+ group_interventions: Sequence[Mapping[str, Any]] = (),
666
+ store: Any | None = None,
667
+ ) -> EdgeVerdictTable:
668
+ """Turn each selected attribution edge into a native verdict on the real model.
669
+
670
+ ``graph`` is a circuit-tracer ``Graph`` (or an object exposing the same fields; see
671
+ :func:`build_synthetic_graph`). ``adapter`` is a Saturn decoder adapter wrapping the
672
+ **real** model the graph was computed against. ``decoder_writes(layer, feature)`` returns
673
+ the transcoder's residual-space write directions for a feature, one ``(write_layer,
674
+ direction)`` pair per layer it writes to (one pair for a per-layer transcoder).
675
+
676
+ Pass ``graph`` to select edges here, or a precomputed ``selection`` (a
677
+ :class:`GraphInfluence`, e.g. ranked with circuit-tracer's own influence then kept while the
678
+ heavy replacement model is freed) to run only the native test. The two are mutually
679
+ sufficient; ``graph`` may be ``None`` when ``selection`` is given.
680
+
681
+ ``max_carrier_edges`` caps how many (top-ranked, last-position, single-write-layer) edges use
682
+ the heavier ``carrier``+``arbitrate`` path (which forks several native continuations for its
683
+ sealed receipt + exact-replay gate); edges past the cap fall through to the single-forward
684
+ ``residual_hook``, so every edge still gets a native verdict under the same frozen rule.
685
+
686
+ Every selected feature becomes a :func:`Reading.from_external` asserting the edge is
687
+ load-bearing, graded under the frozen ``decision_rule`` into a **native-necessity** label
688
+ (about the real model only): ``native_necessary`` (removing this one feature is individually
689
+ load-bearing), ``native_effect_absent`` (no individual effect -- under a redundant circuit
690
+ this is expected and is *not* by itself evidence against the graph), or ``inconclusive``.
691
+ When ``selection`` edges carry ``graph_predicted_delta`` (the replacement model's own
692
+ predicted drop for the same intervention), each row also gets a ``graph_vs_native`` tag
693
+ (:func:`classify_graph_vs_native`): ``invert`` means the graph predicted a large effect the
694
+ native model does not show (a real disagreement), ``agree_small``/``agree_large`` mean both
695
+ agree. ``group_interventions`` (built with :func:`native_group_intervention`) seal joint
696
+ ablation/steering of whole supernodes or the top-k set. Transcoder error nodes are reported
697
+ ``uncovered`` with their influence share. The result is a :class:`EdgeVerdictTable` whose
698
+ :meth:`~EdgeVerdictTable.seal` writes a hash-pinned, offline-re-derivable bundle.
699
+ """
700
+ import torch
701
+
702
+ rule = decision_rule or default_edge_rule()
703
+ tokens = [int(t) for t in prompt_tokens]
704
+ last_pos = len(tokens) - 1
705
+ if selection is None:
706
+ if graph is None:
707
+ raise ValueError("native_edge_test needs either a graph or a precomputed selection")
708
+ selection = select_edges(graph, top_k=top_k, influence=influence)
709
+
710
+ with torch.inference_mode():
711
+ clean_logits = adapter.model(torch.tensor([tokens], device=adapter.device)).logits[:, -1]
712
+
713
+ use_carrier = "carrier" in operators
714
+ use_hook = "residual_hook" in operators
715
+ rows: list[EdgeRow] = []
716
+ carrier_used = 0
717
+
718
+ for edge in selection.edges:
719
+ writes = [(int(wl), d) for wl, d in decoder_writes(edge.layer, edge.feature)]
720
+ write_layers = tuple(wl for wl, _ in writes)
721
+ in_range = all(0 <= wl < adapter.layers for wl in write_layers)
722
+ feature_type = (
723
+ "per-layer-transcoder"
724
+ if len(writes) == 1 and write_layers[0] == edge.layer
725
+ else "cross-layer-transcoder"
726
+ )
727
+ reading = Reading.from_external(
728
+ "circuit-tracer",
729
+ claim=(
730
+ f"attribution edge: feature {edge.feature} (layer {edge.layer}, "
731
+ f"position {edge.position}) is load-bearing for the target logit"
732
+ ),
733
+ asserts_effect=True,
734
+ detail={
735
+ "layer": edge.layer,
736
+ "position": edge.position,
737
+ "feature": edge.feature,
738
+ "graph_weight": edge.graph_weight,
739
+ "activation": edge.activation,
740
+ "write_layers": list(write_layers),
741
+ "feature_type": feature_type,
742
+ },
743
+ )
744
+
745
+ if not in_range:
746
+ rows.append(
747
+ _uncovered_row(
748
+ edge,
749
+ write_layers,
750
+ feature_type,
751
+ reading,
752
+ rule,
753
+ reason="transcoder write layer is outside the model's layer range",
754
+ )
755
+ )
756
+ continue
757
+
758
+ carrier_ok = (
759
+ use_carrier
760
+ and len(writes) == 1
761
+ and writes[0][0] == edge.layer
762
+ and edge.position == last_pos
763
+ and (max_carrier_edges is None or carrier_used < max_carrier_edges)
764
+ )
765
+ if carrier_ok:
766
+ carrier_used += 1
767
+ direction = writes[0][1]
768
+ trial_row, meas = _carrier_effect(
769
+ adapter, edge, direction, target_token, rule, reading, tokens
770
+ )
771
+ # cross-check with the position-matched residual hook (same intervention)
772
+ if use_hook:
773
+ hook = _residual_hook_effect(
774
+ adapter, tokens, writes, edge.activation, target_token, clean_logits
775
+ )
776
+ meas = {**meas, "residual_hook_crosscheck_drop": hook["consumer_logprob_drop"]}
777
+ rows.append(
778
+ EdgeRow(
779
+ node_kind="feature",
780
+ layer=edge.layer,
781
+ position=edge.position,
782
+ feature=edge.feature,
783
+ graph_weight=edge.graph_weight,
784
+ activation=edge.activation,
785
+ write_layers=write_layers,
786
+ feature_type=feature_type,
787
+ operator="carrier+arbitrate",
788
+ covered=True,
789
+ verdict=_VERDICT_FROM_TRIAL[trial_row.verdict],
790
+ native_logit_delta=trial_row.consumer_effect,
791
+ graph_predicted_delta=edge.graph_predicted_delta,
792
+ graph_vs_native=classify_graph_vs_native(
793
+ edge.graph_predicted_delta, trial_row.consumer_effect, rule
794
+ ),
795
+ clean_logprob=meas.get("clean_logprob"),
796
+ ablated_logprob=meas.get("ablated_logprob"),
797
+ top_token_clean=meas.get("top_token_clean"),
798
+ top_token_ablated=meas.get("top_token_ablated"),
799
+ top_token_flip=meas.get("top_token_flip"),
800
+ reason=trial_row.reason,
801
+ reading_fingerprint=reading.fingerprint,
802
+ rule_fingerprint=rule.fingerprint,
803
+ receipt=trial_row.receipt,
804
+ measurements=meas,
805
+ )
806
+ )
807
+ continue
808
+
809
+ if use_hook:
810
+ hook = _residual_hook_effect(
811
+ adapter, tokens, writes, edge.activation, target_token, clean_logits
812
+ )
813
+ effect = hook["consumer_logprob_drop"]
814
+ verdict, _classification, reason = grade(reading, rule, effect)
815
+ receipt = Receipt.make(
816
+ operation="interop.circuit_tracer.native_edge_test.residual_hook",
817
+ model_identity=adapter.model_identity,
818
+ execution=dict(adapter.execution),
819
+ reading=reading.to_dict(),
820
+ decision_rule=rule.to_dict(),
821
+ verdict=verdict,
822
+ consumer_effect=effect,
823
+ measurements=describe(hook),
824
+ layer=edge.layer,
825
+ position=edge.position,
826
+ feature=edge.feature,
827
+ write_layers=list(write_layers),
828
+ )
829
+ rows.append(
830
+ EdgeRow(
831
+ node_kind="feature",
832
+ layer=edge.layer,
833
+ position=edge.position,
834
+ feature=edge.feature,
835
+ graph_weight=edge.graph_weight,
836
+ activation=edge.activation,
837
+ write_layers=write_layers,
838
+ feature_type=feature_type,
839
+ operator="residual_hook",
840
+ covered=True,
841
+ verdict=_VERDICT_FROM_TRIAL[verdict],
842
+ native_logit_delta=effect,
843
+ graph_predicted_delta=edge.graph_predicted_delta,
844
+ graph_vs_native=classify_graph_vs_native(
845
+ edge.graph_predicted_delta, effect, rule
846
+ ),
847
+ clean_logprob=hook["clean_logprob"],
848
+ ablated_logprob=hook["ablated_logprob"],
849
+ top_token_clean=hook["top_token_clean"],
850
+ top_token_ablated=hook["top_token_ablated"],
851
+ top_token_flip=hook["top_token_flip"],
852
+ reason=reason,
853
+ reading_fingerprint=reading.fingerprint,
854
+ rule_fingerprint=rule.fingerprint,
855
+ receipt=receipt.fingerprint,
856
+ measurements=hook,
857
+ )
858
+ )
859
+ continue
860
+
861
+ rows.append(
862
+ _uncovered_row(
863
+ edge,
864
+ write_layers,
865
+ feature_type,
866
+ reading,
867
+ rule,
868
+ reason="no enabled operator covers this edge (not last position; hook disabled)",
869
+ )
870
+ )
871
+
872
+ # transcoder error nodes: carried influence with no feature direction to intervene on.
873
+ rows.append(
874
+ EdgeRow(
875
+ node_kind="error",
876
+ layer=None,
877
+ position=None,
878
+ feature=None,
879
+ graph_weight=selection.error_influence_total,
880
+ activation=None,
881
+ write_layers=(),
882
+ feature_type="transcoder-error",
883
+ operator="uncovered",
884
+ covered=False,
885
+ verdict="uncovered",
886
+ native_logit_delta=None,
887
+ clean_logprob=None,
888
+ ablated_logprob=None,
889
+ top_token_clean=None,
890
+ top_token_ablated=None,
891
+ top_token_flip=None,
892
+ reason=(
893
+ f"{selection.n_error_nodes} transcoder error nodes carry "
894
+ f"{selection.error_node_influence_share:.3f} of node influence; the error term is "
895
+ "the residual the transcoders do not reconstruct, so it has no feature direction "
896
+ "to write as a native Act"
897
+ ),
898
+ reading_fingerprint=None,
899
+ rule_fingerprint=None,
900
+ receipt=None,
901
+ measurements={
902
+ "n_error_nodes": selection.n_error_nodes,
903
+ "error_influence_total": selection.error_influence_total,
904
+ "error_node_influence_share": selection.error_node_influence_share,
905
+ },
906
+ )
907
+ )
908
+
909
+ graph_summary = {
910
+ "n_feature_nodes": selection.n_feature_nodes,
911
+ "n_error_nodes": selection.n_error_nodes,
912
+ "feature_influence_total": selection.feature_influence_total,
913
+ "error_influence_total": selection.error_influence_total,
914
+ "error_node_influence_share": selection.error_node_influence_share,
915
+ }
916
+ if graph_scores:
917
+ graph_summary["scores"] = dict(graph_scores)
918
+
919
+ table = EdgeVerdictTable(
920
+ model_identity=adapter.model_identity,
921
+ execution=dict(adapter.execution),
922
+ prompt=prompt_text,
923
+ tokens=tuple(tokens),
924
+ target_token=int(target_token),
925
+ target_text=target_text,
926
+ subject_position=subject_position,
927
+ top_k=int(top_k),
928
+ decision_rule=rule.to_dict(),
929
+ rows=tuple(rows),
930
+ graph_summary=graph_summary,
931
+ environment={
932
+ "python": platform.python_version(),
933
+ "platform": platform.platform(),
934
+ **{k: v for k, v in dict(adapter.execution.get("environment_versions", {})).items()},
935
+ },
936
+ custody=dict(store) if isinstance(store, Mapping) else {},
937
+ group_interventions=tuple(dict(g) for g in group_interventions),
938
+ )
939
+ return table
940
+
941
+
942
+ def _uncovered_row(
943
+ edge: _SelectedEdge,
944
+ write_layers: tuple[int, ...],
945
+ feature_type: str,
946
+ reading: Reading,
947
+ rule: DecisionRule,
948
+ *,
949
+ reason: str,
950
+ ) -> EdgeRow:
951
+ return EdgeRow(
952
+ node_kind="feature",
953
+ layer=edge.layer,
954
+ position=edge.position,
955
+ feature=edge.feature,
956
+ graph_weight=edge.graph_weight,
957
+ activation=edge.activation,
958
+ write_layers=write_layers,
959
+ feature_type=feature_type,
960
+ operator="uncovered",
961
+ covered=False,
962
+ verdict="uncovered",
963
+ native_logit_delta=None,
964
+ clean_logprob=None,
965
+ ablated_logprob=None,
966
+ top_token_clean=None,
967
+ top_token_ablated=None,
968
+ top_token_flip=None,
969
+ reason=reason,
970
+ reading_fingerprint=reading.fingerprint,
971
+ rule_fingerprint=rule.fingerprint,
972
+ receipt=None,
973
+ measurements={},
974
+ )
975
+
976
+
977
+ # --------------------------------------------------------------------------------------
978
+ # Offline re-derivation (stdlib only: no torch, no circuit_tracer, no model).
979
+ # --------------------------------------------------------------------------------------
980
+
981
+
982
+ def verify_edge_bundle(bundle: str | Path) -> dict[str, Any]:
983
+ """Re-derive every covered verdict in a sealed bundle from its scalars, offline.
984
+
985
+ Checks ``edge_verdicts.json`` against its ``manifest.json`` SHA-256, rebuilds the frozen
986
+ :class:`DecisionRule`, and re-grades each covered edge from its sealed
987
+ ``native_logit_delta`` with :func:`saturn.trial.grade`, confirming it reproduces the
988
+ sealed verdict. Uncovered rows (error nodes, out-of-range writes) must stay uncovered.
989
+ Stdlib only; needs no GPU, model, or ``circuit_tracer``.
990
+ """
991
+ directory = Path(bundle)
992
+ manifest = json.loads((directory / "manifest.json").read_bytes())
993
+ body = (directory / "edge_verdicts.json").read_bytes()
994
+ hash_ok = hashlib.sha256(body).hexdigest() == manifest.get("edge_verdicts.json")
995
+ table = json.loads(body)
996
+ stored_fp = table.get("fingerprint")
997
+ recomputed = dict(table)
998
+ recomputed.pop("fingerprint", None)
999
+ fingerprint_ok = digest(recomputed) == stored_fp
1000
+
1001
+ _rule_fields = {
1002
+ "name",
1003
+ "version",
1004
+ "metric",
1005
+ "present_threshold",
1006
+ "absent_threshold",
1007
+ "require_exact_gate",
1008
+ "require_sham_flat",
1009
+ "sham_metric",
1010
+ "sham_tolerance",
1011
+ "description",
1012
+ }
1013
+ rule_body = {k: v for k, v in table["decision_rule"].items() if k in _rule_fields}
1014
+ rule = DecisionRule(**rule_body)
1015
+ rule_fp_ok = rule.fingerprint == table["decision_rule"].get("fingerprint")
1016
+
1017
+ verdicts: list[dict[str, Any]] = []
1018
+ verdict_ok = True
1019
+ for row in table["rows"]:
1020
+ stored = {k: v for k, v in row.items() if k != "fingerprint"}
1021
+ if digest(stored) != row.get("fingerprint"):
1022
+ verdict_ok = False
1023
+ verdicts.append(
1024
+ {"row": _row_id(row), "ok": False, "reason": "row fingerprint mismatch"}
1025
+ )
1026
+ continue
1027
+ if not row["covered"]:
1028
+ ok = row["verdict"] == "uncovered"
1029
+ verdict_ok = verdict_ok and ok
1030
+ verdicts.append({"row": _row_id(row), "ok": ok, "derived": "uncovered"})
1031
+ continue
1032
+ reading = Reading(
1033
+ instrument="external:circuit-tracer",
1034
+ claim=row.get("reason") or "attribution edge",
1035
+ asserts_effect=True,
1036
+ source="circuit-tracer",
1037
+ )
1038
+ derived, _classification, _reason = grade(reading, rule, float(row["native_logit_delta"]))
1039
+ derived_verdict = _VERDICT_FROM_TRIAL[derived]
1040
+ derived_gvn = classify_graph_vs_native(
1041
+ row.get("graph_predicted_delta"), float(row["native_logit_delta"]), rule
1042
+ )
1043
+ ok = derived_verdict == row["verdict"] and derived_gvn == row.get("graph_vs_native")
1044
+ verdict_ok = verdict_ok and ok
1045
+ verdicts.append(
1046
+ {
1047
+ "row": _row_id(row),
1048
+ "ok": ok,
1049
+ "derived": derived_verdict,
1050
+ "stored": row["verdict"],
1051
+ "derived_graph_vs_native": derived_gvn,
1052
+ }
1053
+ )
1054
+
1055
+ group_ok = True
1056
+ group_checks: list[dict[str, Any]] = []
1057
+ for g in table.get("group_interventions", []):
1058
+ g_reading = Reading(
1059
+ instrument="external:circuit-tracer",
1060
+ claim=g.get("reason") or "group intervention",
1061
+ asserts_effect=True,
1062
+ source="circuit-tracer",
1063
+ )
1064
+ g_derived, _c, _r = grade(g_reading, rule, float(g["native_logit_delta"]))
1065
+ g_verdict = _VERDICT_FROM_TRIAL[g_derived]
1066
+ g_gvn = classify_graph_vs_native(
1067
+ g.get("graph_predicted_delta"), float(g["native_logit_delta"]), rule
1068
+ )
1069
+ ok = g_verdict == g["verdict"] and g_gvn == g.get("graph_vs_native")
1070
+ group_ok = group_ok and ok
1071
+ group_checks.append(
1072
+ {
1073
+ "group": g.get("name"),
1074
+ "ok": ok,
1075
+ "derived": g_verdict,
1076
+ "stored": g["verdict"],
1077
+ "derived_graph_vs_native": g_gvn,
1078
+ }
1079
+ )
1080
+
1081
+ return {
1082
+ "ok": bool(hash_ok and fingerprint_ok and rule_fp_ok and verdict_ok and group_ok),
1083
+ "hash_ok": bool(hash_ok),
1084
+ "fingerprint_ok": bool(fingerprint_ok),
1085
+ "rule_fingerprint_ok": bool(rule_fp_ok),
1086
+ "verdict_ok": bool(verdict_ok),
1087
+ "group_ok": bool(group_ok),
1088
+ "bundle": str(directory),
1089
+ "summary": table.get("summary"),
1090
+ "verdicts": verdicts,
1091
+ "group_checks": group_checks,
1092
+ }
1093
+
1094
+
1095
+ def _row_id(row: Mapping[str, Any]) -> str:
1096
+ if row["node_kind"] == "error":
1097
+ return "error-nodes"
1098
+ return f"L{row['layer']}/p{row['position']}/f{row['feature']}"
1099
+
1100
+
1101
+ # --------------------------------------------------------------------------------------
1102
+ # Synthetic graph for offline tests / the notebook's mechanics demo.
1103
+ # --------------------------------------------------------------------------------------
1104
+
1105
+
1106
+ @dataclass
1107
+ class _SyntheticConfig:
1108
+ n_layers: int
1109
+
1110
+
1111
+ @dataclass
1112
+ class SyntheticAttributionGraph:
1113
+ """A minimal stand-in for a circuit-tracer ``Graph`` for offline tests and examples.
1114
+
1115
+ It carries exactly the fields :func:`native_edge_test` reads, in circuit-tracer's node
1116
+ order (features, then ``n_layers * n_pos`` error nodes, then ``n_pos`` embed nodes, then
1117
+ logit nodes). No ``circuit_tracer`` import is required.
1118
+ """
1119
+
1120
+ active_features: Any
1121
+ selected_features: Any
1122
+ activation_values: Any
1123
+ adjacency_matrix: Any
1124
+ logit_probabilities: Any
1125
+ input_tokens: Any
1126
+ n_pos: int
1127
+ cfg: _SyntheticConfig
1128
+
1129
+
1130
+ def build_synthetic_graph(
1131
+ *,
1132
+ n_layers: int,
1133
+ input_tokens: Sequence[int],
1134
+ features: Sequence[tuple[int, int, int, float]],
1135
+ logit_weights: Sequence[float] = (1.0,),
1136
+ seed: int = 0,
1137
+ unselected: Sequence[tuple[int, int, int, float]] = (),
1138
+ ) -> SyntheticAttributionGraph:
1139
+ """Build a synthetic graph whose feature nodes feed the logit with decreasing influence.
1140
+
1141
+ ``features`` is a list of ``(layer, position, feature_idx, activation)``. Earlier entries
1142
+ are given larger edges to the (single) logit node so the influence ranking is
1143
+ deterministic. The adjacency matrix is wired features -> logit directly.
1144
+
1145
+ ``unselected`` adds active features that attribution did not select. As in circuit-tracer,
1146
+ ``active_features`` and ``activation_values`` then cover every active feature (unselected
1147
+ first), and ``selected_features`` indexes the selected ones within them.
1148
+ """
1149
+ import torch
1150
+
1151
+ g = torch.Generator().manual_seed(seed)
1152
+ n_pos = len(input_tokens)
1153
+ n_feat = len(features)
1154
+ n_err = n_layers * n_pos
1155
+ n_embed = n_pos
1156
+ n_logit = len(logit_weights)
1157
+ n_nodes = n_feat + n_err + n_embed + n_logit
1158
+ adjacency = torch.zeros(n_nodes, n_nodes)
1159
+ # logit node (target node row) attends to feature + error source columns
1160
+ logit_row = n_nodes - n_logit
1161
+ for i in range(n_feat):
1162
+ adjacency[logit_row, i] = float(n_feat - i) # decreasing feature influence
1163
+ # give error nodes a modest, nonzero influence so the error share is reported
1164
+ err_start = n_feat
1165
+ for j in range(n_err):
1166
+ adjacency[logit_row, err_start + j] = 0.3 + 0.01 * (torch.rand((), generator=g).item())
1167
+ every = list(unselected) + list(features)
1168
+ active = torch.tensor(
1169
+ [[layer, pos, feat] for (layer, pos, feat, _a) in every], dtype=torch.long
1170
+ )
1171
+ activation_values = torch.tensor([a for (_l, _p, _f, a) in every], dtype=torch.float32)
1172
+ n_skip = len(unselected)
1173
+ return SyntheticAttributionGraph(
1174
+ active_features=active,
1175
+ selected_features=torch.arange(n_skip, n_skip + n_feat, dtype=torch.long),
1176
+ activation_values=activation_values,
1177
+ adjacency_matrix=adjacency,
1178
+ logit_probabilities=torch.tensor(list(logit_weights), dtype=torch.float32),
1179
+ input_tokens=torch.tensor(list(input_tokens), dtype=torch.long),
1180
+ n_pos=n_pos,
1181
+ cfg=_SyntheticConfig(n_layers=n_layers),
1182
+ )
1183
+
1184
+
1185
+ __all__ = [
1186
+ "native_edge_test",
1187
+ "native_group_intervention",
1188
+ "classify_graph_vs_native",
1189
+ "verify_edge_bundle",
1190
+ "select_edges",
1191
+ "default_edge_rule",
1192
+ "EdgeRow",
1193
+ "EdgeVerdictTable",
1194
+ "GraphInfluence",
1195
+ "SyntheticAttributionGraph",
1196
+ "build_synthetic_graph",
1197
+ "DecoderWrites",
1198
+ ]