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,454 @@
|
|
|
1
|
+
"""Pools: sealed value sets collected at one address over a prompt set.
|
|
2
|
+
|
|
3
|
+
Leave-one-out means and donor picking were hand-coded again and again in driver scripts; one
|
|
4
|
+
hit a self-inclusion bug and the hop-math ``mean_cell(exclude=...)`` argument was dead code.
|
|
5
|
+
A ``Pool`` is "values taken from other runs" as one debugger object with provenance:
|
|
6
|
+
|
|
7
|
+
pool = collect(dbg, items, "cache.L20.v[kv6,row=@carrier]", labels=("country",),
|
|
8
|
+
where=lambda item, run: item["correct"], name="carrier-v")
|
|
9
|
+
pool.mean_for(item) # leave-one-out mean: the item is never in it
|
|
10
|
+
pool.class_mean_for(item, by="country") # same-label mean, item excluded
|
|
11
|
+
pool.donor(item, rule="other:country") # first other-label item in pool order
|
|
12
|
+
pool.random(item, seed=0) # Gaussian, norm matched to the item's own value
|
|
13
|
+
pool.seal() # a ``pool`` record: items digest, origins, payload
|
|
14
|
+
|
|
15
|
+
Every value a pool hands out is an ``engine.refs.ValueRef`` whose pointer names the pool (its
|
|
16
|
+
sealed record id once sealed), the rule, and exactly which items went in (``items`` and
|
|
17
|
+
``excluded``), so ``Run.set(addr, pool.mean_for(item))`` or a ``Branches`` arm records where an
|
|
18
|
+
edit value came from. Means are float64 over the stored native values (cast once to the model
|
|
19
|
+
dtype when an edit stages it).
|
|
20
|
+
|
|
21
|
+
Collection (``collect``): one run per item (``Run`` of the item's token ids), stepped until the
|
|
22
|
+
address is computed; ``@role`` in the address is the item's role row (``item["roles"][role]`` or
|
|
23
|
+
``item[role]``), ``@last`` the last prompt row. A port occurrence's row is stepped (prefill =
|
|
24
|
+
that row); a cache cell is read at the last row's first port (rows before it are the prefill's).
|
|
25
|
+
``where(item, run)`` (after the read) filters items; the skipped ids are recorded. Each item keeps
|
|
26
|
+
its origin pointer (address, value sha256, cut). Values are stored as the native dtype's exact
|
|
27
|
+
float values in a sha256-checked JSON payload (``core.bounded.put_json``; held on the pool with
|
|
28
|
+
no project store; ``save``/``load`` write and verify a file).
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import hashlib
|
|
34
|
+
import json
|
|
35
|
+
import re
|
|
36
|
+
from collections.abc import Callable, Sequence
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from typing import Any
|
|
39
|
+
|
|
40
|
+
from mdb.core.bounded import load_json, put_json
|
|
41
|
+
from mdb.core.kinds import POOL # noqa: F401 (declares the kind)
|
|
42
|
+
from mdb.core.records import seal_record
|
|
43
|
+
|
|
44
|
+
from ..numerics.labels import EXACT, MEASURED, f64, num
|
|
45
|
+
from ..predict.consumers import Refusal
|
|
46
|
+
|
|
47
|
+
SCHEMA = "mdb-pool-v1"
|
|
48
|
+
_ROLE = re.compile(r"@(\w+)")
|
|
49
|
+
_CAP = 64
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _torch():
|
|
53
|
+
import torch
|
|
54
|
+
|
|
55
|
+
return torch
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _role_row(item: dict[str, Any], role: str) -> int:
|
|
59
|
+
if role == "last":
|
|
60
|
+
return len(item["ids"]) - 1
|
|
61
|
+
roles = item.get("roles") or {}
|
|
62
|
+
value = roles.get(role, item.get(role))
|
|
63
|
+
if isinstance(value, (list, tuple)):
|
|
64
|
+
value = value[0] if len(value) == 1 else None
|
|
65
|
+
if not isinstance(value, int):
|
|
66
|
+
raise Refusal(f"item {item.get('id')!r} has no row for role @{role}")
|
|
67
|
+
return value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def bind(address: str, item: dict[str, Any]) -> str:
|
|
71
|
+
"""``address`` with every ``@role`` replaced by the item's row (``t@last`` -> ``t<last>``)."""
|
|
72
|
+
return _ROLE.sub(lambda m: str(_role_row(item, m.group(1))), address)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Pool:
|
|
76
|
+
"""Values at one address, one per item, with origins (module docstring)."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, name: str, address: str, items: list[dict[str, Any]], values: Any,
|
|
79
|
+
*, skipped: Sequence[Any] = (), model_identity: Any = None,
|
|
80
|
+
execution: dict[str, Any] | None = None, labels: Sequence[str] = ()):
|
|
81
|
+
torch = _torch()
|
|
82
|
+
self.name, self.address = name, address
|
|
83
|
+
self.items = items # {id, address, origin, labels}
|
|
84
|
+
self.values = values.detach().to("cpu") if isinstance(values, torch.Tensor) else values
|
|
85
|
+
self.skipped = list(skipped)
|
|
86
|
+
self.model_identity, self.execution = model_identity, dict(execution or {})
|
|
87
|
+
self.labels = tuple(labels)
|
|
88
|
+
self.record: dict[str, Any] | None = None
|
|
89
|
+
self._index = {str(it["id"]): i for i, it in enumerate(items)}
|
|
90
|
+
if len(self._index) != len(items):
|
|
91
|
+
raise Refusal("pool item ids must be unique")
|
|
92
|
+
|
|
93
|
+
# --- identity -------------------------------------------------------------------------
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def ids(self) -> list[str]:
|
|
97
|
+
return [str(it["id"]) for it in self.items]
|
|
98
|
+
|
|
99
|
+
def items_sha256(self, ids: Sequence[str] | None = None) -> str:
|
|
100
|
+
chosen = self.ids if ids is None else list(ids)
|
|
101
|
+
return hashlib.sha256(json.dumps(chosen, separators=(",", ":")).encode()).hexdigest()
|
|
102
|
+
|
|
103
|
+
def payload(self) -> dict[str, Any]:
|
|
104
|
+
return {"schema": SCHEMA, "dtype": str(self.values.dtype).removeprefix("torch."),
|
|
105
|
+
"shape": list(self.values.shape[1:]), "ids": self.ids,
|
|
106
|
+
"labels": [it.get("labels") or {} for it in self.items],
|
|
107
|
+
"tokens_sha256": [(it.get("origin") or {}).get("tokens_sha256")
|
|
108
|
+
for it in self.items],
|
|
109
|
+
"values": f64(self.values).reshape(len(self.items), -1).tolist()}
|
|
110
|
+
|
|
111
|
+
def __len__(self) -> int:
|
|
112
|
+
return len(self.items)
|
|
113
|
+
|
|
114
|
+
def value(self, item: Any) -> Any:
|
|
115
|
+
return self.values[self._position(item)]
|
|
116
|
+
|
|
117
|
+
def _position(self, item: Any) -> int:
|
|
118
|
+
key = str(item["id"] if isinstance(item, dict) else item)
|
|
119
|
+
if key not in self._index:
|
|
120
|
+
raise Refusal(f"item {key!r} is not in pool {self.name}")
|
|
121
|
+
return self._index[key]
|
|
122
|
+
|
|
123
|
+
def _label(self, item: Any, by: str) -> Any:
|
|
124
|
+
if isinstance(item, dict) and by in ((item.get("labels") or {}).keys() | item.keys()):
|
|
125
|
+
return (item.get("labels") or {}).get(by, item.get(by)) # nested labels win
|
|
126
|
+
return self.items[self._position(item)]["labels"].get(by)
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def kernel_path(self) -> str:
|
|
130
|
+
"""``mdb-prefill-batched`` for cache-cell pools (read from the batched prefill; the
|
|
131
|
+
per-item ``origin.prefill`` is recorded), else ``mdb-stepped``; ``mdb-stepped`` too for a
|
|
132
|
+
cache-cell pool collected with ``prefill=`` splits before every item's cell row."""
|
|
133
|
+
if getattr(self, "_kernel_path", None):
|
|
134
|
+
return self._kernel_path
|
|
135
|
+
return "mdb-prefill-batched" if self.address.startswith("cache.") else "mdb-stepped"
|
|
136
|
+
|
|
137
|
+
def duplicates(self) -> int:
|
|
138
|
+
"""Items whose prompt tokens equal an earlier item's (by ``tokens_sha256``)."""
|
|
139
|
+
seen = [(it.get("origin") or {}).get("tokens_sha256") for it in self.items]
|
|
140
|
+
return len([h for i, h in enumerate(seen) if h is not None and h in seen[:i]])
|
|
141
|
+
|
|
142
|
+
def _excluded(self, item: Any, exclude: str) -> set[int]:
|
|
143
|
+
"""Positions that must not feed ``item``'s value: its own id and, when ``exclude`` is
|
|
144
|
+
``"tokens"`` (default), every item with the same prompt tokens under another id (a
|
|
145
|
+
duplicated prompt would put the item's own value in its leave-one-out mean)."""
|
|
146
|
+
if exclude not in ("id", "tokens"):
|
|
147
|
+
raise Refusal("exclude is 'id' or 'tokens'")
|
|
148
|
+
key = str(item["id"] if isinstance(item, dict) else item)
|
|
149
|
+
out = {self._index[key]} if key in self._index else set()
|
|
150
|
+
if exclude == "tokens":
|
|
151
|
+
sha = None
|
|
152
|
+
if isinstance(item, dict) and item.get("ids") is not None:
|
|
153
|
+
sha = hashlib.sha256(json.dumps([int(t) for t in item["ids"]]).encode()
|
|
154
|
+
).hexdigest()
|
|
155
|
+
elif key in self._index:
|
|
156
|
+
sha = (self.items[self._index[key]].get("origin") or {}).get("tokens_sha256")
|
|
157
|
+
if sha is not None:
|
|
158
|
+
out |= {i for i, it in enumerate(self.items)
|
|
159
|
+
if (it.get("origin") or {}).get("tokens_sha256") == sha}
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
# --- values handed out ------------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
def _ref(self, value: Any, rule: str, used: list[str], excluded: str | None,
|
|
165
|
+
**extra: Any) -> Any:
|
|
166
|
+
from mdb.engine.ports import tensor_digest
|
|
167
|
+
from mdb.engine.refs import ValueRef
|
|
168
|
+
|
|
169
|
+
pointer = {"kind": "pool", "origin": f"pool:{self.name}", "pool": self.name,
|
|
170
|
+
"record": None if self.record is None else self.record["id"],
|
|
171
|
+
"address": self.address, "rule": rule, "n": len(used),
|
|
172
|
+
"items_sha256": self.items_sha256(used), "excluded": excluded,
|
|
173
|
+
"sha256": tensor_digest(value), "shape": list(value.shape), **extra}
|
|
174
|
+
if len(used) <= 16:
|
|
175
|
+
pointer["items"] = list(used)
|
|
176
|
+
return ValueRef(value, pointer)
|
|
177
|
+
|
|
178
|
+
def _mean(self, keep: list[int], rule: str, excluded: str | None, **extra: Any) -> Any:
|
|
179
|
+
if not keep:
|
|
180
|
+
raise Refusal(f"pool {self.name}: no item left for the {rule}")
|
|
181
|
+
torch = _torch()
|
|
182
|
+
index = torch.tensor(keep, dtype=torch.long)
|
|
183
|
+
value = f64(self.values.index_select(0, index)).mean(0)
|
|
184
|
+
return self._ref(value, rule, [self.ids[i] for i in keep], excluded, **extra)
|
|
185
|
+
|
|
186
|
+
def mean(self) -> Any:
|
|
187
|
+
"""The mean over every item: the value for an item OUTSIDE the pool. For an item of the
|
|
188
|
+
pool use ``mean_for`` (it is excluded by construction)."""
|
|
189
|
+
return self._mean(list(range(len(self))), "mean of all items", None)
|
|
190
|
+
|
|
191
|
+
def mean_for(self, item: Any, *, exclude: str = "tokens") -> Any:
|
|
192
|
+
"""Leave-one-out mean: every item but ``item`` (excluded by construction; an item not
|
|
193
|
+
in the pool gets the full mean, ``excluded`` None). ``exclude="tokens"`` (default) also
|
|
194
|
+
drops items with the same prompt tokens under another id; ``"id"`` drops only the id."""
|
|
195
|
+
key = str(item["id"] if isinstance(item, dict) else item)
|
|
196
|
+
gone = self._excluded(item, exclude)
|
|
197
|
+
keep = [i for i in range(len(self)) if i not in gone]
|
|
198
|
+
own = {self._index[key]} if key in self._index else set()
|
|
199
|
+
return self._mean(keep, "leave-one-out mean", key if key in self._index else None,
|
|
200
|
+
exclude=exclude, duplicates_dropped=len(gone - own))
|
|
201
|
+
|
|
202
|
+
def class_mean_for(self, item: Any, *, by: str, exclude: str = "tokens") -> Any:
|
|
203
|
+
"""Mean over the items with ``item``'s label ``by``, ``item`` excluded."""
|
|
204
|
+
key = str(item["id"] if isinstance(item, dict) else item)
|
|
205
|
+
label = self._label(item, by)
|
|
206
|
+
gone = self._excluded(item, exclude)
|
|
207
|
+
keep = [i for i, it in enumerate(self.items)
|
|
208
|
+
if it["labels"].get(by) == label and i not in gone]
|
|
209
|
+
return self._mean(keep, f"same-{by} mean, item excluded", key if key in self._index
|
|
210
|
+
else None, label={by: label}, exclude=exclude)
|
|
211
|
+
|
|
212
|
+
def donor(self, item: Any, *, rule: str = "other", order: Sequence[str] | None = None,
|
|
213
|
+
exclude: str = "tokens") -> Any:
|
|
214
|
+
"""One other item's value: ``rule`` ``any`` (any other item), ``same:<label>`` (same
|
|
215
|
+
label) or ``other:<label>`` (another label); the first eligible item in ``order``
|
|
216
|
+
(default: pool order) that is not ``item``."""
|
|
217
|
+
key = str(item["id"] if isinstance(item, dict) else item)
|
|
218
|
+
kind, _, by = rule.partition(":")
|
|
219
|
+
if kind not in ("any", "same", "other") or (kind != "any" and not by):
|
|
220
|
+
raise Refusal("donor rule is any, same:<label> or other:<label>")
|
|
221
|
+
label = None if kind == "any" else self._label(item, by)
|
|
222
|
+
gone = self._excluded(item, exclude)
|
|
223
|
+
for donor_id in (order or self.ids):
|
|
224
|
+
if str(donor_id) == key or str(donor_id) not in self._index \
|
|
225
|
+
or self._index[str(donor_id)] in gone:
|
|
226
|
+
continue
|
|
227
|
+
labels = self.items[self._index[str(donor_id)]]["labels"]
|
|
228
|
+
if kind == "same" and labels.get(by) != label:
|
|
229
|
+
continue
|
|
230
|
+
if kind == "other" and labels.get(by) == label:
|
|
231
|
+
continue
|
|
232
|
+
position = self._index[str(donor_id)]
|
|
233
|
+
ref = self._ref(self.values[position].clone(), f"donor ({rule})", [str(donor_id)],
|
|
234
|
+
key if key in self._index else None, donor=str(donor_id))
|
|
235
|
+
ref.pointer["donor_origin"] = self.items[position]["origin"]
|
|
236
|
+
return ref
|
|
237
|
+
raise Refusal(f"pool {self.name}: no donor for {key!r} under rule {rule!r}")
|
|
238
|
+
|
|
239
|
+
def donors(self, item: Any, n: int, *, seed: int = 0, exclude: str = "tokens") -> list[Any]:
|
|
240
|
+
"""``n`` other items' values for ``item`` (multi-donor mode, ``analysis.measure.donors``): a
|
|
241
|
+
seeded draw without replacement over the items ``item`` may take from (itself and, by
|
|
242
|
+
default, same-token duplicates excluded); fewer when the pool has fewer."""
|
|
243
|
+
import random
|
|
244
|
+
|
|
245
|
+
key = str(item["id"] if isinstance(item, dict) else item)
|
|
246
|
+
gone = self._excluded(item, exclude)
|
|
247
|
+
eligible = [i for i in range(len(self)) if i not in gone]
|
|
248
|
+
chosen = sorted(random.Random(int(seed)).sample(eligible, min(int(n), len(eligible))))
|
|
249
|
+
out = []
|
|
250
|
+
for position in chosen:
|
|
251
|
+
ref = self._ref(self.values[position].clone(), f"donor (draw of {n}, seed {seed})",
|
|
252
|
+
[self.ids[position]], key if key in self._index else None,
|
|
253
|
+
donor=self.ids[position])
|
|
254
|
+
ref.pointer["donor_origin"] = self.items[position]["origin"]
|
|
255
|
+
out.append(ref)
|
|
256
|
+
return out
|
|
257
|
+
|
|
258
|
+
def random(self, item: Any = None, *, norm: float | None = None, seed: int = 0) -> Any:
|
|
259
|
+
"""A seeded Gaussian of the pool's value shape (float64), rescaled to ``norm`` or to the
|
|
260
|
+
norm of ``item``'s own value (matched-norm random)."""
|
|
261
|
+
torch = _torch()
|
|
262
|
+
if norm is None:
|
|
263
|
+
if item is None:
|
|
264
|
+
raise Refusal("random needs norm= or an item whose norm it matches")
|
|
265
|
+
norm = float(f64(self.value(item)).norm())
|
|
266
|
+
g = torch.randn(tuple(self.values.shape[1:]),
|
|
267
|
+
generator=torch.Generator().manual_seed(int(seed)), dtype=torch.float64)
|
|
268
|
+
g = g * (float(norm) / float(g.norm()))
|
|
269
|
+
key = None if item is None else str(item["id"] if isinstance(item, dict) else item)
|
|
270
|
+
return self._ref(g, "matched-norm Gaussian", [], key, seed=int(seed),
|
|
271
|
+
norm=num(float(norm), EXACT))
|
|
272
|
+
|
|
273
|
+
# --- records ----------------------------------------------------------------------------
|
|
274
|
+
|
|
275
|
+
def seal(self, *, session_id: str | None = None, store: Any = None) -> dict[str, Any]:
|
|
276
|
+
"""A ``pool`` record: address, items (ids, labels, origins; first 64), items digest,
|
|
277
|
+
skipped ids, the values payload (sha256-checked JSON) and custody."""
|
|
278
|
+
from mdb.core.custody import custody
|
|
279
|
+
|
|
280
|
+
payload = put_json(self.payload(), store=store, run=self)
|
|
281
|
+
shown = [{"id": str(it["id"]), "labels": it["labels"],
|
|
282
|
+
"origin": {k: it["origin"][k] for k in ("address", "sha256", "cut", "prefill")
|
|
283
|
+
if k in it["origin"]}}
|
|
284
|
+
for it in self.items[:_CAP]]
|
|
285
|
+
body = {"schema": SCHEMA, "name": self.name, "address": self.address,
|
|
286
|
+
"n": len(self.items), "shape": list(self.values.shape[1:]),
|
|
287
|
+
"dtype": str(self.values.dtype).removeprefix("torch."),
|
|
288
|
+
"items": shown, "items_omitted": max(0, len(self.items) - _CAP),
|
|
289
|
+
"items_sha256": self.items_sha256(), "skipped": [str(s) for s in
|
|
290
|
+
self.skipped[:_CAP]],
|
|
291
|
+
"labels": list(self.labels), "payload": payload,
|
|
292
|
+
"norms": {"mean": num(float(f64(self.values).reshape(len(self), -1).norm(dim=1)
|
|
293
|
+
.mean()), MEASURED)} if len(self) else {},
|
|
294
|
+
"duplicates": self.duplicates(),
|
|
295
|
+
"custody": custody(self.kernel_path)}
|
|
296
|
+
session = session_id or "mdb-pool:" + self.items_sha256()[:32]
|
|
297
|
+
self.record = seal_record(session_id=session, kind="pool",
|
|
298
|
+
model_identity=self.model_identity,
|
|
299
|
+
execution=self.execution, authority=MEASURED, body=body,
|
|
300
|
+
run=[it["origin"]["from_checkpoint"] for it in self.items
|
|
301
|
+
if it["origin"].get("from_checkpoint")])
|
|
302
|
+
return self.record
|
|
303
|
+
|
|
304
|
+
def save(self, path: str | Path) -> Path:
|
|
305
|
+
"""Write ``{record, payload, items}`` as JSON (seals first if needed)."""
|
|
306
|
+
record = self.record or self.seal()
|
|
307
|
+
path = Path(path)
|
|
308
|
+
path.write_text(json.dumps({"record": record, "payload": self.payload(),
|
|
309
|
+
"items": self.items}, default=str))
|
|
310
|
+
return path
|
|
311
|
+
|
|
312
|
+
@classmethod
|
|
313
|
+
def load(cls, path: str | Path) -> Pool:
|
|
314
|
+
"""Read a saved pool, checking the record seal and the payload sha256."""
|
|
315
|
+
from mdb.core.bounded import json_bytes
|
|
316
|
+
from mdb.core.records import verify_record
|
|
317
|
+
|
|
318
|
+
torch = _torch()
|
|
319
|
+
data = json.loads(Path(path).read_text())
|
|
320
|
+
record = verify_record(data["record"])
|
|
321
|
+
payload = data["payload"]
|
|
322
|
+
if hashlib.sha256(json_bytes(payload)).hexdigest() != record["body"]["payload"]["sha256"]:
|
|
323
|
+
raise Refusal("pool payload differs from its sealed sha256")
|
|
324
|
+
items = data["items"]
|
|
325
|
+
if [str(it["id"]) for it in items] != [str(i) for i in payload["ids"]]:
|
|
326
|
+
raise Refusal("pool items differ from the payload ids (order or content): refused, "
|
|
327
|
+
"the leave-one-out mean would use the wrong rows")
|
|
328
|
+
body = record["body"]
|
|
329
|
+
if hashlib.sha256(json.dumps([str(i) for i in payload["ids"]], separators=(",", ":"))
|
|
330
|
+
.encode()).hexdigest() != body["items_sha256"]:
|
|
331
|
+
raise Refusal("pool ids differ from the sealed items_sha256")
|
|
332
|
+
for it, label in zip(items, payload.get("labels", [None] * len(items))):
|
|
333
|
+
if label is not None and (it.get("labels") or {}) != label:
|
|
334
|
+
raise Refusal(f"pool item {it['id']!r} labels differ from the sealed payload")
|
|
335
|
+
for it, sha in zip(items, payload.get("tokens_sha256", [None] * len(items))):
|
|
336
|
+
if sha is not None and (it.get("origin") or {}).get("tokens_sha256") != sha:
|
|
337
|
+
raise Refusal(f"pool item {it['id']!r} tokens digest differs from the payload")
|
|
338
|
+
dtype = getattr(torch, payload["dtype"])
|
|
339
|
+
values = torch.tensor(payload["values"], dtype=torch.float64).reshape(
|
|
340
|
+
len(payload["ids"]), *payload["shape"]).to(dtype)
|
|
341
|
+
pool = cls(record["body"]["name"], record["body"]["address"], items, values,
|
|
342
|
+
skipped=record["body"]["skipped"], model_identity=record["model_identity"],
|
|
343
|
+
execution=record["execution"], labels=record["body"]["labels"])
|
|
344
|
+
pool.record = record
|
|
345
|
+
return pool
|
|
346
|
+
|
|
347
|
+
def held_payload(self) -> Any:
|
|
348
|
+
"""The payload the record points at, read back and checked (``bounded.load_json``)."""
|
|
349
|
+
if self.record is None:
|
|
350
|
+
raise Refusal("seal the pool first")
|
|
351
|
+
return load_json(self.record["body"]["payload"], run=self)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def collect(debugger: Any, items: Sequence[dict[str, Any]], address: str, *,
|
|
355
|
+
name: str = "pool", labels: Sequence[str] = (),
|
|
356
|
+
where: Callable[[dict[str, Any], Any], bool] | None = None,
|
|
357
|
+
prefill: Callable[[dict[str, Any]], int] | None = None) -> Pool:
|
|
358
|
+
"""Collect one value per item at ``address`` (module docstring). ``items``: dicts with
|
|
359
|
+
``id``, ``ids`` (token ids), optional ``roles`` and the ``labels`` keys; or ``core`` (alias
|
|
360
|
+
``from``) instead of ``ids``: a checkpoint (path, record id of the debugger's project, or a
|
|
361
|
+
loaded one) the item's run is rehydrated from, no prefix recomputed. ``prefill`` (cache
|
|
362
|
+
cells only): ``prefill(item)`` is the item's prefill split, so the rows from it on are
|
|
363
|
+
stepped (the kernel path of a driver that ran ``dbg.run(ids, prefill=K)``); the pool's
|
|
364
|
+
kernel path is ``mdb-stepped`` when every item's cell row is at or after its split."""
|
|
365
|
+
from mdb.engine.run import Run
|
|
366
|
+
|
|
367
|
+
torch = _torch()
|
|
368
|
+
adapter = debugger.adapter if hasattr(debugger, "adapter") else debugger
|
|
369
|
+
kept, values, skipped = [], [], []
|
|
370
|
+
stepped = prefill is not None
|
|
371
|
+
loaded: dict[str, Any] = {}
|
|
372
|
+
for item in items:
|
|
373
|
+
core = item.get("core", item.get("from"))
|
|
374
|
+
if core is not None:
|
|
375
|
+
run, ids = _from_checkpoint(debugger, item, core, loaded)
|
|
376
|
+
bound = bind(address, {**item, "ids": ids})
|
|
377
|
+
last = len(ids) - 1
|
|
378
|
+
if bound.startswith("cache."):
|
|
379
|
+
cell_row = re.search(r"row=(\d+)", bound)
|
|
380
|
+
stepped = stepped and cell_row is not None and int(cell_row[1]) >= run.first_row
|
|
381
|
+
target = f"t{last}.L0.{run.program.names[0]}"
|
|
382
|
+
if run.parse(target) > run.parse(run.where):
|
|
383
|
+
run.until(target)
|
|
384
|
+
else:
|
|
385
|
+
_reach(run, bound.partition("[")[0])
|
|
386
|
+
else:
|
|
387
|
+
bound = bind(address, item)
|
|
388
|
+
ids = [int(t) for t in item["ids"]]
|
|
389
|
+
last = len(ids) - 1
|
|
390
|
+
if bound.startswith("cache."):
|
|
391
|
+
split = None if prefill is None else int(prefill(item))
|
|
392
|
+
run = Run(adapter, ids, prefill=split)
|
|
393
|
+
cell_row = re.search(r"row=(\d+)", bound)
|
|
394
|
+
stepped = stepped and cell_row is not None and int(cell_row[1]) >= int(
|
|
395
|
+
run.prefill)
|
|
396
|
+
run.until(f"t{last}.L0.{run.program.names[0]}")
|
|
397
|
+
else:
|
|
398
|
+
row = int(bound.split(".", 1)[0][1:]) if bound.startswith("t") else last
|
|
399
|
+
run = Run(adapter, ids, prefill=min(row, last))
|
|
400
|
+
run.until(bound.partition("[")[0])
|
|
401
|
+
run.name = f"{name}:{item['id']}"
|
|
402
|
+
ref = run.ref(bound)
|
|
403
|
+
if where is not None and not where(item, run):
|
|
404
|
+
skipped.append(item["id"])
|
|
405
|
+
continue
|
|
406
|
+
kept.append({"id": str(item["id"]), "address": bound,
|
|
407
|
+
"labels": {k: (item.get("labels") or {}).get(k, item.get(k)) for k in labels},
|
|
408
|
+
"origin": {**ref.pointer, "prefill": int(run.prefill), "tokens_sha256": hashlib.sha256(
|
|
409
|
+
json.dumps(ids).encode()).hexdigest(),
|
|
410
|
+
**({"checkpoint": run.core["record"],
|
|
411
|
+
"from_checkpoint": dict(run.from_checkpoint)}
|
|
412
|
+
if core is not None else {})}})
|
|
413
|
+
values.append(ref.value.detach().to("cpu"))
|
|
414
|
+
if not kept:
|
|
415
|
+
raise Refusal(f"pool {name}: no item kept (skipped {len(skipped)})")
|
|
416
|
+
stacked = torch.stack(values)
|
|
417
|
+
pool = Pool(name, address, kept, stacked, skipped=skipped,
|
|
418
|
+
model_identity=adapter.model_identity, execution=dict(adapter.execution),
|
|
419
|
+
labels=labels)
|
|
420
|
+
if stepped and address.startswith("cache."):
|
|
421
|
+
pool._kernel_path = "mdb-stepped"
|
|
422
|
+
return pool
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _from_checkpoint(debugger: Any, item: dict[str, Any], core: Any,
|
|
426
|
+
loaded: dict[str, Any]) -> tuple[Any, list[int]]:
|
|
427
|
+
"""A run of the item's checkpoint (``core`` / ``from``: a path, a record id of the
|
|
428
|
+
debugger's project or a loaded checkpoint), rehydrated with no prefix recompute, and its
|
|
429
|
+
token ids (the item's ``ids``, when given, must be the checkpoint's prompt)."""
|
|
430
|
+
from mdb.engine import checkpoint as states
|
|
431
|
+
|
|
432
|
+
adapter = debugger.adapter if hasattr(debugger, "adapter") else debugger
|
|
433
|
+
key = core if isinstance(core, str) else id(core)
|
|
434
|
+
found = loaded.get(key)
|
|
435
|
+
if found is None:
|
|
436
|
+
found = loaded[key] = states.load(core, project=getattr(debugger, "project", None))
|
|
437
|
+
run = found.run(adapter, check=False)
|
|
438
|
+
ids = [int(t) for t in found.prompt]
|
|
439
|
+
if "ids" in item and [int(t) for t in item["ids"]] != ids:
|
|
440
|
+
raise Refusal(f"pool item {item.get('id')!r}: its ids differ from its checkpoint's "
|
|
441
|
+
"prompt")
|
|
442
|
+
return run, ids
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _reach(run: Any, target: str) -> None:
|
|
446
|
+
"""Move ``run`` to ``target`` forwards (``until``) or backwards (``rewind``)."""
|
|
447
|
+
key, here = run.parse(target), run.parse(run.where)
|
|
448
|
+
if key > here:
|
|
449
|
+
run.until(target)
|
|
450
|
+
elif key < here:
|
|
451
|
+
run.rewind(target)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
__all__ = ["Pool", "SCHEMA", "bind", "collect"]
|