model-debugger 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
"""A frozen cross-item circuit map: slots that bind per item, edges between them, a consumer
|
|
2
|
+
rule, declared candidate sets and constants frozen from per-item results.
|
|
3
|
+
|
|
4
|
+
A symbol table at a cursor is a snapshot of one prompt. A map is the same schema across
|
|
5
|
+
prompts: a ``Slot`` is a rule that binds a set of cache cells on each item (``bind`` calls
|
|
6
|
+
``symbols.declare``, so the per-item object is the ordinary ``Binding`` and the partition rule
|
|
7
|
+
still holds); an ``Edge`` names how one slot reaches another (``read``: the destination's
|
|
8
|
+
heads read the source's cells; ``compose``: the answer row's MLPs; ``consume``: the margin);
|
|
9
|
+
``Map.freeze`` fills ``constants`` from the items' results with ``summary.summarize`` (numeric
|
|
10
|
+
claims and verdict counts) and ``summary.modes`` (categorical paths: a slot's layer, KV head,
|
|
11
|
+
best token). The frozen map is JSON with a sha256 (``Map.digest``), committed before any held-out
|
|
12
|
+
item is scored; ``predict``-style use binds the frozen slots on new items without refitting.
|
|
13
|
+
|
|
14
|
+
Row rules (``Slot.rows_rule``), bound per item from the item's roles (``span``: the descriptor
|
|
15
|
+
rows, ``gt``: a declared ground-truth row, ``last``: the reader row):
|
|
16
|
+
|
|
17
|
+
* ``gt``: the item's ``gt`` role;
|
|
18
|
+
* ``R_argmax``: the span row (t0 excluded) with the largest summed attention weight of the
|
|
19
|
+
reader row's heads ``rule_heads`` at layer ``rule_layer`` (read from the run, ``p``);
|
|
20
|
+
* ``R_last`` / ``R_first``: the last / first span row;
|
|
21
|
+
* ``rest``: the span rows no other slot of the map binds (whole rows).
|
|
22
|
+
|
|
23
|
+
A slot with ``layers`` and ``kv`` binds those value cells of its row(s)
|
|
24
|
+
(``cache.L<l>.v[kv<g>,row=<r>]``); without them it binds the whole rows (``t<r>``).
|
|
25
|
+
|
|
26
|
+
Cell census (``cell_census``): the content of every (row, layer, KV head) value cell at unit
|
|
27
|
+
attention mass, ``W_g v`` with ``W_g = sum_{h in kappa^-1(g)} W_O,h`` (P06/P07), read through
|
|
28
|
+
``gamma * W_U`` over candidate sets. The final ``rho`` is a positive scalar common to all cells
|
|
29
|
+
of a row's readout, so ranks and margins per unit ``rho`` are exact without it (derived-exact,
|
|
30
|
+
float64). It runs on a live run's cache or on captured V tensors alike.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import hashlib
|
|
36
|
+
import json
|
|
37
|
+
import re
|
|
38
|
+
from dataclasses import asdict, dataclass, field
|
|
39
|
+
from typing import Any
|
|
40
|
+
|
|
41
|
+
from ..numerics import summary as summ
|
|
42
|
+
from ..numerics.labels import f64
|
|
43
|
+
from ..predict.consumers import Refusal
|
|
44
|
+
from .binding import Binding, Candidates, declare, declared
|
|
45
|
+
|
|
46
|
+
ROLES = ("carrier", "descriptor", "reader", "composer", "consumer")
|
|
47
|
+
ROW_RULES = ("gt", "R_argmax", "R_last", "R_first", "rest")
|
|
48
|
+
EDGE_KINDS = ("read", "compose", "consume")
|
|
49
|
+
SCHEMA = "mdb-circuit-map-v1"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class Slot:
|
|
54
|
+
name: str
|
|
55
|
+
role: str
|
|
56
|
+
rows_rule: str
|
|
57
|
+
layers: tuple[int, ...] | None = None
|
|
58
|
+
kv: tuple[int, ...] | None = None
|
|
59
|
+
ports: tuple[str, ...] = ("v",)
|
|
60
|
+
reader_rule: str = "last"
|
|
61
|
+
rule_layer: int | None = None
|
|
62
|
+
rule_heads: tuple[int, ...] | None = None
|
|
63
|
+
|
|
64
|
+
def __post_init__(self):
|
|
65
|
+
if self.role not in ROLES:
|
|
66
|
+
raise Refusal(f"slot role {self.role!r} is not one of {ROLES}")
|
|
67
|
+
if self.rows_rule not in ROW_RULES:
|
|
68
|
+
raise Refusal(f"row rule {self.rows_rule!r} is not one of {ROW_RULES}")
|
|
69
|
+
if self.rows_rule == "R_argmax" and (self.rule_layer is None or not self.rule_heads):
|
|
70
|
+
raise Refusal("R_argmax needs rule_layer and rule_heads")
|
|
71
|
+
if (self.layers is None) != (self.kv is None):
|
|
72
|
+
raise Refusal("a cell slot gives both layers and kv; a row slot gives neither")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class Edge:
|
|
77
|
+
src: str
|
|
78
|
+
dst: str
|
|
79
|
+
kind: str
|
|
80
|
+
|
|
81
|
+
def __post_init__(self):
|
|
82
|
+
if self.kind not in EDGE_KINDS:
|
|
83
|
+
raise Refusal(f"edge kind {self.kind!r} is not one of {EDGE_KINDS}")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class LabelSymbol:
|
|
88
|
+
"""A declared label (ported from ``mdb_lanes.compiled_state.Symbol``): a finite value
|
|
89
|
+
(``cardinality`` distinct values at most) fixed by the tokens at rows up to
|
|
90
|
+
``visible_from`` (a row, or the name of an item role). A binding whose rows all lie before
|
|
91
|
+
that row cannot see the label: ``item_report`` lists it under ``hidden_labels`` instead
|
|
92
|
+
(a token position is never silently reinterpreted, the ``symbol_lifecycle`` rule)."""
|
|
93
|
+
|
|
94
|
+
name: str
|
|
95
|
+
cardinality: int | None = None
|
|
96
|
+
visible_from: int | str | None = None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class Map:
|
|
101
|
+
slots: list[Slot]
|
|
102
|
+
edges: list[Edge]
|
|
103
|
+
consumer_rule: dict[str, Any]
|
|
104
|
+
candidate_sets: dict[str, list[int]]
|
|
105
|
+
constants: dict[str, Any] = field(default_factory=dict)
|
|
106
|
+
symbols: list[LabelSymbol] = field(default_factory=list)
|
|
107
|
+
|
|
108
|
+
def __post_init__(self):
|
|
109
|
+
names = [s.name for s in self.slots]
|
|
110
|
+
if len(set(names)) != len(names):
|
|
111
|
+
raise Refusal("slot names must be distinct")
|
|
112
|
+
for e in self.edges:
|
|
113
|
+
for end in (e.src, e.dst):
|
|
114
|
+
if end not in names:
|
|
115
|
+
raise Refusal(f"edge end {end!r} is not a slot of the map")
|
|
116
|
+
|
|
117
|
+
def slot(self, name: str) -> Slot:
|
|
118
|
+
return next(s for s in self.slots if s.name == name)
|
|
119
|
+
|
|
120
|
+
def to_json(self) -> dict[str, Any]:
|
|
121
|
+
out = {"schema": SCHEMA, "slots": [asdict(s) for s in self.slots],
|
|
122
|
+
"edges": [asdict(e) for e in self.edges], "consumer_rule": self.consumer_rule,
|
|
123
|
+
"candidate_sets": self.candidate_sets, "constants": self.constants}
|
|
124
|
+
if self.symbols: # only when declared: older maps keep their digest
|
|
125
|
+
out["symbols"] = [asdict(s) for s in self.symbols]
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
def digest(self) -> str:
|
|
129
|
+
"""sha256 of the canonical JSON (sorted keys, no whitespace)."""
|
|
130
|
+
text = json.dumps(self.to_json(), sort_keys=True, separators=(",", ":"), default=str)
|
|
131
|
+
return hashlib.sha256(text.encode()).hexdigest()
|
|
132
|
+
|
|
133
|
+
@classmethod
|
|
134
|
+
def from_json(cls, data: dict[str, Any]) -> Map:
|
|
135
|
+
if data.get("schema") != SCHEMA:
|
|
136
|
+
raise Refusal(f"not a {SCHEMA} map")
|
|
137
|
+
|
|
138
|
+
def tup(x):
|
|
139
|
+
return None if x is None else tuple(x)
|
|
140
|
+
slots = [Slot(s["name"], s["role"], s["rows_rule"], tup(s["layers"]), tup(s["kv"]),
|
|
141
|
+
tuple(s["ports"]), s["reader_rule"], s["rule_layer"], tup(s["rule_heads"]))
|
|
142
|
+
for s in data["slots"]]
|
|
143
|
+
edges = [Edge(**e) for e in data["edges"]]
|
|
144
|
+
return cls(slots, edges, data["consumer_rule"], data["candidate_sets"],
|
|
145
|
+
data.get("constants", {}),
|
|
146
|
+
[LabelSymbol(**x) for x in data.get("symbols", ())])
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _reader_row(run: Any, item: dict[str, Any], rule: str) -> int:
|
|
150
|
+
if rule == "last":
|
|
151
|
+
return int(item.get("last", int(run.where.split(".")[0][1:])))
|
|
152
|
+
if rule in item:
|
|
153
|
+
return int(item[rule])
|
|
154
|
+
raise Refusal(f"reader rule {rule!r} names no role of the item")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def slot_rows(slot: Slot, run: Any, item: dict[str, Any], taken: set[int] = frozenset()) -> list[int]:
|
|
158
|
+
"""The rows ``slot`` binds on ``item`` (see the module docstring)."""
|
|
159
|
+
span = [int(r) for r in item["span"]]
|
|
160
|
+
if not span:
|
|
161
|
+
raise Refusal(f"item {item.get('name', '?')} has an empty span")
|
|
162
|
+
rule = slot.rows_rule
|
|
163
|
+
if rule == "gt":
|
|
164
|
+
if "gt" not in item:
|
|
165
|
+
raise Refusal(f"slot {slot.name}: the item has no gt role")
|
|
166
|
+
return [int(item["gt"])]
|
|
167
|
+
if rule == "R_last":
|
|
168
|
+
return [span[-1]]
|
|
169
|
+
if rule == "R_first":
|
|
170
|
+
return [span[0]]
|
|
171
|
+
if rule == "rest":
|
|
172
|
+
return [r for r in span if r not in taken]
|
|
173
|
+
reader = _reader_row(run, item, slot.reader_rule)
|
|
174
|
+
p = f64(run.read(f"t{reader}.L{slot.rule_layer}.p"))
|
|
175
|
+
p = p.reshape(p.shape[-3] if p.dim() >= 3 else 1, -1) # (heads, rows)
|
|
176
|
+
sink = {int(r) for r in item.get("sink", (0,))} # sink rows (default t0)
|
|
177
|
+
rows = [r for r in span if r not in sink]
|
|
178
|
+
if not rows:
|
|
179
|
+
raise Refusal(f"slot {slot.name}: the span holds only sink rows")
|
|
180
|
+
score = {r: float(sum(p[h, r] for h in slot.rule_heads)) for r in rows}
|
|
181
|
+
return [max(rows, key=lambda r: (score[r], r))]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def slot_addresses(slot: Slot, rows: list[int]) -> list[str]:
|
|
185
|
+
if slot.layers is None:
|
|
186
|
+
return [f"t{r}" for r in rows]
|
|
187
|
+
return [f"cache.L{layer}.{port}[kv{g},row={r}]" for r in rows for layer in slot.layers
|
|
188
|
+
for g in slot.kv for port in slot.ports]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def bind(m: Map, run: Any, item: dict[str, Any]) -> dict[str, Binding]:
|
|
192
|
+
"""Declare every slot of ``m`` on ``run`` for ``item`` (``rest`` slots last, over the rows the
|
|
193
|
+
others left). Declared symbols must not overlap, so a row slot never binds a row that holds
|
|
194
|
+
a cell slot's cells (``rest`` skips those rows). Returns slot name -> Binding; a slot that
|
|
195
|
+
binds no row is skipped (``item_report`` lists it under ``unbound_slots``). Each Binding
|
|
196
|
+
carries its slot's ``role``, ``slot`` and the map's ``map_digest``."""
|
|
197
|
+
out: dict[str, Binding] = {}
|
|
198
|
+
digest = m.digest()
|
|
199
|
+
taken: set[int] = set()
|
|
200
|
+
cell_rows: set[int] = set()
|
|
201
|
+
order = [s for s in m.slots if s.rows_rule != "rest"] + [s for s in m.slots
|
|
202
|
+
if s.rows_rule == "rest"]
|
|
203
|
+
for slot in order:
|
|
204
|
+
if slot.role in ("composer", "consumer", "reader") and slot.layers is None and \
|
|
205
|
+
slot.rows_rule != "rest":
|
|
206
|
+
continue # rule slots with no cells: not cache bindings
|
|
207
|
+
rows = slot_rows(slot, run, item, taken | cell_rows)
|
|
208
|
+
if slot.layers is None:
|
|
209
|
+
rows = [r for r in rows if r not in cell_rows]
|
|
210
|
+
if not rows:
|
|
211
|
+
continue
|
|
212
|
+
binding = declare(run, slot.name, slot_addresses(slot, rows))
|
|
213
|
+
binding.role, binding.slot, binding.map_digest = slot.role, slot.name, digest
|
|
214
|
+
out[slot.name] = binding
|
|
215
|
+
(taken if slot.layers is None else cell_rows).update(rows)
|
|
216
|
+
return out
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def cache_slots(m: Map) -> list[str]:
|
|
220
|
+
"""The slots ``bind`` declares as cache bindings (rule-only slots excluded)."""
|
|
221
|
+
return [s.name for s in m.slots
|
|
222
|
+
if not (s.role in ("composer", "consumer", "reader") and s.layers is None
|
|
223
|
+
and s.rows_rule != "rest")]
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def item_report(m: Map, run: Any, item: dict[str, Any], *, consumer: Any = None,
|
|
227
|
+
truths: dict[str, int | None] | None = None, tokenizer: Any = None,
|
|
228
|
+
content_layers: bool = False, sets: list[Any] | None = None,
|
|
229
|
+
labels: dict[str, Any] | None = None, frame: bool = False,
|
|
230
|
+
**options: Any) -> dict[str, Any]:
|
|
231
|
+
"""One item's report: bind the map's slots, then ``symbols.table`` at the cursor over the
|
|
232
|
+
declared slots only (they page first), with content over the map's candidate sets
|
|
233
|
+
(``truths``: set name -> the item's true token). The declared symbols are removed after.
|
|
234
|
+
|
|
235
|
+
``sets``: ``candidates.CandidateSet`` objects (flags, pairs) used instead of the map's
|
|
236
|
+
token lists; ``labels``: item labels (default ``item["labels"]``), carried on every row;
|
|
237
|
+
``options``: passed to ``symbols.table`` (``co``, ``lexical_null``, ``switch``, ``derive``,
|
|
238
|
+
``sink``, ``foreign``, ``causal``). The report lists ``unbound_slots`` (slots that bound no
|
|
239
|
+
row on this item) and, with ``frame``, keeps the ``Table`` under ``"_table"`` (not JSON)."""
|
|
240
|
+
from .table import table
|
|
241
|
+
|
|
242
|
+
labels = dict(item.get("labels") or {}, **(labels or {}))
|
|
243
|
+
bound = bind(m, run, item)
|
|
244
|
+
try:
|
|
245
|
+
if sets is not None:
|
|
246
|
+
cands = [s.candidates((truths or {}).get(s.name)) if hasattr(s, "candidates")
|
|
247
|
+
else s for s in sets]
|
|
248
|
+
else:
|
|
249
|
+
cands = [Candidates(name, tuple(tokens), (truths or {}).get(name))
|
|
250
|
+
for name, tokens in m.candidate_sets.items()]
|
|
251
|
+
n = max(1, len(bound))
|
|
252
|
+
tab = table(run, consumer=consumer, limit=min(n, 16), sets=cands or None,
|
|
253
|
+
content_layers=content_layers, tokenizer=tokenizer, labels=labels or None,
|
|
254
|
+
**options)
|
|
255
|
+
rows = {name: b.addresses for name, b in bound.items()}
|
|
256
|
+
tokens = [int(t) for t in run.tokens]
|
|
257
|
+
out = {"item": item.get("name"), "slots": rows, "table": tab.report,
|
|
258
|
+
"prompt_sha256": hashlib.sha256(json.dumps(tokens).encode()).hexdigest(),
|
|
259
|
+
"unbound_slots": [s for s in cache_slots(m) if s not in bound],
|
|
260
|
+
"map_digest": m.digest()}
|
|
261
|
+
if labels:
|
|
262
|
+
from .table import label_claim
|
|
263
|
+
|
|
264
|
+
out["labels"] = {k: label_claim(v) for k, v in labels.items()}
|
|
265
|
+
_hide_labels(m, item, bound, tab.report)
|
|
266
|
+
if frame:
|
|
267
|
+
out["_table"] = tab
|
|
268
|
+
return out
|
|
269
|
+
finally:
|
|
270
|
+
for name in list(bound):
|
|
271
|
+
declared(run).pop(name, None)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _hide_labels(m: Map, item: dict[str, Any], bound: dict[str, Binding],
|
|
275
|
+
report: dict[str, Any]) -> None:
|
|
276
|
+
"""Move a label off the rows of a binding that cannot see it (``LabelSymbol``)."""
|
|
277
|
+
for sym in m.symbols:
|
|
278
|
+
if sym.visible_from is None:
|
|
279
|
+
continue
|
|
280
|
+
row = sym.visible_from if isinstance(sym.visible_from, int) else item.get(sym.visible_from)
|
|
281
|
+
if row is None:
|
|
282
|
+
continue
|
|
283
|
+
for view in report.get("bindings", []):
|
|
284
|
+
binding = bound.get(view.get("symbol"))
|
|
285
|
+
if binding is None or sym.name not in view.get("labels", {}):
|
|
286
|
+
continue
|
|
287
|
+
if max(c.row for c in binding.cells) < int(row):
|
|
288
|
+
view["labels"].pop(sym.name)
|
|
289
|
+
view.setdefault("hidden_labels", []).append(sym.name)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _bindings_by_name(report: dict[str, Any]) -> dict[str, Any]:
|
|
293
|
+
"""``report`` with ``table.bindings`` re-keyed by symbol name (``table.bindings.<slot>``),
|
|
294
|
+
so cross-item statistics line up by slot even when an item's slot bound no row (``bind``
|
|
295
|
+
skips it, which would shift every later position)."""
|
|
296
|
+
table = report.get("table")
|
|
297
|
+
if not isinstance(table, dict) or not isinstance(table.get("bindings"), list):
|
|
298
|
+
return report
|
|
299
|
+
keyed = {}
|
|
300
|
+
for i, entry in enumerate(table["bindings"]):
|
|
301
|
+
name = (entry.get("symbol") or entry.get("name")) if isinstance(entry, dict) else None
|
|
302
|
+
keyed[str(name) if name is not None else f"#{i}"] = entry
|
|
303
|
+
return {**report, "table": {**table, "bindings": keyed}}
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def freeze(m: Map, reports: list[dict[str, Any]], categorical: list[str], *,
|
|
307
|
+
switch: str | None = None, ties: str = "value",
|
|
308
|
+
supplied: dict[str, Any] | None = None) -> Map:
|
|
309
|
+
"""``m`` with ``constants`` filled from per-item ``reports``: ``summary`` (numeric claims and
|
|
310
|
+
verdict counts over the paths every report has) and ``modes`` (the most common value of
|
|
311
|
+
each categorical dotted path, with counts). Table bindings are keyed by symbol name
|
|
312
|
+
(``table.bindings.<slot>.*``), never by page position. Mode ties are broken by value
|
|
313
|
+
(``ties``: first appearance depends on item order) and reported.
|
|
314
|
+
|
|
315
|
+
``switch``: a label path (``labels.family.label``, or ``labels.depth.value`` for a number): constants are also stored per switch
|
|
316
|
+
value under ``by_switch`` (the pooled ``summary`` stays the fallback for an unseen value,
|
|
317
|
+
the ``mdb_lanes.compiled_state`` rule). ``supplied``: constants measured elsewhere, each
|
|
318
|
+
``supplied_constant(...)`` (value plus the record it came from), never free text."""
|
|
319
|
+
constants = dict(m.constants)
|
|
320
|
+
keyed = [_bindings_by_name(r) for r in reports]
|
|
321
|
+
constants["summary"] = summ.summarize(keyed)
|
|
322
|
+
constants["modes"] = summ.modes(keyed, categorical, ties=ties)
|
|
323
|
+
constants["n_items"] = len(reports)
|
|
324
|
+
unbound: dict[str, int] = {}
|
|
325
|
+
for r in reports:
|
|
326
|
+
for name in r.get("unbound_slots", ()):
|
|
327
|
+
unbound[name] = unbound.get(name, 0) + 1
|
|
328
|
+
if unbound:
|
|
329
|
+
constants["unbound_slots"] = unbound
|
|
330
|
+
for sym in m.symbols:
|
|
331
|
+
if sym.cardinality is None:
|
|
332
|
+
continue
|
|
333
|
+
seen = {summ.json_key(_label(r, f"labels.{sym.name}")) for r in reports} - {None}
|
|
334
|
+
if len(seen) > sym.cardinality:
|
|
335
|
+
raise Refusal(f"label {sym.name} takes {len(seen)} values, more than its declared "
|
|
336
|
+
f"cardinality {sym.cardinality}")
|
|
337
|
+
if switch is not None:
|
|
338
|
+
constants["by_switch"] = summ.summarize_by(keyed, switch)
|
|
339
|
+
constants["switch_fallback"] = "pooled summary for an unseen switch value"
|
|
340
|
+
if supplied:
|
|
341
|
+
for name, entry in supplied.items():
|
|
342
|
+
if not isinstance(entry, dict) or "source" not in entry:
|
|
343
|
+
raise Refusal(f"supplied constant {name} needs its source record "
|
|
344
|
+
"(circuit_map.supplied_constant)")
|
|
345
|
+
constants["supplied"] = dict(supplied)
|
|
346
|
+
return Map(m.slots, m.edges, m.consumer_rule, m.candidate_sets, constants, list(m.symbols))
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def supplied_constant(value: Any, *, source: str, authority: str = "measured",
|
|
350
|
+
note: str = "") -> dict[str, Any]:
|
|
351
|
+
"""A constant measured elsewhere, with its provenance: ``source`` is the record id (or
|
|
352
|
+
sealed file sha256) it came from (``mdb_lanes.computation_atlas``: effects are
|
|
353
|
+
caller-supplied measurements with provenance)."""
|
|
354
|
+
if not isinstance(source, str) or not source.strip():
|
|
355
|
+
raise Refusal("a supplied constant names the record it came from")
|
|
356
|
+
return {"value": value, "authority": authority, "source": source, "note": note,
|
|
357
|
+
"label": "supplied"}
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
# --------------------------------------------------------------------------- MapTable
|
|
361
|
+
|
|
362
|
+
_SITE = re.compile(r"cache\.L(?P<l>\d+)\.[kv]\[kv(?P<g>\d+),row=(?P<r>\d+)\]")
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _site(report: dict[str, Any], slot: str) -> Any:
|
|
366
|
+
"""``(layer, kv, row - last)`` of a slot's first cell on this item, or ``("row", row -
|
|
367
|
+
last)`` for a row slot (positions relative to the reader row, so items of different
|
|
368
|
+
lengths compare)."""
|
|
369
|
+
addresses = (report.get("slots") or {}).get(slot) or []
|
|
370
|
+
if not addresses:
|
|
371
|
+
return None
|
|
372
|
+
last = None
|
|
373
|
+
where = (report.get("table") or {}).get("where", "")
|
|
374
|
+
if where.startswith("t"):
|
|
375
|
+
last = int(where.split(".")[0][1:])
|
|
376
|
+
match = _SITE.search(addresses[0])
|
|
377
|
+
if match:
|
|
378
|
+
r = int(match["r"])
|
|
379
|
+
return (int(match["l"]), int(match["g"]), r - last if last is not None else r)
|
|
380
|
+
if addresses[0].startswith("t") and addresses[0][1:].isdigit():
|
|
381
|
+
r = int(addresses[0][1:])
|
|
382
|
+
return ("row", r - last if last is not None else r)
|
|
383
|
+
return addresses[0]
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _binding(report: dict[str, Any], slot: str) -> dict[str, Any] | None:
|
|
387
|
+
bindings = (report.get("table") or {}).get("bindings") or []
|
|
388
|
+
if isinstance(bindings, dict):
|
|
389
|
+
return bindings.get(slot)
|
|
390
|
+
return next((b for b in bindings if isinstance(b, dict) and b.get("symbol") == slot), None)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _label(report: dict[str, Any], switch: str) -> Any:
|
|
394
|
+
try:
|
|
395
|
+
return summ.leaf(report, switch)
|
|
396
|
+
except (KeyError, IndexError, ValueError, TypeError):
|
|
397
|
+
return None
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
@dataclass
|
|
401
|
+
class MapTable:
|
|
402
|
+
"""A cross-item view of a map: one row per slot. Every row keeps the per-item
|
|
403
|
+
values behind it (``items``: item name, site, the binding row), so different native
|
|
404
|
+
locations are never silently merged (the ``mdb_lanes.symbol_trace`` safeguard)."""
|
|
405
|
+
|
|
406
|
+
rows: list[dict[str, Any]]
|
|
407
|
+
items: list[dict[str, Any]]
|
|
408
|
+
switch: str | None = None
|
|
409
|
+
|
|
410
|
+
@classmethod
|
|
411
|
+
def build(cls, m: Map, reports: list[dict[str, Any]], *, switch: str | None = None,
|
|
412
|
+
null: str | None = "answer_permutation") -> MapTable:
|
|
413
|
+
names = [s.name for s in m.slots if s.name in set(cache_slots(m))]
|
|
414
|
+
rows, items = [], []
|
|
415
|
+
for slot in m.slots:
|
|
416
|
+
if slot.name not in names:
|
|
417
|
+
continue
|
|
418
|
+
found = [(r, _binding(r, slot.name)) for r in reports]
|
|
419
|
+
bound = [(r, b) for r, b in found if b is not None]
|
|
420
|
+
row: dict[str, Any] = {"slot": slot.name, "role": slot.role, "n_items": len(reports),
|
|
421
|
+
"n_bound": len(bound)}
|
|
422
|
+
for key in ("mass", "to_consumer", "contrast", "mass_nonsink", "mask_delta"):
|
|
423
|
+
values = [(b[key]["value"], b[key]["authority"]) for _, b in bound
|
|
424
|
+
if isinstance(b.get(key), dict) and "value" in b[key]
|
|
425
|
+
and isinstance(b[key]["value"], (int, float))]
|
|
426
|
+
if values:
|
|
427
|
+
row[key] = summ.numeric_stat(key, values)
|
|
428
|
+
sites = [{"site": json.dumps(_site(r, slot.name))} for r, _ in bound]
|
|
429
|
+
mode = summ.modes(sites, ["site"], ties="value")[0]
|
|
430
|
+
row["site_mode"] = mode
|
|
431
|
+
row["baselines"] = {"constant_site": {
|
|
432
|
+
"same_site": mode["count"], "n": mode["n"],
|
|
433
|
+
"meaning": "items whose bound site (layer, kv, row - last) equals the modal "
|
|
434
|
+
"site: a rule that always picks one constant site scores the same "
|
|
435
|
+
"on these (TP1: the constant L20 KV6 site matched the forecast "
|
|
436
|
+
"174/178)"}}
|
|
437
|
+
content = {}
|
|
438
|
+
for set_name in m.candidate_sets or {}:
|
|
439
|
+
entries = [(r, (b.get("content") or {}).get(set_name)) for r, b in bound]
|
|
440
|
+
entries = [(r, e) for r, e in entries if isinstance(e, dict) and "best" in e]
|
|
441
|
+
if not entries:
|
|
442
|
+
continue
|
|
443
|
+
named = [e for _, e in entries if "names_truth" in e]
|
|
444
|
+
best_mode = summ.modes([{"best": e["best"]} for _, e in entries], ["best"],
|
|
445
|
+
ties="value")[0]
|
|
446
|
+
item = {"n": len(entries), "best_mode": best_mode}
|
|
447
|
+
if named:
|
|
448
|
+
item["names_truth"] = {"count": sum(bool(e["names_truth"]) for e in named),
|
|
449
|
+
"n": len(named)}
|
|
450
|
+
if null == "answer_permutation":
|
|
451
|
+
item["answer_permutation"] = _permutation_null(entries)
|
|
452
|
+
for other in sorted({k for _, e in entries for k in (e.get("co") or {})}):
|
|
453
|
+
projected = [(r, {**e["co"][other]["projected"],
|
|
454
|
+
**({"truth": e["truth"]} if "truth" in e else {})})
|
|
455
|
+
for r, e in entries if other in (e.get("co") or {})]
|
|
456
|
+
item.setdefault("co_permutation", {})[other] = \
|
|
457
|
+
_permutation_null(projected)
|
|
458
|
+
for flag in ("collision", "first_subword"):
|
|
459
|
+
flagged = [e for _, e in entries if (e.get("flags") or {}).get(flag)]
|
|
460
|
+
if flagged:
|
|
461
|
+
item[f"{flag}_count"] = len(flagged)
|
|
462
|
+
content[set_name] = item
|
|
463
|
+
if content:
|
|
464
|
+
row["content"] = content
|
|
465
|
+
if switch is not None:
|
|
466
|
+
groups: dict[Any, list[float]] = {}
|
|
467
|
+
for r, b in bound:
|
|
468
|
+
value = _label(r, switch)
|
|
469
|
+
tc = b.get("to_consumer")
|
|
470
|
+
if isinstance(tc, dict) and isinstance(tc.get("value"), (int, float)):
|
|
471
|
+
groups.setdefault(summ.json_key(value), []).append(
|
|
472
|
+
(tc["value"], tc["authority"]))
|
|
473
|
+
row["by_switch"] = [{"value": k, "n": len(v),
|
|
474
|
+
"to_consumer": summ.numeric_stat("to_consumer", v)}
|
|
475
|
+
for k, v in sorted(groups.items(), key=lambda kv: str(kv[0]))]
|
|
476
|
+
rows.append(row)
|
|
477
|
+
for r, b in bound:
|
|
478
|
+
items.append({"item": r.get("item"), "slot": slot.name,
|
|
479
|
+
"site": _site(r, slot.name), "binding": b,
|
|
480
|
+
"prompt_sha256": r.get("prompt_sha256"),
|
|
481
|
+
"labels": r.get("labels")})
|
|
482
|
+
return cls(rows, items, switch)
|
|
483
|
+
|
|
484
|
+
def frame(self) -> Any:
|
|
485
|
+
"""The per-item rows behind the statistics as a long DataFrame."""
|
|
486
|
+
import pandas as pd
|
|
487
|
+
|
|
488
|
+
from .frame import flatten
|
|
489
|
+
|
|
490
|
+
out = []
|
|
491
|
+
for entry in self.items:
|
|
492
|
+
row = {"item": entry["item"], "slot": entry["slot"],
|
|
493
|
+
"site": json.dumps(entry["site"])}
|
|
494
|
+
for key, value in (entry.get("labels") or {}).items():
|
|
495
|
+
row[f"item_labels.{key}"] = (value.get("label", value.get("value"))
|
|
496
|
+
if isinstance(value, dict) else value)
|
|
497
|
+
row.update(flatten(entry["binding"], skip=("readers",)))
|
|
498
|
+
out.append(row)
|
|
499
|
+
return pd.DataFrame(out)
|
|
500
|
+
|
|
501
|
+
def to_json(self) -> dict[str, Any]:
|
|
502
|
+
return {"schema": SCHEMA + "/table", "rows": self.rows, "switch": self.switch,
|
|
503
|
+
"items": [{**e, "site": e["site"]} for e in self.items]}
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _permutation_null(entries: list[tuple[dict[str, Any], dict[str, Any]]]) -> dict[str, Any]:
|
|
507
|
+
"""The answer-permutation null of ``names_truth``: the expected count when each item's best
|
|
508
|
+
is compared with the other items' truths (mean over all derangement pairs: the
|
|
509
|
+
real chance is an answer permutation, not a shuffled direction)."""
|
|
510
|
+
pairs = [(e["best"], e["truth"]) for _, e in entries if "truth" in e]
|
|
511
|
+
n = len(pairs)
|
|
512
|
+
if n < 2:
|
|
513
|
+
return {"state": "unresolved", "reason": "needs truth on at least two items "
|
|
514
|
+
"(content.<set>.truth)"}
|
|
515
|
+
hits = sum(1 for i, (b, _) in enumerate(pairs) for j, (_, t) in enumerate(pairs)
|
|
516
|
+
if i != j and b == t)
|
|
517
|
+
observed = sum(1 for b, t in pairs if b == t)
|
|
518
|
+
return {"observed": observed, "expected": hits / (n - 1), "n": n,
|
|
519
|
+
"meaning": "expected names_truth count if each item's truth were another item's"}
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
# --------------------------------------------------------------------------- cell census
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def group_writers(o_weight: Any, heads: int, kv: int) -> Any:
|
|
526
|
+
"""``W_g = sum_{h in kappa^-1(g)} W_O,h`` per KV group: (kv, d_model, head_dim) float64."""
|
|
527
|
+
torch = _torch()
|
|
528
|
+
w = f64(o_weight)
|
|
529
|
+
d_model, inner = w.shape
|
|
530
|
+
dh = inner // heads
|
|
531
|
+
per_head = w.reshape(d_model, heads, dh).permute(1, 0, 2) # (H, d, dh)
|
|
532
|
+
group = torch.arange(heads) // (heads // kv)
|
|
533
|
+
return torch.stack([per_head[group == g].sum(0) for g in range(kv)])
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def group_heads(adapter: Any, kv: int) -> tuple[int, ...]:
|
|
537
|
+
"""The query heads of KV group ``kv`` (``kappa^-1(kv)``, the grouping ``group_writers`` sums
|
|
538
|
+
over), for a per-model ``Slot(rule_heads=...)`` (experiment scripts built it by
|
|
539
|
+
hand)."""
|
|
540
|
+
heads, groups = int(adapter.num_heads), int(adapter.num_kv_heads)
|
|
541
|
+
if not 0 <= kv < groups:
|
|
542
|
+
raise Refusal(f"kv group {kv} is not in 0..{groups - 1}")
|
|
543
|
+
return tuple(h for h in range(heads) if h // (heads // groups) == kv)
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def group_writer(adapter: Any, layer: int, kv: int | None = None) -> Any:
|
|
547
|
+
"""``group_writers`` of ``layer``'s ``o_proj`` for an attached model, computed from the
|
|
548
|
+
weight as it is NOW on every call (no cache: ``.data`` edits do not bump a parameter's
|
|
549
|
+
version counter, so no cache key can see them, and the sum is one reshape): ``(kv, d_model,
|
|
550
|
+
head_dim)`` float64, or one group's ``(d_model, head_dim)`` when ``kv`` is given. Replaces
|
|
551
|
+
the per-script ``W_O`` sums."""
|
|
552
|
+
from ..measure.readout import layer_module
|
|
553
|
+
|
|
554
|
+
weight = layer_module(adapter, layer).self_attn.o_proj.weight
|
|
555
|
+
writers = group_writers(weight, adapter.num_heads, adapter.num_kv_heads)
|
|
556
|
+
return writers if kv is None else writers[kv]
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def cell_census(values: dict[int, Any], writers: dict[int, Any], rows: list[int],
|
|
560
|
+
readout_rows: dict[str, Any]) -> dict[str, Any]:
|
|
561
|
+
"""Scores of every (layer, row, KV head) value cell at unit mass over candidate sets.
|
|
562
|
+
|
|
563
|
+
``values[l]``: the layer's V cache ``(1, kv, T, dh)`` (or ``(kv, T, dh)``); ``writers[l]``:
|
|
564
|
+
``group_writers`` of the layer; ``readout_rows[name]``: ``gamma * W_U[tokens]`` (float64,
|
|
565
|
+
``(n_tokens, d_model)``). Returns name -> tensor ``(layers, rows, kv, n_tokens)`` (float64)
|
|
566
|
+
and the layer order. Exact per unit final ``rho`` (P06/P07, P19)."""
|
|
567
|
+
torch = _torch()
|
|
568
|
+
layers = sorted(values)
|
|
569
|
+
out = {}
|
|
570
|
+
for name, ro in readout_rows.items():
|
|
571
|
+
per_layer = []
|
|
572
|
+
for layer in layers:
|
|
573
|
+
v = f64(values[layer])
|
|
574
|
+
v = v.reshape(v.shape[-3], v.shape[-2], v.shape[-1]) # (kv, T, dh)
|
|
575
|
+
proj = torch.einsum("nd,gde->gne", f64(ro), f64(writers[layer])) # (kv, n, dh)
|
|
576
|
+
sel = v[:, rows, :] # (kv, R, dh)
|
|
577
|
+
per_layer.append(torch.einsum("gne,gre->rgn", proj, sel)) # (R, kv, n)
|
|
578
|
+
out[name] = torch.stack(per_layer)
|
|
579
|
+
return {"layers": layers, "rows": rows, "scores": out}
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def rank_of(scores: Any, tokens: list[int], truth: int | None) -> int | None:
|
|
583
|
+
"""1-based rank of ``truth`` among ``tokens`` (ties count against it); None if absent."""
|
|
584
|
+
if truth is None or truth not in tokens:
|
|
585
|
+
return None
|
|
586
|
+
where = tokens.index(truth)
|
|
587
|
+
return int((scores > scores[where]).sum()) + 1
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def _torch():
|
|
591
|
+
import torch
|
|
592
|
+
return torch
|