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,7 @@
|
|
|
1
|
+
"""Symbols: the symbol table (``table``) and what builds on it: candidates, liveness, binding
|
|
2
|
+
kinds (``components``, ``subspace``), the cross-item circuit map, rows and probes, sealed maps
|
|
3
|
+
and traces, and the table's dataframe form (``frame``).
|
|
4
|
+
|
|
5
|
+
Sublayer above ``circuits`` (``numerics < predict < measure < circuits < symbols < features``):
|
|
6
|
+
module-level imports reach only the sublayers up to ``symbols``.
|
|
7
|
+
"""
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Bindings: named sets of cache cells, declared on a run, and candidate token sets.
|
|
2
|
+
|
|
3
|
+
``Binding`` names the key/value cells a symbol lives in (whole rows, single cells, a feature
|
|
4
|
+
of a component or a subspace); ``declare`` records one on a run and ``declared`` lists them.
|
|
5
|
+
``Candidates`` is a named set of tokens whose readout a table scores. ``symbols.table`` builds
|
|
6
|
+
the symbol table from these.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import weakref
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from ..measure.readout import computed, first_row
|
|
16
|
+
from ..measure.reads import Source, parse_source
|
|
17
|
+
from ..predict.consumers import Refusal
|
|
18
|
+
|
|
19
|
+
_PORTS = ("k", "v")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Binding:
|
|
24
|
+
"""A named set of cache cells: ``cells`` are ``Source`` items (row, layers, KV heads,
|
|
25
|
+
ports)."""
|
|
26
|
+
|
|
27
|
+
name: str
|
|
28
|
+
kind: str
|
|
29
|
+
cells: list[Source]
|
|
30
|
+
addresses: list[str]
|
|
31
|
+
_by_row: dict[int, list[Source]] | None = field(default=None, repr=False, compare=False)
|
|
32
|
+
# the circuit-map slot that bound it (``circuit_map.bind``), and labels:
|
|
33
|
+
# ``labels[name] = (value, authority)``, supplied or derived
|
|
34
|
+
role: str | None = field(default=None, compare=False)
|
|
35
|
+
slot: str | None = field(default=None, compare=False)
|
|
36
|
+
map_digest: str | None = field(default=None, compare=False)
|
|
37
|
+
labels: dict[str, Any] = field(default_factory=dict, compare=False)
|
|
38
|
+
|
|
39
|
+
def at(self, row: int) -> list[Source]:
|
|
40
|
+
"""The cells of source row ``row`` (indexed once: a symbol can hold thousands of rows)."""
|
|
41
|
+
if self._by_row is None:
|
|
42
|
+
index: dict[int, list[Source]] = {}
|
|
43
|
+
for cell in self.cells:
|
|
44
|
+
index.setdefault(cell.row, []).append(cell)
|
|
45
|
+
self._by_row = index
|
|
46
|
+
return self._by_row.get(row, [])
|
|
47
|
+
|
|
48
|
+
def whole(self, row: int) -> bool:
|
|
49
|
+
"""Whether the binding holds every k/v cell of ``row`` (a whole-row cell ``t<row>``)."""
|
|
50
|
+
return any(c.layers is None and c.kv is None and c.ports is None for c in self.at(row))
|
|
51
|
+
|
|
52
|
+
def covers(self, row: int, layer: int, kv: int, port: str) -> bool:
|
|
53
|
+
return any(c.covers(layer, kv, port) for c in self.at(row))
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def component(cls, run: Any, name: str, cell: str, basis: Any, *,
|
|
57
|
+
features: list[int] | None = None) -> Any:
|
|
58
|
+
"""A sub-cell binding: the value cell ``cell`` split over a residual feature basis into
|
|
59
|
+
per-feature components, the decoder bias and the error (``analysis.symbols.components``). It
|
|
60
|
+
holds no cells of its own (the partition of value cells is unchanged); its components
|
|
61
|
+
add up to the cell's float64 image exactly."""
|
|
62
|
+
from .components import component_binding
|
|
63
|
+
|
|
64
|
+
return component_binding(run, name, cell, basis, features=features)
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def subspace(cls, name: str, layer: int, kv: int, basis: Any, *, authority: str = "supplied",
|
|
68
|
+
provenance: dict[str, Any] | None = None, row: int | None = None) -> Any:
|
|
69
|
+
"""A sub-cell binding: a named subspace of the value cell ``cache.L<layer>.v[kv<kv>]``
|
|
70
|
+
with its basis authority (``fitted`` / ``derived-exact`` / ``supplied``) and provenance
|
|
71
|
+
(``analysis.symbols.subspace``). It holds no cells of its own."""
|
|
72
|
+
from .subspace import subspace_binding
|
|
73
|
+
|
|
74
|
+
return subspace_binding(name, layer, kv, basis, authority=authority,
|
|
75
|
+
provenance=provenance, row=row)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
_DECLARED: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def declared(run: Any) -> dict[str, Binding]:
|
|
82
|
+
"""The user symbols declared on ``run`` in this process, by name."""
|
|
83
|
+
if run not in _DECLARED:
|
|
84
|
+
_DECLARED[run] = {}
|
|
85
|
+
return _DECLARED[run]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def declare(run: Any, name: str, addresses: list[str]) -> Binding:
|
|
89
|
+
"""Declare (or redeclare) symbol ``name`` over ``addresses``; ``Refusal`` when it overlaps
|
|
90
|
+
another declared symbol, names a row the cursor's row cannot read or is not a cache row."""
|
|
91
|
+
if not name or not name.replace("_", "").replace("-", "").isalnum() or name == "Unbound":
|
|
92
|
+
raise Refusal(f"a symbol name is letters, digits, '_' or '-' (and not Unbound), not "
|
|
93
|
+
f"{name!r}")
|
|
94
|
+
if not addresses:
|
|
95
|
+
raise Refusal("a symbol needs at least one address")
|
|
96
|
+
here = int(run.where.split(".")[0][1:])
|
|
97
|
+
cells = [parse_source(run, text) for text in addresses]
|
|
98
|
+
late = [c for c in cells if c.row > here]
|
|
99
|
+
if late:
|
|
100
|
+
raise Refusal(f"t{late[0].row} has not been computed at {run.where}")
|
|
101
|
+
for cell in cells:
|
|
102
|
+
if cell.layers is None or cell.row < first_row(run):
|
|
103
|
+
continue
|
|
104
|
+
for layer in cell.layers:
|
|
105
|
+
for port in cell.ports or _PORTS:
|
|
106
|
+
address = f"t{cell.row}.L{layer}.{port}"
|
|
107
|
+
if not computed(run, address):
|
|
108
|
+
raise Refusal(f"{address} has not been computed at {run.where}")
|
|
109
|
+
binding = Binding(name, "declared", cells, [c.text for c in cells])
|
|
110
|
+
layers, kv = run.adapter.layers, run.adapter.num_kv_heads
|
|
111
|
+
for other in declared(run).values():
|
|
112
|
+
if other.name == name:
|
|
113
|
+
continue
|
|
114
|
+
for cell in cells:
|
|
115
|
+
for layer in range(layers):
|
|
116
|
+
for k in range(kv):
|
|
117
|
+
for port in _PORTS:
|
|
118
|
+
if cell.covers(layer, k, port) and other.covers(cell.row, layer, k,
|
|
119
|
+
port):
|
|
120
|
+
raise Refusal(f"{name} overlaps symbol {other.name} at "
|
|
121
|
+
f"cache.L{layer}.{port}[kv{k},row={cell.row}]")
|
|
122
|
+
declared(run)[name] = binding
|
|
123
|
+
return binding
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass(frozen=True)
|
|
127
|
+
class Candidates:
|
|
128
|
+
"""A declared candidate token set for content readouts; ``truth`` is the token the caller
|
|
129
|
+
expects (its rank is reported), or None. ``info``: the ``candidates.CandidateSet`` it was
|
|
130
|
+
built from (words, pieces, provenance), when it was built from words."""
|
|
131
|
+
|
|
132
|
+
name: str
|
|
133
|
+
tokens: tuple[int, ...]
|
|
134
|
+
truth: int | None = None
|
|
135
|
+
info: Any = field(default=None, compare=False, repr=False)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
__all__ = ["Binding", "Candidates", "declare", "declared"]
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""First-class candidate sets for content readouts.
|
|
2
|
+
|
|
3
|
+
A ``CandidateSet`` is a supplied word list turned into token ids by a declared rule, with its
|
|
4
|
+
provenance sealed (the sha256 of the canonical word list, its source and the rule): the
|
|
5
|
+
vocabulary is supplied, never inferred, and a reader never receives an expected answer or
|
|
6
|
+
chooses a native address (the rule ported from ``mdb_lanes.symbol_sources``). Per word it
|
|
7
|
+
records the token ids of ``" " + word``, ``n_pieces``, the first piece and whether that first
|
|
8
|
+
piece is shared with another word of the same set (``collides_within``) or of another declared
|
|
9
|
+
set (``collides_across``). Token facts are structural; the flags are ``derived-exact`` (a
|
|
10
|
+
deterministic function of the tokenizer files).
|
|
11
|
+
|
|
12
|
+
``content_flags`` adds to a content readout of one set:
|
|
13
|
+
|
|
14
|
+
* ``first_subword``: the best token is the first piece of a multi-piece word of the set;
|
|
15
|
+
* ``collision``: the best token stands for more than one word of the set (``words`` lists them);
|
|
16
|
+
* ``kind``: the other declared sets that also hold the best token (e.g. the Czech country and
|
|
17
|
+
language tokens are identical, so a "names the country" count includes language wins).
|
|
18
|
+
|
|
19
|
+
Readouts beside ``content`` (all float64, linear in the write, derived-exact P19):
|
|
20
|
+
|
|
21
|
+
* ``lexical_null(source_token)``: the same readout applied to ``W_U[source_token]`` itself
|
|
22
|
+
(through the same ``gamma``): does the token's own unembedding already name the truth? A
|
|
23
|
+
``names_truth`` beside a lexical null that also names it is a test with no power
|
|
24
|
+
(46-48/48 on the capital test).
|
|
25
|
+
* ``co_readout``: read set ``S`` with a whole subspace projected out of the write: by default
|
|
26
|
+
the span of every ``gamma * W_U[t]`` of another set (``project_out``), or its top ``k``
|
|
27
|
+
principal directions. One direction is not enough: projecting out a single country
|
|
28
|
+
direction leaves the true country in the write, so the default is
|
|
29
|
+
the whole span. Reports ``raw``, ``projected``, ``lexical_null`` (the readout of the removed
|
|
30
|
+
part alone: the projection of the write onto the subspace) and ``counts`` = projected names
|
|
31
|
+
the truth and the removed part alone does not. The projection is ``supplied`` (the caller
|
|
32
|
+
chose the subspace) and says so in ``premises``.
|
|
33
|
+
* ``switched``: the truth of set ``S`` made a function of the decoded token of another set
|
|
34
|
+
(``switch``): rank the capital of the country the write names, not the item's true capital
|
|
35
|
+
(the 2.7 switched readout; ``pairs`` maps the other set's word to this set's word).
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import hashlib
|
|
41
|
+
import json
|
|
42
|
+
from dataclasses import dataclass, field
|
|
43
|
+
from pathlib import Path
|
|
44
|
+
from typing import Any
|
|
45
|
+
|
|
46
|
+
from ..numerics.labels import EXACT, SUPPLIED, f64, num
|
|
47
|
+
from ..predict.consumers import Refusal
|
|
48
|
+
|
|
49
|
+
SCHEMA = "mdb-candidate-set-v1"
|
|
50
|
+
RULES = ("first", "single")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _torch():
|
|
54
|
+
import torch
|
|
55
|
+
|
|
56
|
+
return torch
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class CandidateSet:
|
|
61
|
+
"""A supplied word list as token ids (module docstring). ``pieces[i]`` are the ids of
|
|
62
|
+
``" " + words[i]``; ``tokens[i]`` its first piece (the id a readout ranks)."""
|
|
63
|
+
|
|
64
|
+
name: str
|
|
65
|
+
words: tuple[str, ...]
|
|
66
|
+
pieces: tuple[tuple[int, ...], ...]
|
|
67
|
+
rule: str = "first"
|
|
68
|
+
source: str = "supplied"
|
|
69
|
+
pairs: dict[str, str] = field(default_factory=dict, compare=False)
|
|
70
|
+
across: dict[int, tuple[str, ...]] = field(default_factory=dict, compare=False)
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def tokens(self) -> tuple[int, ...]:
|
|
74
|
+
return tuple(p[0] for p in self.pieces)
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def sha256(self) -> str:
|
|
78
|
+
text = json.dumps({"schema": SCHEMA, "name": self.name, "words": list(self.words),
|
|
79
|
+
"rule": self.rule}, sort_keys=True, separators=(",", ":"))
|
|
80
|
+
return hashlib.sha256(text.encode()).hexdigest()
|
|
81
|
+
|
|
82
|
+
def token(self, word: str) -> int:
|
|
83
|
+
if word not in self.words:
|
|
84
|
+
raise Refusal(f"{word!r} is not a word of candidate set {self.name}")
|
|
85
|
+
return self.pieces[self.words.index(word)][0]
|
|
86
|
+
|
|
87
|
+
def words_of(self, token: int) -> list[str]:
|
|
88
|
+
return [w for w, p in zip(self.words, self.pieces) if p[0] == int(token)]
|
|
89
|
+
|
|
90
|
+
def collides_within(self, word: str) -> bool:
|
|
91
|
+
return len(self.words_of(self.token(word))) > 1
|
|
92
|
+
|
|
93
|
+
def multi_piece(self, token: int) -> bool:
|
|
94
|
+
return any(p[0] == int(token) and len(p) > 1 for p in self.pieces)
|
|
95
|
+
|
|
96
|
+
def candidates(self, truth: Any = None) -> Any:
|
|
97
|
+
"""The ``symbols.Candidates`` of this set; ``truth`` a word of the set or a token id."""
|
|
98
|
+
from .binding import Candidates
|
|
99
|
+
|
|
100
|
+
if isinstance(truth, str):
|
|
101
|
+
truth = self.token(truth)
|
|
102
|
+
return Candidates(self.name, self.tokens, None if truth is None else int(truth),
|
|
103
|
+
info=self)
|
|
104
|
+
|
|
105
|
+
def describe(self) -> dict[str, Any]:
|
|
106
|
+
"""Record-safe provenance: name, size, rule, source, sha256 and per-set flag counts."""
|
|
107
|
+
within = sum(1 for w in self.words if self.collides_within(w))
|
|
108
|
+
multi = sum(1 for p in self.pieces if len(p) > 1)
|
|
109
|
+
return {"name": self.name, "size": len(self.words), "rule": self.rule,
|
|
110
|
+
"source": self.source, "sha256": self.sha256,
|
|
111
|
+
"words_collide_within": within, "multi_piece_words": multi,
|
|
112
|
+
"first_tokens_shared_across": sum(1 for t in set(self.tokens) if t in self.across),
|
|
113
|
+
"authority": "structural (tokenizer); flags derived-exact"}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def build(name: str, words: list[str], tokenizer: Any, *, rule: str = "first",
|
|
117
|
+
source: str = "supplied", pairs: dict[str, str] | None = None) -> CandidateSet:
|
|
118
|
+
"""Tokenise ``" " + word`` for each word (``rule``: ``first`` keeps multi-piece words and
|
|
119
|
+
ranks their first piece; ``single`` refuses them)."""
|
|
120
|
+
if rule not in RULES:
|
|
121
|
+
raise Refusal(f"rule is one of {RULES}, not {rule!r}")
|
|
122
|
+
words = [str(w) for w in words]
|
|
123
|
+
if len(words) < 2 or len(set(words)) != len(words) or any(not w.strip() for w in words):
|
|
124
|
+
raise Refusal(f"candidate set {name} needs at least two distinct non-empty words")
|
|
125
|
+
if tokenizer is None:
|
|
126
|
+
raise Refusal("a candidate set from words needs a tokenizer (give token ids instead)")
|
|
127
|
+
pieces = []
|
|
128
|
+
for word in words:
|
|
129
|
+
ids = tuple(int(i) for i in tokenizer.encode(" " + word, add_special_tokens=False))
|
|
130
|
+
if not ids:
|
|
131
|
+
raise Refusal(f"{word!r} encodes to no token")
|
|
132
|
+
if rule == "single" and len(ids) != 1:
|
|
133
|
+
raise Refusal(f"rule=single: {word!r} is {len(ids)} tokens")
|
|
134
|
+
pieces.append(ids)
|
|
135
|
+
return CandidateSet(name, tuple(words), tuple(pieces), rule, source, dict(pairs or {}))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def from_tokens(name: str, tokens: list[int], words: list[str] | None = None, *,
|
|
139
|
+
source: str = "supplied") -> CandidateSet:
|
|
140
|
+
"""A set given as token ids (one piece each); ``words`` default to ``#<id>``."""
|
|
141
|
+
words = list(words) if words is not None else [f"#{int(t)}" for t in tokens]
|
|
142
|
+
if len(words) != len(tokens):
|
|
143
|
+
raise Refusal("words and tokens differ in length")
|
|
144
|
+
return CandidateSet(name, tuple(words), tuple((int(t),) for t in tokens), "first", source)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def cross(sets: list[CandidateSet]) -> list[CandidateSet]:
|
|
148
|
+
"""The sets with ``across`` filled: per first token, the other sets that hold it."""
|
|
149
|
+
holders: dict[int, list[str]] = {}
|
|
150
|
+
for s in sets:
|
|
151
|
+
for t in set(s.tokens):
|
|
152
|
+
holders.setdefault(t, []).append(s.name)
|
|
153
|
+
out = []
|
|
154
|
+
for s in sets:
|
|
155
|
+
across = {t: tuple(n for n in holders[t] if n != s.name) for t in set(s.tokens)
|
|
156
|
+
if len(holders[t]) > 1}
|
|
157
|
+
out.append(CandidateSet(s.name, s.words, s.pieces, s.rule, s.source, dict(s.pairs),
|
|
158
|
+
across))
|
|
159
|
+
return out
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def pair(target: CandidateSet, on: CandidateSet) -> CandidateSet:
|
|
163
|
+
"""``target`` with ``pairs`` from parallel word lists: ``on.words[i] -> target.words[i]``."""
|
|
164
|
+
if len(target.words) != len(on.words):
|
|
165
|
+
raise Refusal(f"sets {on.name} and {target.name} are not parallel ({len(on.words)} vs "
|
|
166
|
+
f"{len(target.words)} words)")
|
|
167
|
+
return CandidateSet(target.name, target.words, target.pieces, target.rule, target.source,
|
|
168
|
+
dict(zip(on.words, target.words)), dict(target.across))
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def load(path: str, name: str, tokenizer: Any, *, rule: str = "first") -> CandidateSet:
|
|
172
|
+
"""A set from a file: a JSON list of words, ``{"words": [...], "pairs": {...}}``, or text
|
|
173
|
+
with one word per line."""
|
|
174
|
+
text = Path(path).expanduser().read_text()
|
|
175
|
+
pairs = None
|
|
176
|
+
try:
|
|
177
|
+
data = json.loads(text)
|
|
178
|
+
except json.JSONDecodeError:
|
|
179
|
+
data = [line.strip() for line in text.splitlines() if line.strip()]
|
|
180
|
+
if isinstance(data, dict):
|
|
181
|
+
pairs = data.get("pairs")
|
|
182
|
+
data = data.get("words", [])
|
|
183
|
+
return build(name, list(data), tokenizer, rule=rule, source=str(path), pairs=pairs)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
# --------------------------------------------------------------------------- readouts
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _rank(scores: Any, tokens: tuple[int, ...], truth: int | None) -> dict[str, Any]:
|
|
190
|
+
order = scores.argsort(descending=True)
|
|
191
|
+
best, second = int(order[0]), int(order[1])
|
|
192
|
+
out: dict[str, Any] = {"best": tokens[best],
|
|
193
|
+
"margin": num(float(scores[best] - scores[second]), EXACT, "P19")}
|
|
194
|
+
if truth is not None and truth in tokens:
|
|
195
|
+
where = tokens.index(truth)
|
|
196
|
+
out["truth_rank"] = int((scores > scores[where]).sum()) + 1
|
|
197
|
+
out["names_truth"] = tokens[best] == truth
|
|
198
|
+
return out
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _rows(run: Any, tokens: tuple[int, ...], gamma: Any) -> Any:
|
|
202
|
+
"""``gamma * W_U[tokens]`` (n, d) float64 (rows sliced, then cast)."""
|
|
203
|
+
torch = _torch()
|
|
204
|
+
weight = run.adapter.model.lm_head.weight
|
|
205
|
+
index = torch.tensor(list(tokens), dtype=torch.long, device=weight.device)
|
|
206
|
+
return f64(weight.index_select(0, index)).cpu() * gamma
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def content_flags(cand: Any, best: int, sets: list[Any]) -> dict[str, Any]:
|
|
210
|
+
"""``first_subword``, ``collision`` and ``kind`` of a best token (module docstring)."""
|
|
211
|
+
info = getattr(cand, "info", None)
|
|
212
|
+
words = info.words_of(best) if info is not None else []
|
|
213
|
+
kind = sorted({c.name for c in sets if c.name != cand.name and best in c.tokens})
|
|
214
|
+
out: dict[str, Any] = {"collision": len(words) > 1, "kind": kind,
|
|
215
|
+
"authority": "derived-exact (tokenizer)"}
|
|
216
|
+
if info is not None:
|
|
217
|
+
out["first_subword"] = info.multi_piece(best)
|
|
218
|
+
out["words"] = words[:8]
|
|
219
|
+
else:
|
|
220
|
+
out["first_subword"] = None
|
|
221
|
+
out["note"] = "token-id set: no word pieces known (declare it with words)"
|
|
222
|
+
truth = getattr(cand, "truth", None)
|
|
223
|
+
if truth is not None:
|
|
224
|
+
out["truth_collides"] = info is not None and len(info.words_of(truth)) > 1
|
|
225
|
+
out["truth_kind"] = sorted({c.name for c in sets if c.name != cand.name
|
|
226
|
+
and truth in c.tokens})
|
|
227
|
+
return out
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def lexical_null(run: Any, cand: Any, source_token: int, basis: tuple[float, Any]) -> dict:
|
|
231
|
+
"""The readout of ``W_U[source_token]`` through the same ``rho * gamma`` (module doc)."""
|
|
232
|
+
rho, gamma = basis
|
|
233
|
+
weight = run.adapter.model.lm_head.weight
|
|
234
|
+
direction = f64(weight[int(source_token)]).cpu().reshape(-1)
|
|
235
|
+
scores = rho * (_rows(run, cand.tokens, gamma) @ direction)
|
|
236
|
+
return {**_rank(scores, cand.tokens, cand.truth), "source_token": int(source_token),
|
|
237
|
+
"meaning": "the readout of the source token's own unembedding row: does lexical "
|
|
238
|
+
"similarity alone name the truth?"}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@dataclass(frozen=True)
|
|
242
|
+
class CoReadout:
|
|
243
|
+
"""Read set ``target`` with the span of set ``project_out`` (or ``tokens``) removed;
|
|
244
|
+
``k``: keep only the top-k principal directions of that span (None: the whole span)."""
|
|
245
|
+
|
|
246
|
+
target: str
|
|
247
|
+
project_out: str | None = None
|
|
248
|
+
tokens: tuple[int, ...] | None = None
|
|
249
|
+
k: int | None = None
|
|
250
|
+
|
|
251
|
+
def text(self) -> str:
|
|
252
|
+
what = self.project_out or f"{len(self.tokens or ())} tokens"
|
|
253
|
+
return f"{self.target} with span({what}){'' if self.k is None else f' top-{self.k}'} " \
|
|
254
|
+
"projected out"
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def subspace(run: Any, tokens: tuple[int, ...], gamma: Any, k: int | None = None) -> Any:
|
|
258
|
+
"""An orthonormal basis ``Q`` (d, r) of ``span(gamma * W_U[tokens])`` (rank-revealing SVD,
|
|
259
|
+
float64), or its top-``k`` right singular directions."""
|
|
260
|
+
torch = _torch()
|
|
261
|
+
rows = _rows(run, tuple(dict.fromkeys(tokens)), gamma)
|
|
262
|
+
_, s, vh = torch.linalg.svd(rows, full_matrices=False)
|
|
263
|
+
keep = int((s > s[0] * rows.shape[1] * 2.0 ** -52).sum()) if s.numel() else 0
|
|
264
|
+
if k is not None:
|
|
265
|
+
keep = min(keep, int(k))
|
|
266
|
+
return vh[:keep].T.contiguous()
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def co_readout(run: Any, write: Any, cand: Any, q: Any, basis: tuple[float, Any],
|
|
270
|
+
spec: CoReadout) -> dict[str, Any]:
|
|
271
|
+
"""Raw, projected and removed-part readouts of ``cand`` (module docstring)."""
|
|
272
|
+
rho, gamma = basis
|
|
273
|
+
w = f64(write).reshape(-1).cpu()
|
|
274
|
+
inside = q @ (q.T @ w)
|
|
275
|
+
outside = w - inside
|
|
276
|
+
rows = _rows(run, cand.tokens, gamma)
|
|
277
|
+
raw = _rank(rho * (rows @ w), cand.tokens, cand.truth)
|
|
278
|
+
projected = _rank(rho * (rows @ outside), cand.tokens, cand.truth)
|
|
279
|
+
removed = _rank(rho * (rows @ inside), cand.tokens, cand.truth)
|
|
280
|
+
out: dict[str, Any] = {
|
|
281
|
+
"raw": raw, "projected": projected, "lexical_null": removed,
|
|
282
|
+
"rank": int(q.shape[1]),
|
|
283
|
+
"removed_norm_share": num(float(inside.norm() / w.norm()) if float(w.norm()) else 0.0,
|
|
284
|
+
EXACT),
|
|
285
|
+
"projection": {"text": spec.text(), "authority": SUPPLIED},
|
|
286
|
+
"premises": ["the subspace is supplied by the caller (project_out / tokens / k); it is "
|
|
287
|
+
"removed from the write and so from every candidate's score",
|
|
288
|
+
"lexical_null reads the removed part alone"]}
|
|
289
|
+
if "names_truth" in projected:
|
|
290
|
+
out["counts"] = bool(projected["names_truth"]) and not bool(removed.get("names_truth"))
|
|
291
|
+
return out
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def switched(cand: Any, on: dict[str, Any], on_set: Any, scores_fn: Any) -> dict[str, Any]:
|
|
295
|
+
"""The readout of ``cand`` with its truth switched on the decoded token of ``on_set``
|
|
296
|
+
(``on``: that set's content entry). ``scores_fn(tokens)``: the write's scores."""
|
|
297
|
+
info = getattr(cand, "info", None)
|
|
298
|
+
on_info = getattr(on_set, "info", None)
|
|
299
|
+
if info is None or on_info is None or not info.pairs:
|
|
300
|
+
return {"state": "unresolved", "reason": f"switch needs word pairs {on_set.name} -> "
|
|
301
|
+
f"{cand.name} (candidates ... paired=)"}
|
|
302
|
+
decoded_words = on_info.words_of(on["best"])
|
|
303
|
+
targets = [info.pairs[w] for w in decoded_words if w in info.pairs]
|
|
304
|
+
if not targets:
|
|
305
|
+
return {"state": "unresolved", "reason": f"the decoded {on_set.name} token has no pair "
|
|
306
|
+
f"in {cand.name}"}
|
|
307
|
+
truth = info.token(targets[0])
|
|
308
|
+
scores = scores_fn(cand.tokens)
|
|
309
|
+
out = _rank(scores, cand.tokens, truth)
|
|
310
|
+
out.update({"on": on_set.name, "decoded": on["best"], "decoded_words": decoded_words[:4],
|
|
311
|
+
"truth": truth, "truth_word": targets[0],
|
|
312
|
+
"ambiguous": len(set(targets)) > 1,
|
|
313
|
+
"meaning": f"rank of the {cand.name} word paired with the {on_set.name} word the "
|
|
314
|
+
"write names (not the item's truth)"})
|
|
315
|
+
return out
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
__all__ = ["CandidateSet", "CoReadout", "RULES", "SCHEMA", "build", "co_readout",
|
|
319
|
+
"content_flags", "cross", "from_tokens", "lexical_null", "load", "pair", "subspace",
|
|
320
|
+
"switched"]
|