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,80 @@
|
|
|
1
|
+
"""Authority labels and labelled numbers shared by every analysis module.
|
|
2
|
+
|
|
3
|
+
``EXACT``/``LOCAL``/``BOUND``/``MEASURED``/``SUPPLIED`` are the authority vocabulary, ``num``
|
|
4
|
+
builds a labelled number ``{value, authority, proof}``, ``premise`` a checked premise, and
|
|
5
|
+
``f64``/``f64_at`` the float64 CPU casts. Torch is imported inside functions only.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from mdb.core.records import num as _record_num
|
|
14
|
+
|
|
15
|
+
EXACT = "derived-exact"
|
|
16
|
+
LOCAL = "derived-local"
|
|
17
|
+
BOUND = "bound"
|
|
18
|
+
MEASURED = "measured"
|
|
19
|
+
SUPPLIED = "supplied"
|
|
20
|
+
STATES = ("resolved", "unresolved", "refused")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _torch():
|
|
24
|
+
import torch
|
|
25
|
+
|
|
26
|
+
return torch
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def f64(x: Any) -> Any:
|
|
30
|
+
"""Float64 CPU copy of a tensor or array-like (exact for bf16/fp16/fp32 inputs).
|
|
31
|
+
|
|
32
|
+
Model weights (and slices of them) are detached; float64 tensors keep autograd tracking so a
|
|
33
|
+
caller's float64 replica can be differentiated through these functions.
|
|
34
|
+
"""
|
|
35
|
+
torch = _torch()
|
|
36
|
+
if isinstance(x, torch.Tensor) and (isinstance(x, torch.nn.Parameter)
|
|
37
|
+
or (x.requires_grad and x.dtype != torch.float64)):
|
|
38
|
+
x = x.detach()
|
|
39
|
+
if isinstance(x, torch.Tensor):
|
|
40
|
+
return x.to(device="cpu", dtype=torch.float64)
|
|
41
|
+
return torch.as_tensor(x, dtype=torch.float64)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def f64_at(x: Any, index: Any) -> Any:
|
|
45
|
+
"""``f64(x)[index]`` without casting the rest of ``x`` (index, then cast: the same values).
|
|
46
|
+
A Parameter is detached first, as ``f64`` detaches it."""
|
|
47
|
+
torch = _torch()
|
|
48
|
+
if isinstance(x, torch.nn.Parameter):
|
|
49
|
+
x = x.detach()
|
|
50
|
+
return f64(x[index])
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
AUTHORITIES = ("measured", "derived-exact", "derived-local", "bound", "supplied")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def num(value: float, authority: str, proof: str | None = None) -> dict[str, Any]:
|
|
57
|
+
"""A labelled number ``{value, authority, proof}``: ``mdb.core.records.num`` after 0-d
|
|
58
|
+
tensors and numpy scalars are unwrapped."""
|
|
59
|
+
if not isinstance(value, (bool, int, float)) and hasattr(value, "item"):
|
|
60
|
+
value = value.item() # 0-d tensors and numpy scalars
|
|
61
|
+
return _record_num(value, authority, proof=proof)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _is_finite(value: Any) -> bool:
|
|
65
|
+
try:
|
|
66
|
+
return math.isfinite(float(value))
|
|
67
|
+
except (TypeError, ValueError):
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def premise(holds: bool, value: float, tolerance: float | None, proof: str, *,
|
|
72
|
+
authority: str = MEASURED) -> dict[str, Any]:
|
|
73
|
+
"""One checked premise: ``{holds, value: num, tolerance: num | None}``.
|
|
74
|
+
|
|
75
|
+
``value`` is the checked quantity (``measured`` unless stated); ``tolerance`` is the limit the
|
|
76
|
+
check used, a constant chosen here (``supplied``), or ``None`` when no limit applies.
|
|
77
|
+
"""
|
|
78
|
+
return {"holds": bool(holds),
|
|
79
|
+
"value": num(float(value), authority, proof) if _is_finite(value) else None,
|
|
80
|
+
"tolerance": None if tolerance is None else num(float(tolerance), SUPPLIED, proof)}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Donor pooling: the labels and pooled verdict of a causal null measured over donors.
|
|
2
|
+
|
|
3
|
+
``informative`` says whether a donor's patched value differs (bitwise) from the base's,
|
|
4
|
+
``label`` is the text a reader sees (``no effect (1 donor)``, ``no effect (16 donors, 12
|
|
5
|
+
informative)``), ``stamp`` puts ``donors`` and ``label`` on a verdict and ``pooled`` pools
|
|
6
|
+
per-donor verdicts by ``RULE``. The multi-donor runners are in ``measure.donors``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from .labels import MEASURED, SUPPLIED, num
|
|
15
|
+
|
|
16
|
+
EFFECT, NO_EFFECT, UNRESOLVED = "effect", "no effect", "unresolved"
|
|
17
|
+
RULE = ("pooled over donors: effect when >= 1 donor has an effect; no effect when every donor "
|
|
18
|
+
"was measured and none had; else unresolved. informative = the donor's patched value "
|
|
19
|
+
"differs (bitwise) from the base value at the patched site")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _torch():
|
|
23
|
+
import torch
|
|
24
|
+
|
|
25
|
+
return torch
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def informative(base: Any, donor: Any) -> bool | None:
|
|
29
|
+
"""Whether the donor's value differs from the base's (bitwise, in the stored dtype); None
|
|
30
|
+
when either is missing or the shapes differ."""
|
|
31
|
+
if base is None or donor is None:
|
|
32
|
+
return None
|
|
33
|
+
torch = _torch()
|
|
34
|
+
base, donor = torch.as_tensor(base), torch.as_tensor(donor)
|
|
35
|
+
if base.shape != donor.shape and base.numel() != donor.numel():
|
|
36
|
+
return None
|
|
37
|
+
return not torch.equal(base.reshape(-1).to(donor.dtype).cpu(), donor.reshape(-1).cpu())
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def label(verdict: str, n: int = 1, k: int | None = None) -> str:
|
|
41
|
+
"""The text of a verdict with its donor count (module docstring); effects and unresolved
|
|
42
|
+
verdicts of one donor are printed as they are."""
|
|
43
|
+
if verdict != NO_EFFECT and n == 1:
|
|
44
|
+
return verdict
|
|
45
|
+
if n == 1:
|
|
46
|
+
if k == 0:
|
|
47
|
+
return f"{verdict} (1 donor, not informative: the donor value equals the base)"
|
|
48
|
+
return f"{verdict} (1 donor)"
|
|
49
|
+
shown = "informative not measured" if k is None else f"{k} informative"
|
|
50
|
+
return f"{verdict} ({n} donors, {shown})"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def stamp(effect: dict[str, Any], n: int = 1, k: int | None = None) -> dict[str, Any]:
|
|
54
|
+
"""Attach ``donors`` and ``label`` to a verdict dict (``verdict.decide``'s, or any dict with
|
|
55
|
+
a ``verdict``); returns it."""
|
|
56
|
+
effect["donors"] = {"n": num(int(n), SUPPLIED),
|
|
57
|
+
"informative": (num(int(k), MEASURED) if k is not None else
|
|
58
|
+
{"compared": False,
|
|
59
|
+
"reason": "the donor value was not compared with the "
|
|
60
|
+
"base value"})}
|
|
61
|
+
effect["label"] = label(effect["verdict"], n, k)
|
|
62
|
+
return effect
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def pooled(rows: Sequence[dict[str, Any]]) -> dict[str, Any]:
|
|
66
|
+
"""Pool per-donor verdicts. Each row: ``verdict`` and ``informative`` (bool or None), and
|
|
67
|
+
optionally ``path_diverged`` (bool). Returns the pooled verdict with its counts and label."""
|
|
68
|
+
n = len(rows)
|
|
69
|
+
verdicts = [r["verdict"] for r in rows]
|
|
70
|
+
known = [r.get("informative") for r in rows]
|
|
71
|
+
k = None if any(x is None for x in known) else sum(bool(x) for x in known)
|
|
72
|
+
n_effect = sum(v == EFFECT for v in verdicts)
|
|
73
|
+
if n_effect:
|
|
74
|
+
verdict = EFFECT
|
|
75
|
+
elif n and all(v == NO_EFFECT for v in verdicts):
|
|
76
|
+
verdict = NO_EFFECT
|
|
77
|
+
else:
|
|
78
|
+
verdict = UNRESOLVED
|
|
79
|
+
out = {"verdict": verdict, "n_donors": n, "n_informative": k, "n_effect": n_effect,
|
|
80
|
+
"n_unresolved": sum(v not in (EFFECT, NO_EFFECT) for v in verdicts),
|
|
81
|
+
"rule": RULE}
|
|
82
|
+
if any("path_diverged" in r for r in rows):
|
|
83
|
+
out["n_path_diverged"] = sum(bool(r.get("path_diverged")) for r in rows)
|
|
84
|
+
out["label"] = (f"effect ({n_effect} of {n} donors, {k} informative)" if verdict == EFFECT
|
|
85
|
+
and n > 1 else label(verdict, n, k))
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
__all__ = ["EFFECT", "NO_EFFECT", "RULE", "UNRESOLVED", "informative", "label", "pooled", "stamp"]
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Verdict stability across kernel paths: a margin rule on top of the noise floor.
|
|
2
|
+
|
|
3
|
+
The floor (``supplied.judge``: ``floor_spacings`` x the dtype spacing at the consumer's
|
|
4
|
+
magnitude, 2 spacings by default) is a noise bound: it says whether one realisation of a forward
|
|
5
|
+
moved the consumer. It does not say the verdict survives another realisation of the same forward.
|
|
6
|
+
An experiment measured, over mdb's above-floor patch effects on Qwen3-0.6B-Base and
|
|
7
|
+
Qwen2.5-0.5B, how many lose their verdict (sign reversed, or fall to or below the floor) when
|
|
8
|
+
the same forward runs another way: every loss sits at or below 4 floors, and no effect above 4 floors lost its verdict
|
|
9
|
+
(0/110 and 0/104) on any path. Any reordering moves 3-spacing verdicts: the kernel path (TL
|
|
10
|
+
batched vs mdb stepped: 60/274 Qwen3, 16/228 Qwen2.5), batch composition (TL batched vs TL
|
|
11
|
+
batch-1: 72/286, 19/241) and processing (processed vs unprocessed bridge: 46/257, 82/249). On
|
|
12
|
+
Qwen2.5 processing, not the kernel path, dominates.
|
|
13
|
+
|
|
14
|
+
``stability`` therefore marks a verdict ``stable`` only when ``|effect| > k`` floors, else
|
|
15
|
+
``kernel-sensitive`` (the verdict field itself is unchanged); ``k`` defaults to
|
|
16
|
+
``STABLE_FLOORS`` = 4 (``supplied``, from that experiment's table) or comes from a per-model
|
|
17
|
+
``Calibration`` measured by ``calibrate`` on paired effects from two realisations (e.g. mdb
|
|
18
|
+
stepped vs batched): the smallest ``k`` in floor units above which no verdict was lost, with the
|
|
19
|
+
loss table by bin. Every result names the kernel path its verdict was made on
|
|
20
|
+
(``mdb-stepped``, ``batched`` or a caller-declared string).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import math
|
|
27
|
+
from collections.abc import Iterable
|
|
28
|
+
from dataclasses import asdict, dataclass, field
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
from .labels import MEASURED, SUPPLIED, num
|
|
33
|
+
|
|
34
|
+
STABLE_FLOORS = 4.0
|
|
35
|
+
STABLE = "stable"
|
|
36
|
+
SENSITIVE = "kernel-sensitive"
|
|
37
|
+
MDB_STEPPED = "mdb-stepped"
|
|
38
|
+
BATCHED = "batched"
|
|
39
|
+
UNDECLARED = "undeclared"
|
|
40
|
+
BINS = (1.0, 1.5, 2.0, 4.0) # floor units; the last bin is open (> 4 floors)
|
|
41
|
+
STABLE_SUPPORT = ("exp6 (showcase 2026-11-14, AUDIT-SHOWCASE.md correction 1): 0/110 (Qwen3-0.6B-"
|
|
42
|
+
"Base) and 0/104 (Qwen2.5-0.5B) above-floor effects > 4 floors lost their "
|
|
43
|
+
"verdict on any path (kernel path, batch composition, processing); every loss "
|
|
44
|
+
"was <= 4 floors")
|
|
45
|
+
RULE = ("stable when |effect| > k floors, else kernel-sensitive: a verdict within k floors of zero "
|
|
46
|
+
"can move under another realisation of the same forward (kernel path, batch "
|
|
47
|
+
"composition, processing); the verdict field is unchanged")
|
|
48
|
+
SCHEMA = "mdb-verdict-stability-calibration-v1"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Calibration:
|
|
53
|
+
"""A per-model stability margin measured from paired effects of two realisations.
|
|
54
|
+
|
|
55
|
+
``k``: the smallest margin in floor units above which no verdict was lost (``measured``; at
|
|
56
|
+
least 1, the floor itself). ``table``: per bin of ``|reference effect| / floor``, the count
|
|
57
|
+
of reference effects, how many lost their verdict on the other path and how many of those
|
|
58
|
+
reversed sign. ``paths``: ``[reference, other, ...]`` kernel-path names."""
|
|
59
|
+
|
|
60
|
+
model: str
|
|
61
|
+
k: float
|
|
62
|
+
paths: list[str]
|
|
63
|
+
n: int
|
|
64
|
+
above_floor: int
|
|
65
|
+
lost: int
|
|
66
|
+
sign_reversed: int
|
|
67
|
+
table: list[dict[str, Any]] = field(default_factory=list)
|
|
68
|
+
gained: int = 0
|
|
69
|
+
source: str = ""
|
|
70
|
+
schema: str = SCHEMA
|
|
71
|
+
|
|
72
|
+
def to_json(self) -> dict[str, Any]:
|
|
73
|
+
return asdict(self)
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def from_json(cls, data: dict[str, Any]) -> Calibration:
|
|
77
|
+
if data.get("schema", SCHEMA) != SCHEMA:
|
|
78
|
+
raise ValueError(f"not a {SCHEMA} calibration: {data.get('schema')!r}")
|
|
79
|
+
return cls(**{k: data[k] for k in cls.__dataclass_fields__ if k in data})
|
|
80
|
+
|
|
81
|
+
def save(self, path: str | Path) -> Path:
|
|
82
|
+
path = Path(path)
|
|
83
|
+
path.write_text(json.dumps(self.to_json(), indent=1, sort_keys=True) + "\n")
|
|
84
|
+
return path
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def load(cls, path: str | Path) -> Calibration:
|
|
88
|
+
return cls.from_json(json.loads(Path(path).read_text()))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _bin(ratio: float, bins: tuple[float, ...]) -> str:
|
|
92
|
+
for low, high in zip(bins, bins[1:]):
|
|
93
|
+
if low < ratio <= high:
|
|
94
|
+
return f"{low:g}-{high:g}"
|
|
95
|
+
return f">{bins[-1]:g}"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def lost(reference: float, other: float, floor: float) -> bool:
|
|
99
|
+
"""The reference verdict ``effect`` (``|reference| > floor``) is lost on the other path: the
|
|
100
|
+
sign reverses or the other effect is at or below the floor."""
|
|
101
|
+
return abs(reference) > floor and (reference * other < 0 or abs(other) <= floor)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def calibrate(pairs: Iterable[tuple[float, float, float]], *, model: str,
|
|
105
|
+
paths: tuple[str, ...] | list[str] = (MDB_STEPPED, BATCHED),
|
|
106
|
+
bins: tuple[float, ...] = BINS, source: str = "") -> Calibration:
|
|
107
|
+
"""Calibrate the stability margin of one model from ``(reference, other, floor)`` triples:
|
|
108
|
+
the same effect (e.g. a patch's margin change) measured on the reference path (the one
|
|
109
|
+
verdicts are made on, e.g. mdb stepped) and on another realisation of the same forward
|
|
110
|
+
(batched, another batch composition, a processed bridge), with the floor the verdict uses.
|
|
111
|
+
Pairs from several other paths can be concatenated (name them all in ``paths``).
|
|
112
|
+
|
|
113
|
+
Returns the smallest ``k`` (floor units) above which no reference verdict is lost (``k =
|
|
114
|
+
max |reference| / floor`` over lost verdicts; 1.0 when none is lost) with the loss table by
|
|
115
|
+
bin of ``|reference| / floor`` (``bins``: edges, last bin open). ``gained`` counts reference
|
|
116
|
+
effects at or below the floor that the other path puts above it (reported, not used)."""
|
|
117
|
+
rows: dict[str, dict[str, Any]] = {}
|
|
118
|
+
order = [f"{a:g}-{b:g}" for a, b in zip(bins, bins[1:])] + [f">{bins[-1]:g}"]
|
|
119
|
+
for name in order:
|
|
120
|
+
rows[name] = {"bin": name, "n": 0, "lost": 0, "sign_reversed": 0}
|
|
121
|
+
n = above = n_lost = reversed_ = gained = 0
|
|
122
|
+
k = 1.0
|
|
123
|
+
for reference, other, floor in pairs:
|
|
124
|
+
reference, other, floor = float(reference), float(other), float(floor)
|
|
125
|
+
if not floor > 0:
|
|
126
|
+
raise ValueError("a floor must be positive")
|
|
127
|
+
n += 1
|
|
128
|
+
if abs(reference) <= floor:
|
|
129
|
+
gained += abs(other) > floor
|
|
130
|
+
continue
|
|
131
|
+
above += 1
|
|
132
|
+
ratio = abs(reference) / floor
|
|
133
|
+
row = rows[_bin(ratio, bins)]
|
|
134
|
+
row["n"] += 1
|
|
135
|
+
if lost(reference, other, floor):
|
|
136
|
+
n_lost += 1
|
|
137
|
+
row["lost"] += 1
|
|
138
|
+
k = max(k, ratio)
|
|
139
|
+
if reference * other < 0:
|
|
140
|
+
reversed_ += 1
|
|
141
|
+
row["sign_reversed"] += 1
|
|
142
|
+
return Calibration(model=model, k=k, paths=list(paths), n=n, above_floor=above, lost=n_lost,
|
|
143
|
+
sign_reversed=reversed_, table=list(rows.values()), gained=gained,
|
|
144
|
+
source=source)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _margin(calibration: Calibration | dict | str | Path | None,
|
|
148
|
+
k: float | None) -> tuple[float, str, str]:
|
|
149
|
+
"""``(k, authority, source)`` of the margin to use."""
|
|
150
|
+
if calibration is not None:
|
|
151
|
+
if isinstance(calibration, (str, Path)):
|
|
152
|
+
calibration = Calibration.load(calibration)
|
|
153
|
+
elif isinstance(calibration, dict):
|
|
154
|
+
calibration = Calibration.from_json(calibration)
|
|
155
|
+
return (float(calibration.k), MEASURED,
|
|
156
|
+
f"calibrated for {calibration.model} on {' vs '.join(calibration.paths)}")
|
|
157
|
+
if k is not None:
|
|
158
|
+
return float(k), SUPPLIED, "caller"
|
|
159
|
+
return STABLE_FLOORS, SUPPLIED, STABLE_SUPPORT
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def stability(effect: float, floor: float, *, kernel_path: str | None = None,
|
|
163
|
+
calibration: Calibration | dict | str | Path | None = None,
|
|
164
|
+
k: float | None = None) -> dict[str, Any]:
|
|
165
|
+
"""The stability of a verdict on an effect of size ``|effect|`` against ``floor``:
|
|
166
|
+
``stable`` when ``|effect| > k x floor``, else ``kernel-sensitive``. ``k`` from the model's
|
|
167
|
+
``calibration`` (a ``Calibration``, its JSON, or a path to it), else the caller's ``k``,
|
|
168
|
+
else ``STABLE_FLOORS``. ``kernel_path`` names the realisation the verdict was made on."""
|
|
169
|
+
margin, authority, source = _margin(calibration, k)
|
|
170
|
+
effect, floor = abs(float(effect)), float(floor)
|
|
171
|
+
floors = effect / floor if floor > 0 else (math.inf if effect else 0.0)
|
|
172
|
+
out: dict[str, Any] = {
|
|
173
|
+
"stability": STABLE if floors > margin else SENSITIVE,
|
|
174
|
+
"k": num(margin, authority), "k_source": source,
|
|
175
|
+
"kernel_path": kernel_path or UNDECLARED, "rule": RULE,
|
|
176
|
+
}
|
|
177
|
+
if math.isfinite(floors):
|
|
178
|
+
out["floors"] = num(floors, MEASURED)
|
|
179
|
+
return out
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
__all__ = ["BATCHED", "BINS", "Calibration", "MDB_STEPPED", "RULE", "SENSITIVE", "STABLE",
|
|
183
|
+
"STABLE_FLOORS", "STABLE_SUPPORT", "UNDECLARED", "calibrate", "lost", "stability"]
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""Statistics over the results of one op run on many prompts (``each``). Pure Python.
|
|
2
|
+
|
|
3
|
+
``claims(result)`` flattens an op result into its labelled numbers: ``path -> (value,
|
|
4
|
+
authority)`` for every ``{"value": number, "authority": ...}`` mapping (``path`` is the dotted
|
|
5
|
+
key path, list items by index: ``reads.0.mass``), and ``verdicts(result)`` its verdict and
|
|
6
|
+
state fields (``path -> text`` for string leaves under the keys ``verdict`` and ``state``).
|
|
7
|
+
|
|
8
|
+
Name keys: a list whose items are all mappings carrying a distinct
|
|
9
|
+
text ``symbol`` (``NAME_KEYS``) is walked by that name, not by position:
|
|
10
|
+
``bindings.carrier.mass``, never ``bindings.0.mass``. A symbol table's page order depends on
|
|
11
|
+
which slots bound on the item (``circuit_map.bind`` skips a slot that binds no row), so a
|
|
12
|
+
positional path would line up different symbols across items. Every other list keeps index
|
|
13
|
+
paths. ``positional=True`` restores the old paths.
|
|
14
|
+
|
|
15
|
+
``summarize_by(results, switch)`` is the ``switch`` group-by: the same statistics per value of
|
|
16
|
+
a label (a dotted path into each result, e.g. ``labels.family``), with ``n`` per group.
|
|
17
|
+
|
|
18
|
+
``summarize(results)`` takes the results of the items that ran (refused items are not passed)
|
|
19
|
+
and returns, for every path present in all of them:
|
|
20
|
+
|
|
21
|
+
* a numeric claim: ``n``, ``mean``, ``min``, ``max`` (float64, ``math.fsum`` for the mean) and
|
|
22
|
+
``agree`` (the most common sign and how many items have it). The statistics carry the
|
|
23
|
+
inputs' authority when all ``n`` inputs share it; mixed inputs are summarised per label under
|
|
24
|
+
``by_authority``, never merged into one field.
|
|
25
|
+
* a verdict/state field: a count per value.
|
|
26
|
+
|
|
27
|
+
Paths present in only some results are counted (``partial``), not summarised. A statistic is
|
|
28
|
+
arithmetic on the item values; it says nothing about prompts outside the set.
|
|
29
|
+
|
|
30
|
+
``KEY_COLUMNS`` names, per verb, the few claims a one-line-per-item table shows; another verb
|
|
31
|
+
shows its first two claims and its first verdict. It is a view, not a dispatch rule.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import math
|
|
37
|
+
import numbers
|
|
38
|
+
from typing import Any
|
|
39
|
+
|
|
40
|
+
from mdb.core.records import num
|
|
41
|
+
|
|
42
|
+
VERDICT_KEYS = ("verdict", "state")
|
|
43
|
+
NAME_KEYS = ("symbol",) # list items keyed by this field when every item has a distinct one
|
|
44
|
+
|
|
45
|
+
# verb -> alternatives, each (columns (name, path), verdict path, label path); the first
|
|
46
|
+
# alternative whose first column the result has is used (``print`` of a margin or a value)
|
|
47
|
+
KEY_COLUMNS: dict[str, tuple[tuple[tuple[tuple[str, str], ...], str | None, str | None], ...]] = {
|
|
48
|
+
"whatif": (((("native", "measured.delta"), ("exact", "prediction.exact.value")),
|
|
49
|
+
"effect.verdict", None),),
|
|
50
|
+
"reads": (((("mass", "reads.0.mass"), ("effect", "reads.0.to_consumer"),
|
|
51
|
+
("causal", "reads.0.causal.delta"),
|
|
52
|
+
("resid sp", "reads.0.causal.effect.residual_spacings")),
|
|
53
|
+
"reads.0.causal.verdict", "reads.0.name"),),
|
|
54
|
+
"print": (((("margin", "margin.value"),), None, None),
|
|
55
|
+
((("mean", "stats.mean"), ("abs_max", "stats.abs_max")), None, None)),
|
|
56
|
+
"explain": (((("margin", "explain.native_margin"), ("float64", "explain.float64_margin")),
|
|
57
|
+
None, None),),
|
|
58
|
+
"compare": (((("A", "effects.A"), ("B", "effects.B"), ("A+B", "effects.A+B")),
|
|
59
|
+
None, None),),
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _is_claim(node: Any) -> bool:
|
|
64
|
+
return (isinstance(node, dict) and "authority" in node and "value" in node
|
|
65
|
+
and isinstance(node["value"], numbers.Real) and not isinstance(node["value"], bool))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def list_keys(node: Any) -> list[str] | None:
|
|
69
|
+
"""The name keys of a list (``NAME_KEYS``): one distinct text per item, or None when the
|
|
70
|
+
list is walked by index (some item lacks the key, or two items share a name)."""
|
|
71
|
+
if not isinstance(node, (list, tuple)) or not node:
|
|
72
|
+
return None
|
|
73
|
+
for field in NAME_KEYS:
|
|
74
|
+
names = [item.get(field) if isinstance(item, dict) else None for item in node]
|
|
75
|
+
if all(isinstance(n, str) and n and "." not in n for n in names) and \
|
|
76
|
+
len(set(names)) == len(names):
|
|
77
|
+
return names
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _items(node: Any, positional: bool) -> list[tuple[str, Any]]:
|
|
82
|
+
keys = None if positional else list_keys(node)
|
|
83
|
+
if keys is None:
|
|
84
|
+
return [(str(i), item) for i, item in enumerate(node)]
|
|
85
|
+
return list(zip(keys, node))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def claims(result: Any, *, positional: bool = False) -> dict[str, tuple[float, str]]:
|
|
89
|
+
"""Every labelled number of ``result``: dotted path -> (value, authority), in order. Lists
|
|
90
|
+
of named items are walked by name (``NAME_KEYS``) unless ``positional``."""
|
|
91
|
+
out: dict[str, tuple[float, str]] = {}
|
|
92
|
+
|
|
93
|
+
def walk(node: Any, path: str) -> None:
|
|
94
|
+
if _is_claim(node):
|
|
95
|
+
out[path] = (float(node["value"]), str(node["authority"]))
|
|
96
|
+
return
|
|
97
|
+
if isinstance(node, dict):
|
|
98
|
+
for key, item in node.items():
|
|
99
|
+
walk(item, f"{path}.{key}" if path else str(key))
|
|
100
|
+
elif isinstance(node, (list, tuple)):
|
|
101
|
+
for key, item in _items(node, positional):
|
|
102
|
+
walk(item, f"{path}.{key}" if path else key)
|
|
103
|
+
|
|
104
|
+
walk(result, "")
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def verdicts(result: Any, *, positional: bool = False) -> dict[str, str]:
|
|
109
|
+
"""Every verdict/state text of ``result``: dotted path -> value, in order (named lists as
|
|
110
|
+
in ``claims``)."""
|
|
111
|
+
out: dict[str, str] = {}
|
|
112
|
+
|
|
113
|
+
def walk(node: Any, path: str) -> None:
|
|
114
|
+
if isinstance(node, dict):
|
|
115
|
+
for key, item in node.items():
|
|
116
|
+
here = f"{path}.{key}" if path else str(key)
|
|
117
|
+
if key in VERDICT_KEYS and isinstance(item, str):
|
|
118
|
+
out[here] = item
|
|
119
|
+
else:
|
|
120
|
+
walk(item, here)
|
|
121
|
+
elif isinstance(node, (list, tuple)):
|
|
122
|
+
for key, item in _items(node, positional):
|
|
123
|
+
walk(item, f"{path}.{key}" if path else key)
|
|
124
|
+
|
|
125
|
+
walk(result, "")
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _sign(value: float) -> str:
|
|
130
|
+
return "+" if value > 0 else "-" if value < 0 else "0"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _stats(values: list[float], authority: str) -> dict[str, Any]:
|
|
134
|
+
signs: dict[str, int] = {}
|
|
135
|
+
for value in values:
|
|
136
|
+
signs[_sign(value)] = signs.get(_sign(value), 0) + 1
|
|
137
|
+
sign = max(("+", "-", "0"), key=lambda s: (signs.get(s, 0), s == "+", s == "-"))
|
|
138
|
+
return {"n": len(values), "mean": num(math.fsum(values) / len(values), authority),
|
|
139
|
+
"min": num(min(values), authority), "max": num(max(values), authority),
|
|
140
|
+
"agree": {"sign": sign, "count": signs.get(sign, 0)}}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def numeric_stat(path: str, items: list[tuple[float, str]]) -> dict[str, Any]:
|
|
144
|
+
"""The statistics of one path; per authority label when the inputs carry several."""
|
|
145
|
+
labels = sorted({authority for _, authority in items})
|
|
146
|
+
if len(labels) == 1:
|
|
147
|
+
return {"path": path, **_stats([v for v, _ in items], labels[0])}
|
|
148
|
+
return {"path": path, "n": len(items), "mixed": True, "by_authority": {
|
|
149
|
+
label: _stats([v for v, a in items if a == label], label) for label in labels}}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def summarize(results: list[dict[str, Any]]) -> dict[str, Any]:
|
|
153
|
+
"""Statistics over the paths every result has (see the module docstring)."""
|
|
154
|
+
if not results:
|
|
155
|
+
return {"numeric": [], "verdicts": [], "partial": 0, "n": 0}
|
|
156
|
+
flat = [claims(result) for result in results]
|
|
157
|
+
texts = [verdicts(result) for result in results]
|
|
158
|
+
common = [path for path in flat[0] if all(path in other for other in flat[1:])]
|
|
159
|
+
every = set().union(*flat)
|
|
160
|
+
numeric = [numeric_stat(path, [found[path] for found in flat]) for path in common]
|
|
161
|
+
shared = [path for path in texts[0] if all(path in other for other in texts[1:])]
|
|
162
|
+
counted = []
|
|
163
|
+
for path in shared:
|
|
164
|
+
counts: dict[str, int] = {}
|
|
165
|
+
for found in texts:
|
|
166
|
+
counts[found[path]] = counts.get(found[path], 0) + 1
|
|
167
|
+
counted.append({"path": path, "counts": [
|
|
168
|
+
{"label": label, "count": count}
|
|
169
|
+
for label, count in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))]})
|
|
170
|
+
every_text = set().union(*texts)
|
|
171
|
+
return {"numeric": numeric, "verdicts": counted, "n": len(results),
|
|
172
|
+
"partial": (len(every) - len(common)) + (len(every_text) - len(shared))}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def leaf(result: Any, path: str) -> Any:
|
|
176
|
+
"""The value at a dotted path (list items by index, or by name for a named list as in
|
|
177
|
+
``claims``); ``KeyError`` when absent. A labelled number gives its ``value``."""
|
|
178
|
+
node = result
|
|
179
|
+
for key in path.split("."):
|
|
180
|
+
if isinstance(node, (list, tuple)):
|
|
181
|
+
if key.lstrip("-").isdigit():
|
|
182
|
+
node = node[int(key)]
|
|
183
|
+
else:
|
|
184
|
+
names = list_keys(node)
|
|
185
|
+
if names is None or key not in names:
|
|
186
|
+
raise KeyError(key)
|
|
187
|
+
node = node[names.index(key)]
|
|
188
|
+
else:
|
|
189
|
+
node = node[key]
|
|
190
|
+
return node["value"] if _is_claim(node) else node
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _value_order(key: Any) -> tuple:
|
|
194
|
+
"""A total order over JSON leaves (numbers before texts before the rest), so a tie is
|
|
195
|
+
broken by value, whatever the item order."""
|
|
196
|
+
if isinstance(key, bool):
|
|
197
|
+
return (1, int(key), "")
|
|
198
|
+
if isinstance(key, numbers.Real):
|
|
199
|
+
return (0, float(key), "")
|
|
200
|
+
if isinstance(key, str):
|
|
201
|
+
return (2, 0.0, key)
|
|
202
|
+
return (3, 0.0, repr(key))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def modes(results: list[dict[str, Any]], paths: list[str], *,
|
|
206
|
+
ties: str = "first") -> list[dict[str, Any]]:
|
|
207
|
+
"""The most common value of each dotted path over the results that have it (categorical
|
|
208
|
+
fields: a layer, a KV head, a best token): ``mode``, its ``count``, ``n`` (results with the
|
|
209
|
+
path) and every value's count. ``ties``: ``first`` breaks a tie by first appearance (depends
|
|
210
|
+
on item order); ``value`` by the smallest value (order-independent). A tie is
|
|
211
|
+
always reported (``tie``: the tied values)."""
|
|
212
|
+
if ties not in ("first", "value"):
|
|
213
|
+
raise ValueError("ties is first or value")
|
|
214
|
+
out = []
|
|
215
|
+
for path in paths:
|
|
216
|
+
counts: dict[Any, int] = {}
|
|
217
|
+
order: list[Any] = []
|
|
218
|
+
for result in results:
|
|
219
|
+
try:
|
|
220
|
+
value = leaf(result, path)
|
|
221
|
+
except (KeyError, IndexError, ValueError, TypeError):
|
|
222
|
+
continue
|
|
223
|
+
key = json_key(value)
|
|
224
|
+
if key not in counts:
|
|
225
|
+
order.append(key)
|
|
226
|
+
counts[key] = counts.get(key, 0) + 1
|
|
227
|
+
if not counts:
|
|
228
|
+
out.append({"path": path, "n": 0, "mode": None, "count": 0, "counts": []})
|
|
229
|
+
continue
|
|
230
|
+
top = max(counts.values())
|
|
231
|
+
tied = [k for k in order if counts[k] == top]
|
|
232
|
+
if ties == "value":
|
|
233
|
+
tied.sort(key=_value_order)
|
|
234
|
+
mode = tied[0]
|
|
235
|
+
listing = sorted(order, key=lambda k: (-counts[k], _value_order(k)))
|
|
236
|
+
else:
|
|
237
|
+
mode = tied[0]
|
|
238
|
+
listing = sorted(order, key=lambda k: (-counts[k], order.index(k)))
|
|
239
|
+
entry = {"path": path, "n": sum(counts.values()), "mode": mode, "count": counts[mode],
|
|
240
|
+
"counts": [{"value": k, "count": counts[k]} for k in listing]}
|
|
241
|
+
if len(tied) > 1:
|
|
242
|
+
entry["tie"] = {"values": tied, "broken_by": ties}
|
|
243
|
+
out.append(entry)
|
|
244
|
+
return out
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def summarize_by(results: list[dict[str, Any]], switch: str) -> dict[str, Any]:
|
|
248
|
+
"""``summarize`` per value of the label at the dotted path ``switch`` (a group-by): groups
|
|
249
|
+
in value order, each with its ``n``; results without the label are counted in
|
|
250
|
+
``unlabelled``. Statistics carry the inputs' labels, per group."""
|
|
251
|
+
groups: dict[Any, list[dict[str, Any]]] = {}
|
|
252
|
+
missing = 0
|
|
253
|
+
for result in results:
|
|
254
|
+
try:
|
|
255
|
+
value = leaf(result, switch)
|
|
256
|
+
except (KeyError, IndexError, ValueError, TypeError):
|
|
257
|
+
missing += 1
|
|
258
|
+
continue
|
|
259
|
+
groups.setdefault(json_key(value), []).append(result)
|
|
260
|
+
return {"switch": switch, "unlabelled": missing,
|
|
261
|
+
"groups": [{"value": key, "n": len(found), "summary": summarize(found)}
|
|
262
|
+
for key, found in sorted(groups.items(),
|
|
263
|
+
key=lambda kv: _value_order(kv[0]))]}
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def json_key(value: Any) -> Any:
|
|
267
|
+
"""A hashable form of a JSON leaf (lists become tuples)."""
|
|
268
|
+
if isinstance(value, list):
|
|
269
|
+
return tuple(json_key(v) for v in value)
|
|
270
|
+
if isinstance(value, dict):
|
|
271
|
+
return tuple(sorted((k, json_key(v)) for k, v in value.items()))
|
|
272
|
+
return value
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def key_columns(verb: str, result: dict[str, Any]) -> dict[str, Any]:
|
|
276
|
+
"""The table cells of one item: ``columns`` (name -> labelled number, or the field's state
|
|
277
|
+
and reason), ``verdict`` and ``label`` texts when the verb has them."""
|
|
278
|
+
found = claims(result)
|
|
279
|
+
texts = verdicts(result)
|
|
280
|
+
choices = KEY_COLUMNS.get(verb, ())
|
|
281
|
+
spec = next((c for c in choices if c[0][0][1] in found), choices[0] if choices else None)
|
|
282
|
+
if spec is None:
|
|
283
|
+
columns = tuple((path.rsplit(".", 1)[-1], path) for path in list(found)[:2])
|
|
284
|
+
verdict = next((p for p in texts if p.endswith("verdict")), None)
|
|
285
|
+
label = None
|
|
286
|
+
else:
|
|
287
|
+
columns, verdict, label = spec
|
|
288
|
+
out: dict[str, Any] = {"columns": {}}
|
|
289
|
+
for name, path in columns:
|
|
290
|
+
if path in found:
|
|
291
|
+
value, authority = found[path]
|
|
292
|
+
out["columns"][name] = num(value, authority)
|
|
293
|
+
else:
|
|
294
|
+
out["columns"][name] = {"state": "unresolved", "reason": f"no number at {path}"}
|
|
295
|
+
if verdict is not None and verdict in texts:
|
|
296
|
+
out["verdict"] = texts[verdict]
|
|
297
|
+
if label is not None:
|
|
298
|
+
node: Any = result
|
|
299
|
+
for part in label.split("."):
|
|
300
|
+
node = (node[int(part)] if isinstance(node, list) and part.isdigit()
|
|
301
|
+
and int(part) < len(node) else
|
|
302
|
+
node.get(part) if isinstance(node, dict) else None)
|
|
303
|
+
if isinstance(node, str):
|
|
304
|
+
out["label"] = node
|
|
305
|
+
out["paths"] = [path for _, path in columns]
|
|
306
|
+
return out
|