File size: 10,272 Bytes
e9dac18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/env python3
"""Fault injection: how many conversational nodes does the assurance ceiling need?

For every configuration (a subset of the eight nodes) and every fault of the catalogue
(``lgstratum/faults.py``) a probe set of the corpus is run in memory with the very same node code
the orchestrator runs. A run is *activated* when the injected fault really changed a node. Each
activated run is then measured against the honest result of the same item, and ends in one of:

  raised       : the fault pushed the shown assurance above the honest ceiling -- an invariant
                 violation, and the only outcome this topology is not allowed to produce
  lowered      : the answer stayed what the gold asked but the confidence dropped: another node
                 compensated by withdrawing certainty, which is the designed reaction
  masked       : the gold still holds at the same assurance, because the fault changed nothing
                 that the referee reads
  abstained    : the layer withdrew the answer entirely (assurance zero) while the gold expected one
  caught       : an answer was shown that the gold does not accept, but the session pointed at its
                 own gap: a claim fell to the referee of its node, or the assurance sits below the
                 honest one because the configuration itself lost a node
  silent_error : a wrong answer presented with confidence while nothing in the session said so

Usage:  python math-stratum/tools/ablation.py [--probe N] [--all] [--out math-stratum/results/ablation.json]
"""

import argparse
import json
import sys
import time
from pathlib import Path
from typing import Any, Dict, List, Tuple

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from lgstratum import agents, corpus, faults, pipeline  # noqa: E402

FULL = list(agents.ORDER)
OUT = ROOT / "results" / "ablation.json"

CONFIGS: Dict[str, List[str]] = {
    "S1 reader_a": ["reader_a"],
    "S2 +reader_b": ["reader_a", "reader_b"],
    "S3 +equivalence": ["reader_a", "reader_b", "equivalence"],
    "S4 +coverage": ["reader_a", "reader_b", "equivalence", "coverage"],
    "S5 +invoker": ["reader_a", "reader_b", "equivalence", "coverage", "invoker"],
    "S6 +boundary": FULL[:6],
    "S7 +adversary": FULL[:7],
    "S8 full topology": FULL,
}
for _node in FULL:
    CONFIGS["S8 minus %s" % _node] = [node for node in FULL if node != _node]


def single_faults(active: List[str]) -> List[Tuple[str, ...]]:
    # Not every node has a fault to commit: the invoker reads nothing and proves nothing.
    return [("%s:%s" % (node, kind),) for node in active for kind in faults.CATALOG.get(node, [])]


def multi_faults() -> List[Tuple[str, ...]]:
    """The pairs that matter here: both readers wrong in the same way, and certainty forced on
    top of a reading that no longer holds."""
    out: List[Tuple[str, ...]] = [
        ("reader_a:merge_slots", "reader_b:merge_slots"),
        ("reader_a:shift_number", "reader_b:shift_number"),
        ("reader_a:drop_marker", "reader_b:drop_marker"),
        ("equivalence:rubber_stamp", "coverage:rubber_stamp"),
        ("boundary:tamper_math", "arbiter:force_assurance"),
        ("reader_a:shift_number", "equivalence:rubber_stamp"),
        ("reader_a:merge_slots", "arbiter:force_assurance"),
        ("boundary:tamper_math", "adversary:rubber_stamp", "arbiter:force_assurance"),
    ]
    return [spec for spec in out if all(part.split(":")[0] in faults.CATALOG for part in spec)]


def honest(item: Dict[str, Any]) -> Dict[str, Any]:
    """The baseline the injected runs are measured against: no fault, full topology."""
    faults.configure([])
    result = pipeline.ask(item["question"], item["lang"], active=FULL)
    grade = corpus.grade(item, result)
    return {"ok": bool(grade["ok"]), "assurance": int(result["final"].get("assurance", 0)),
            "state": str(result["final"].get("state", "NONE")), "problems": grade["problems"]}


def flagged(result: Dict[str, Any]) -> bool:
    """Did the session itself point at the problem: a claim that did not survive its own referee."""
    final = result.get("final") or {}
    if final.get("detected"):
        return True
    return any(record["claimed"] != record["referee"] for record in result.get("records") or [])


def classify(base: Dict[str, Any], item: Dict[str, Any], result: Dict[str, Any]) -> str:
    """What an injected fault ended up doing to what the layer shows.

    ``raised`` is the violation the tool exists to look for. ``silent_error`` is the narrower thing it
    is supposed to prevent: a wrong answer was shown, and nothing in the session said so. When a
    envelope claim fell to its referee, or the assurance sits below the honest one because the
    topology itself was weakened, the run is ``caught``: the layer still answered, but it pointed at
    its own gap.
    """
    shown = int(result["final"].get("assurance", 0))
    grade = corpus.grade(item, result)
    if shown > base["assurance"]:
        return "raised"
    if grade["ok"]:
        return "lowered" if shown < base["assurance"] else "masked"
    if shown == 0:
        return "abstained"
    return "caught" if (flagged(result) or shown < base["assurance"]) else "silent_error"


def run_cell(items: List[Dict[str, Any]], active: List[str], spec: Tuple[str, ...],
             base: Dict[str, Dict[str, Any]], config: str = "") -> Dict[str, Any]:
    tally = {"runs": 0, "activated": 0, "raised": 0, "lowered": 0, "masked": 0, "caught": 0,
             "abstained": 0, "silent_error": 0, "details": []}
    for item in items:
        # The session itself has to carry the fault: asking for it beforehand is not enough, because
        # a session configures the faults it was given and leaves the others off.
        result = pipeline.ask(item["question"], item["lang"], active=active, fault_spec=list(spec))
        tally["runs"] += 1
        if not faults.FIRED:
            continue
        tally["activated"] += 1
        label = classify(base[item["id"]], item, result)
        tally[label] += 1
        if label in ("raised", "silent_error", "caught"):
            grade = corpus.grade(item, result)
            tally["details"].append({"id": item["id"], "config": config, "fault": list(spec),
                                     "label": label, "honest": base[item["id"]]["assurance"],
                                     "shown": int(result["final"].get("assurance", 0)),
                                     "flagged": flagged(result), "problems": grade["problems"]})
    return tally


def probe_set(items: List[Dict[str, Any]], count: int) -> List[Dict[str, Any]]:
    """Spread the probe across the languages instead of taking the first N of one variety."""
    if count >= len(items):
        return list(items)
    by_lang: Dict[str, List[Dict[str, Any]]] = {}
    for item in items:
        by_lang.setdefault(item["lang"], []).append(item)
    picked: List[Dict[str, Any]] = []
    rank = 0
    while len(picked) < count:
        added = False
        for lang in sorted(by_lang):
            pool = by_lang[lang]
            if rank < len(pool) and len(picked) < count:
                picked.append(pool[rank])
                added = True
        if not added:
            break
        rank += 1
    return picked


def main(argv: List[str] = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--probe", type=int, default=12, help="how many corpus items to run per cell")
    parser.add_argument("--all", action="store_true", help="run the whole corpus in every cell")
    parser.add_argument("--out", default=str(OUT), help="where to write the JSON report")
    args = parser.parse_args(argv)

    items = corpus.load()
    probes = items if args.all else probe_set(items, max(1, args.probe))
    print("probe set: %d items over %s" % (len(probes), ", ".join(sorted({i["lang"] for i in probes}))))
    base = {}
    for item in probes:
        base[item["id"]] = honest(item)
        print("honest %-9s %-12s assurance %d %s" % (item["id"], base[item["id"]]["state"],
                                                     base[item["id"]]["assurance"],
                                                     "" if base[item["id"]]["ok"] else base[item["id"]]["problems"]))

    report: Dict[str, Any] = {"probe": [item["id"] for item in probes], "cells": {}}
    started = time.time()
    for name in sorted(CONFIGS):
        active = CONFIGS[name]
        specs = single_faults(active)
        if name == "S8 full topology":
            specs.extend(multi_faults())
        for spec in specs:
            cell = run_cell(probes, active, spec, base, config=name)
            key = "%s | %s" % (name, ",".join(spec))
            report["cells"][key] = cell
            print("%-46s runs %2d activated %2d raised %d silent %d caught %d abstained %d "
                  "lowered %d masked %d"
                  % (key, cell["runs"], cell["activated"], cell["raised"], cell["silent_error"],
                     cell["caught"], cell["abstained"], cell["lowered"], cell["masked"]))
    totals = {"runs": 0, "activated": 0, "raised": 0, "lowered": 0, "masked": 0, "caught": 0,
              "abstained": 0, "silent_error": 0}
    for cell in report["cells"].values():
        for key in totals:
            totals[key] += cell[key]
    report["totals"] = totals
    report["seconds"] = round(time.time() - started, 1)
    report["violations"] = [detail for cell in report["cells"].values() for detail in cell["details"]]

    destination = Path(args.out)
    destination.parent.mkdir(parents=True, exist_ok=True)
    destination.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print("")
    print("cells %d, activated %d, raised %d, silent errors %d, caught %d, abstained %d, lowered %d, "
          "masked %d"
          % (len(report["cells"]), totals["activated"], totals["raised"], totals["silent_error"],
             totals["caught"], totals["abstained"], totals["lowered"], totals["masked"]))
    print("wrote %s in %.1f seconds" % (destination, report["seconds"]))
    return 1 if totals["raised"] else 0


if __name__ == "__main__":
    raise SystemExit(main())