anthromesh 0.2.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.
- anthromesh/__init__.py +3 -0
- anthromesh/adapters/__init__.py +18 -0
- anthromesh/adapters/base.py +218 -0
- anthromesh/adapters/cloud.py +151 -0
- anthromesh/adapters/factory.py +31 -0
- anthromesh/adapters/heuristic.py +113 -0
- anthromesh/adapters/local.py +91 -0
- anthromesh/benchmarks/__init__.py +3 -0
- anthromesh/benchmarks/datasets.py +207 -0
- anthromesh/benchmarks/empirical.py +176 -0
- anthromesh/benchmarks/panel_cohort.py +67 -0
- anthromesh/benchmarks/public_twin.py +414 -0
- anthromesh/benchmarks/public_validation.py +435 -0
- anthromesh/benchmarks/replay.py +174 -0
- anthromesh/benchmarks/runner.py +140 -0
- anthromesh/benchmarks/study.py +245 -0
- anthromesh/benchmarks/study_report.py +170 -0
- anthromesh/capture/__init__.py +1 -0
- anthromesh/capture/github_webhook.py +51 -0
- anthromesh/capture/graph.py +221 -0
- anthromesh/capture/workflows.py +70 -0
- anthromesh/cli.py +807 -0
- anthromesh/client.py +96 -0
- anthromesh/cohort/__init__.py +3 -0
- anthromesh/cohort/categorical_anchor.py +240 -0
- anthromesh/cohort/clustering.py +93 -0
- anthromesh/cohort/human_anchor.py +92 -0
- anthromesh/cohort/ingest.py +104 -0
- anthromesh/cohort/oracle.py +153 -0
- anthromesh/cohort/twin_priors.py +118 -0
- anthromesh/config.py +48 -0
- anthromesh/gate/__init__.py +15 -0
- anthromesh/gate/calibration.py +95 -0
- anthromesh/gate/conformal.py +73 -0
- anthromesh/gate/engine.py +293 -0
- anthromesh/gate/fast.py +62 -0
- anthromesh/gate/fit.py +56 -0
- anthromesh/judgment/__init__.py +1 -0
- anthromesh/judgment/elicitation.py +206 -0
- anthromesh/judgment/monitor.py +128 -0
- anthromesh/judgment/panel.py +389 -0
- anthromesh/judgment/settings.py +41 -0
- anthromesh/models/__init__.py +39 -0
- anthromesh/models/cohort.py +76 -0
- anthromesh/models/decision.py +81 -0
- anthromesh/models/escalation.py +70 -0
- anthromesh/models/policy.py +41 -0
- anthromesh/models/validity.py +17 -0
- anthromesh/protocols/__init__.py +4 -0
- anthromesh/protocols/a2a_server.py +414 -0
- anthromesh/protocols/capabilities.py +52 -0
- anthromesh/protocols/delegation.py +373 -0
- anthromesh/protocols/mcp_server.py +500 -0
- anthromesh/protocols/oauth.py +177 -0
- anthromesh/ros_gate.py +141 -0
- anthromesh/twin/__init__.py +3 -0
- anthromesh/twin/engine.py +116 -0
- anthromesh/twin/inbox.py +221 -0
- anthromesh/vault/__init__.py +5 -0
- anthromesh/vault/dense.py +171 -0
- anthromesh/vault/encryption.py +50 -0
- anthromesh/vault/policy_engine.py +123 -0
- anthromesh/vault/postgres.py +92 -0
- anthromesh/vault/privacy.py +264 -0
- anthromesh/vault/retrieval.py +135 -0
- anthromesh/vault/storage.py +937 -0
- anthromesh-0.2.0.dist-info/METADATA +493 -0
- anthromesh-0.2.0.dist-info/RECORD +73 -0
- anthromesh-0.2.0.dist-info/WHEEL +5 -0
- anthromesh-0.2.0.dist-info/entry_points.txt +2 -0
- anthromesh-0.2.0.dist-info/licenses/LICENSE +201 -0
- anthromesh-0.2.0.dist-info/licenses/NOTICE +2 -0
- anthromesh-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
"""Retrospective Twin-2K-500 evaluation using the publisher's standardized CSVs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import shutil
|
|
9
|
+
import tempfile
|
|
10
|
+
import time
|
|
11
|
+
from collections import Counter, defaultdict
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from statistics import fmean
|
|
15
|
+
from urllib.error import URLError
|
|
16
|
+
from urllib.request import urlopen
|
|
17
|
+
|
|
18
|
+
from anthromesh.adapters.base import BaseModelAdapter, StructuredPrediction, extract_json_object
|
|
19
|
+
from anthromesh.benchmarks.study_report import _interval
|
|
20
|
+
from anthromesh.cohort.oracle import ResearchCohortOracle
|
|
21
|
+
from anthromesh.gate.calibration import compute_ece, jensen_shannon_divergence
|
|
22
|
+
from anthromesh.gate.conformal import CalibrationProfile, ConformalCalibration, normalize_scores
|
|
23
|
+
from anthromesh.gate.engine import ConfidenceGateEngine
|
|
24
|
+
from anthromesh.models import (
|
|
25
|
+
CandidateOption, CohortArchetype, CohortProfile, CohortQuery, DecisionLog, GateAction, QueryContext,
|
|
26
|
+
)
|
|
27
|
+
from anthromesh.twin.engine import PersonalDecisionTwin
|
|
28
|
+
from anthromesh.vault.policy_engine import PolicyEngine
|
|
29
|
+
from anthromesh.vault.storage import BehavioralVault
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
DATASET = "LLM-Digital-Twin/Twin-2K-500"
|
|
33
|
+
REVISION = "f883165a3026fde855dfd448e0cd16443ab257b6"
|
|
34
|
+
PUBLIC_FILES = {
|
|
35
|
+
"question_catalog.json": "question_catalog_and_human_response_csv",
|
|
36
|
+
"wave1_3_response.csv": "question_catalog_and_human_response_csv",
|
|
37
|
+
"wave4_response.csv": "question_catalog_and_human_response_csv",
|
|
38
|
+
"wave4_formatted_to_catalog_mapping.json": "LLM_simulation_results",
|
|
39
|
+
"responses_wave4_formatted.csv": "LLM_simulation_results/GPT4.1-mini-simulation-llm-vs-human",
|
|
40
|
+
"responses_llm_imputed_formatted.csv": "LLM_simulation_results/GPT4.1-mini-simulation-llm-vs-human",
|
|
41
|
+
}
|
|
42
|
+
FILE_HASHES = {
|
|
43
|
+
"question_catalog.json": "e72e305f0c7c83bb990e97de4c0cf2c718ead18cc197239b7feeb354c9ac1bef",
|
|
44
|
+
"wave1_3_response.csv": "fc227b1682e2654fd4b2a8152294b68118c0e3be4d83f4a9af5f3e96df56d3f0",
|
|
45
|
+
"wave4_response.csv": "09ec1a88bdd48fec95963da3102df0ca467378bf729cbc1c0b869b0f1e4fb942",
|
|
46
|
+
"wave4_formatted_to_catalog_mapping.json": "345f7f6645f80dc23bcb423a9bb7c5ae77dbbd17fe572472fdfeb252bdcfc2c7",
|
|
47
|
+
"responses_wave4_formatted.csv": "ace9258a2029f36283a61b6066aa8c9d59458fedefaac0afcbbe7797f4a3aaea",
|
|
48
|
+
"responses_llm_imputed_formatted.csv": "22937217115db30c064489125e39ceb0539c461b678400d8b3e0827962e5436c",
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def download_public_twin(folder: Path) -> None:
|
|
53
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
marker = folder / "revision.txt"
|
|
55
|
+
if marker.is_file() and marker.read_text(encoding="utf-8-sig").strip() != REVISION:
|
|
56
|
+
raise ValueError("Choose a directory for the pinned Twin-2K-500 revision.")
|
|
57
|
+
base = f"https://huggingface.co/datasets/{DATASET}/resolve/{REVISION}"
|
|
58
|
+
for filename, directory in PUBLIC_FILES.items():
|
|
59
|
+
destination = folder / filename
|
|
60
|
+
expected = FILE_HASHES[filename]
|
|
61
|
+
if destination.exists():
|
|
62
|
+
if hashlib.sha256(destination.read_bytes()).hexdigest() != expected:
|
|
63
|
+
raise ValueError(f"{filename} does not match the pinned release.")
|
|
64
|
+
continue
|
|
65
|
+
for attempt in range(3):
|
|
66
|
+
try:
|
|
67
|
+
suffix = "?download=true" if attempt % 2 == 0 else ""
|
|
68
|
+
with tempfile.TemporaryDirectory(dir=folder) as temporary:
|
|
69
|
+
staged = Path(temporary) / filename
|
|
70
|
+
with (urlopen(f"{base}/{directory}/{filename}{suffix}", timeout=30) as source,
|
|
71
|
+
staged.open("wb") as output):
|
|
72
|
+
shutil.copyfileobj(source, output)
|
|
73
|
+
if hashlib.sha256(staged.read_bytes()).hexdigest() != expected:
|
|
74
|
+
raise ValueError(f"Publisher checksum mismatch for {filename}.")
|
|
75
|
+
staged.replace(destination)
|
|
76
|
+
break
|
|
77
|
+
except (URLError, TimeoutError):
|
|
78
|
+
if attempt == 2:
|
|
79
|
+
raise
|
|
80
|
+
time.sleep(attempt + 1)
|
|
81
|
+
if not marker.exists():
|
|
82
|
+
with marker.open("x", encoding="utf-8") as output:
|
|
83
|
+
output.write(REVISION + "\n")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class Item:
|
|
88
|
+
column: str
|
|
89
|
+
text: str
|
|
90
|
+
options: tuple[CandidateOption, ...]
|
|
91
|
+
|
|
92
|
+
def answer(self, row: dict[str, str]) -> str | None:
|
|
93
|
+
raw = row.get(self.column, "").strip()
|
|
94
|
+
if not raw:
|
|
95
|
+
return None
|
|
96
|
+
try:
|
|
97
|
+
position = float(raw)
|
|
98
|
+
except ValueError as error:
|
|
99
|
+
raise ValueError(f"Non-numeric answer for {self.column}") from error
|
|
100
|
+
if not position.is_integer() or not 1 <= position <= len(self.options):
|
|
101
|
+
raise ValueError(f"Answer code outside catalog for {self.column}")
|
|
102
|
+
return self.options[int(position) - 1].option_id
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class _EvaluationPredictor:
|
|
106
|
+
def __init__(self, adapter: BaseModelAdapter) -> None:
|
|
107
|
+
self.adapter = adapter
|
|
108
|
+
self.adapter_name = adapter.adapter_name
|
|
109
|
+
self.model = adapter.model
|
|
110
|
+
self.prediction: StructuredPrediction | None = None
|
|
111
|
+
|
|
112
|
+
def predict_decision(self, query, evidence):
|
|
113
|
+
prediction = self.adapter.predict_decision(query, evidence)
|
|
114
|
+
self.prediction = prediction
|
|
115
|
+
return prediction
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _choice(prediction: StructuredPrediction | None, item: Item) -> str | None:
|
|
119
|
+
if prediction is None or prediction.chosen_option not in {o.option_id for o in item.options}:
|
|
120
|
+
return None
|
|
121
|
+
if prediction.raw_text:
|
|
122
|
+
try:
|
|
123
|
+
if extract_json_object(prediction.raw_text).get("chosen_option") != prediction.chosen_option:
|
|
124
|
+
return None
|
|
125
|
+
except (AttributeError, ValueError):
|
|
126
|
+
return None
|
|
127
|
+
return prediction.chosen_option
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _rank(*values: str) -> str:
|
|
131
|
+
return hashlib.sha256(json.dumps(values).encode()).hexdigest()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _table(path: Path) -> tuple[set[str], dict[str, dict[str, str]]]:
|
|
135
|
+
rows = {}
|
|
136
|
+
with path.open(encoding="utf-8-sig", newline="") as stream:
|
|
137
|
+
table = csv.DictReader(stream)
|
|
138
|
+
columns = set(table.fieldnames or [])
|
|
139
|
+
if "pid" not in columns or len(columns) != len(table.fieldnames or []):
|
|
140
|
+
raise ValueError(f"{path.name} must be the publisher CSV with unique fields and a pid column.")
|
|
141
|
+
for row in table:
|
|
142
|
+
pid = row.pop("pid")
|
|
143
|
+
if not pid or pid in rows or None in row or None in row.values():
|
|
144
|
+
raise ValueError(f"Malformed or duplicate participant row in {path.name}.")
|
|
145
|
+
rows[pid] = row
|
|
146
|
+
return columns, rows
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _items(catalog: list[dict]) -> dict[str, Item]:
|
|
150
|
+
items = {}
|
|
151
|
+
for entry in catalog:
|
|
152
|
+
if entry["QuestionType"] != "MC" or entry["Settings"].get("Selector") not in {"SAVR", "SAHR"}:
|
|
153
|
+
continue
|
|
154
|
+
labels = [label.strip() for label in entry.get("Options", [])]
|
|
155
|
+
text = entry["QuestionText"].strip()
|
|
156
|
+
[column] = entry["csv_columns"]
|
|
157
|
+
if not text or len(set(labels)) != len(labels) or not 2 <= len(labels) <= 20:
|
|
158
|
+
continue
|
|
159
|
+
if column in items:
|
|
160
|
+
raise ValueError(f"Ambiguous catalog column {column}")
|
|
161
|
+
options = tuple(CandidateOption(option_id=_rank(label.casefold())[:16], label=label) for label in labels)
|
|
162
|
+
if len({option.option_id for option in options}) == len(options):
|
|
163
|
+
items[column] = Item(column, text, options)
|
|
164
|
+
return items
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _query(pid: str, item: Item) -> QueryContext:
|
|
168
|
+
return QueryContext(query_id=f"{pid}:{item.column}", subject_id=pid, caller_agent="public-benchmark",
|
|
169
|
+
domain="survey", context=item.text, candidate_options=list(item.options))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _distribution(votes: Counter, options: tuple[CandidateOption, ...]) -> dict[str, float]:
|
|
173
|
+
total = sum(votes.values())
|
|
174
|
+
return {option.option_id: votes[option.option_id] / total for option in options}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _reference_rows(path: Path) -> dict[str, dict[str, str]]:
|
|
178
|
+
rows = {}
|
|
179
|
+
with path.open(encoding="utf-8-sig", newline="") as stream:
|
|
180
|
+
for row in csv.DictReader(stream):
|
|
181
|
+
pid = row["TWIN_ID"]
|
|
182
|
+
# The publisher includes two Qualtrics metadata rows.
|
|
183
|
+
if not pid.isdecimal():
|
|
184
|
+
continue
|
|
185
|
+
if pid in rows:
|
|
186
|
+
raise ValueError(f"Duplicate participant in {path.name}.")
|
|
187
|
+
rows[pid] = row
|
|
188
|
+
return rows
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _compare_published(folder: Path, cases: list, items: dict[str, Item]) -> dict:
|
|
192
|
+
paths = [folder / name for name in ("wave4_formatted_to_catalog_mapping.json",
|
|
193
|
+
"responses_wave4_formatted.csv",
|
|
194
|
+
"responses_llm_imputed_formatted.csv")]
|
|
195
|
+
mapping = {row["catalog_csv_column"]: row["formatted_column"]
|
|
196
|
+
for row in json.loads(paths[0].read_text(encoding="utf-8-sig"))}
|
|
197
|
+
human = _reference_rows(paths[1])
|
|
198
|
+
model = _reference_rows(paths[2])
|
|
199
|
+
paired = []
|
|
200
|
+
mismatches = 0
|
|
201
|
+
for pid, column, truth, twin in cases:
|
|
202
|
+
if column not in mapping or pid not in human or pid not in model:
|
|
203
|
+
continue
|
|
204
|
+
formatted = mapping[column]
|
|
205
|
+
item = items[column]
|
|
206
|
+
try:
|
|
207
|
+
published_truth = item.answer({column: human[pid].get(formatted, "")})
|
|
208
|
+
published_choice = item.answer({column: model[pid].get(formatted, "")})
|
|
209
|
+
except ValueError:
|
|
210
|
+
mismatches += 1
|
|
211
|
+
continue
|
|
212
|
+
if published_truth != truth:
|
|
213
|
+
mismatches += 1
|
|
214
|
+
elif published_choice is not None:
|
|
215
|
+
paired.append((twin, published_choice == truth))
|
|
216
|
+
return {
|
|
217
|
+
"matched_answers": len(paired),
|
|
218
|
+
"excluded_invalid_or_unaligned_answers": mismatches,
|
|
219
|
+
"anthromesh_ungated_accuracy": fmean(row[0] for row in paired) if paired else None,
|
|
220
|
+
"publisher_gpt_4_1_mini_accuracy": fmean(row[1] for row in paired) if paired else None,
|
|
221
|
+
"sha256": {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in paths},
|
|
222
|
+
"same_cases_different_persona_inputs": True,
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def evaluate_public_twin(folder: Path, adapter: BaseModelAdapter, *, seed: str, participants: int) -> dict:
|
|
227
|
+
if participants < 4:
|
|
228
|
+
raise ValueError("Choose at least four evaluation participants.")
|
|
229
|
+
catalog_path = folder / "question_catalog.json"
|
|
230
|
+
earlier_path = folder / "wave1_3_response.csv"
|
|
231
|
+
later_path = folder / "wave4_response.csv"
|
|
232
|
+
earlier_columns, earlier = _table(earlier_path)
|
|
233
|
+
later_columns, later = _table(later_path)
|
|
234
|
+
items = _items(json.loads(catalog_path.read_text(encoding="utf-8-sig")))
|
|
235
|
+
paired = sorted(items.keys() & earlier_columns & later_columns, key=lambda key: _rank(seed, "question", key))
|
|
236
|
+
cut = len(paired) // 2
|
|
237
|
+
calibration_items, test_items = paired[:cut], paired[cut:]
|
|
238
|
+
people = sorted(earlier.keys() & later.keys(), key=lambda pid: _rank(seed, "participant", pid))
|
|
239
|
+
if cut < 2 or len(people) < participants + 8:
|
|
240
|
+
raise ValueError("Insufficient paired questions or independent calibration participants.")
|
|
241
|
+
test_people = people[:participants]
|
|
242
|
+
calibration_people = people[participants:participants + min(32, (len(people) - participants) // 2)]
|
|
243
|
+
reference_people = people[participants + len(calibration_people):]
|
|
244
|
+
if not reference_people:
|
|
245
|
+
raise ValueError("No participants remain for the independent population prior.")
|
|
246
|
+
history_items = sorted((items.keys() & earlier_columns) - later_columns)
|
|
247
|
+
# Exclude verbatim duplicates even if the publisher used a different column ID.
|
|
248
|
+
paired_text = {items[key].text.casefold() for key in paired}
|
|
249
|
+
history_items = [key for key in history_items if items[key].text.casefold() not in paired_text]
|
|
250
|
+
domain = "survey"
|
|
251
|
+
records = defaultdict(list)
|
|
252
|
+
confidences, correctness, answered = [], [], []
|
|
253
|
+
aggregates = defaultdict(Counter)
|
|
254
|
+
repeat_correct, majority_correct, persona_correct = [], [], []
|
|
255
|
+
paired_cases = []
|
|
256
|
+
majority_deltas = defaultdict(list)
|
|
257
|
+
owner_replays = {}
|
|
258
|
+
cohort = []
|
|
259
|
+
with tempfile.TemporaryDirectory(prefix="anthromesh-public-replay-") as temp:
|
|
260
|
+
vault = BehavioralVault(str(Path(temp) / "benchmark.db"))
|
|
261
|
+
replay = _EvaluationPredictor(adapter)
|
|
262
|
+
gate = ConfidenceGateEngine(vault, PolicyEngine(), replay)
|
|
263
|
+
for pid in test_people + calibration_people:
|
|
264
|
+
for column in history_items:
|
|
265
|
+
item = items[column]
|
|
266
|
+
action = item.answer(earlier[pid])
|
|
267
|
+
if action is None:
|
|
268
|
+
continue
|
|
269
|
+
record = DecisionLog(
|
|
270
|
+
decision_id=f"{pid}:{column}", subject_id=pid, domain=domain, context=item.text,
|
|
271
|
+
options_considered=list(item.options), chosen_action=action,
|
|
272
|
+
rationale=next(option.label for option in item.options if option.option_id == action),
|
|
273
|
+
)
|
|
274
|
+
records[pid].append(record)
|
|
275
|
+
with vault._connect() as conn:
|
|
276
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
277
|
+
for pid in test_people:
|
|
278
|
+
for record in records[pid]:
|
|
279
|
+
vault._insert_decision(conn, record)
|
|
280
|
+
scores = []
|
|
281
|
+
for pid in calibration_people:
|
|
282
|
+
for column in calibration_items:
|
|
283
|
+
item = items[column]
|
|
284
|
+
truth = item.answer(later[pid])
|
|
285
|
+
if truth is None:
|
|
286
|
+
continue
|
|
287
|
+
query = _query(pid, item)
|
|
288
|
+
evidence, _ = gate.select_evidence(query, records[pid])
|
|
289
|
+
prediction = adapter.predict_decision(query, evidence)
|
|
290
|
+
probabilities = normalize_scores(prediction.option_scores, {o.option_id for o in item.options})
|
|
291
|
+
scores.append(1 - probabilities.get(truth, 0) if _choice(prediction, item) else 1)
|
|
292
|
+
if len(scores) < 9:
|
|
293
|
+
raise ValueError("Insufficient observed calibration answers for the 90% prediction set.")
|
|
294
|
+
gate.conformal = ConformalCalibration(
|
|
295
|
+
CalibrationProfile(subject_id=pid, domain=domain, adapter=adapter.adapter_name,
|
|
296
|
+
model=adapter.model, alpha=0.1, scores=scores)
|
|
297
|
+
for pid in test_people
|
|
298
|
+
)
|
|
299
|
+
oracle = ResearchCohortOracle(vault, adapter)
|
|
300
|
+
for column in test_items:
|
|
301
|
+
item = items[column]
|
|
302
|
+
strata = [Counter(answer for pid in reference_people[group::2]
|
|
303
|
+
if (answer := item.answer(earlier[pid])) is not None) for group in range(2)]
|
|
304
|
+
prior = strata[0] + strata[1]
|
|
305
|
+
if not prior:
|
|
306
|
+
continue
|
|
307
|
+
prior_distribution = _distribution(prior, item.options)
|
|
308
|
+
common = max(prior_distribution, key=prior_distribution.__getitem__)
|
|
309
|
+
for pid in test_people:
|
|
310
|
+
early = item.answer(earlier[pid])
|
|
311
|
+
truth = item.answer(later[pid])
|
|
312
|
+
if early is None or truth is None:
|
|
313
|
+
continue
|
|
314
|
+
query = _query(pid, item)
|
|
315
|
+
replay.prediction = None
|
|
316
|
+
result = gate.evaluate(query)
|
|
317
|
+
chosen = _choice(replay.prediction, item)
|
|
318
|
+
persona_summary = "\n".join(
|
|
319
|
+
f"{record.context} — {record.rationale}" for record in records[pid][:8]
|
|
320
|
+
)[:2000]
|
|
321
|
+
persona = adapter.predict_persona(query, persona_summary)
|
|
322
|
+
is_correct = chosen == truth
|
|
323
|
+
correctness.append(is_correct)
|
|
324
|
+
confidences.append(result.confidence)
|
|
325
|
+
persona_correct.append(_choice(persona, item) == truth)
|
|
326
|
+
majority_correct.append(common == truth)
|
|
327
|
+
repeat_correct.append(early == truth)
|
|
328
|
+
majority_deltas[pid].append(int(is_correct) - int(common == truth))
|
|
329
|
+
paired_cases.append((pid, column, truth, is_correct))
|
|
330
|
+
aggregates[column][truth] += 1
|
|
331
|
+
if result.action == GateAction.APPROVED:
|
|
332
|
+
answered.append(is_correct)
|
|
333
|
+
elif result.escalation_ticket:
|
|
334
|
+
owner_replays.setdefault(column, (result.escalation_ticket.ticket_id, truth))
|
|
335
|
+
if not aggregates[column] or not all(strata):
|
|
336
|
+
continue
|
|
337
|
+
profile = CohortProfile(
|
|
338
|
+
cohort_id=f"public-{column}", name="Independent earlier-wave respondents", domain=domain,
|
|
339
|
+
population_weighted=True,
|
|
340
|
+
archetypes=[
|
|
341
|
+
CohortArchetype(archetype_id=f"reference-{index}", label="Reference sample",
|
|
342
|
+
weight=sum(votes.values()) / sum(prior.values()),
|
|
343
|
+
prior_tendencies=_distribution(votes, item.options))
|
|
344
|
+
for index, votes in enumerate(strata)
|
|
345
|
+
],
|
|
346
|
+
)
|
|
347
|
+
oracle.register_cohort(profile)
|
|
348
|
+
distribution = oracle.simulate(CohortQuery(
|
|
349
|
+
cohort_id=profile.cohort_id, stimulus=item.text, options=list(item.options),
|
|
350
|
+
sample_size=2000, random_seed=int(_rank(seed, column)[:8], 16), use_twin_priors=False,
|
|
351
|
+
)).metrics.option_distribution
|
|
352
|
+
observed = _distribution(aggregates[column], item.options)
|
|
353
|
+
generic = adapter.predict_persona(_query("generic", item), "")
|
|
354
|
+
generic_distribution = normalize_scores(generic.option_scores, set(observed))
|
|
355
|
+
cohort.append((observed, distribution, prior_distribution, generic_distribution))
|
|
356
|
+
# Resolve one sampled ticket per question after all forecasts are frozen so
|
|
357
|
+
# held-out labels cannot enter the histories used to predict later cases.
|
|
358
|
+
twin = PersonalDecisionTwin(vault, PolicyEngine(), adapter)
|
|
359
|
+
for ticket_id, choice in owner_replays.values():
|
|
360
|
+
twin.resolve_escalation(ticket_id, choice, "Published Wave 4 outcome used for offline replay.",
|
|
361
|
+
tags=["offline_study_replay"])
|
|
362
|
+
if not vault.verify_audit_chain():
|
|
363
|
+
raise RuntimeError("The study vault audit chain failed after offline escalation replay.")
|
|
364
|
+
if not correctness:
|
|
365
|
+
raise ValueError("No paired evaluation answers matched the question catalog.")
|
|
366
|
+
revision_path = folder / "revision.txt"
|
|
367
|
+
compare = (folder / "wave4_formatted_to_catalog_mapping.json").is_file() and all(
|
|
368
|
+
(folder / filename).is_file() for filename in
|
|
369
|
+
("responses_wave4_formatted.csv", "responses_llm_imputed_formatted.csv")
|
|
370
|
+
)
|
|
371
|
+
cohort_metrics = {}
|
|
372
|
+
for index, name in enumerate(("oracle", "earlier_wave_empirical_prior", "generic_prompt"), start=1):
|
|
373
|
+
tails = [row[index].get(option, 0) >= probability / 2
|
|
374
|
+
for row in cohort for option, probability in row[0].items() if 0 < probability < 0.10]
|
|
375
|
+
cohort_metrics[name] = {
|
|
376
|
+
"mean_jsd": fmean(jensen_shannon_divergence(row[0], row[index]) for row in cohort) if cohort else None,
|
|
377
|
+
"minority_recall_at_half_observed_mass": fmean(tails) if tails else None,
|
|
378
|
+
}
|
|
379
|
+
return {
|
|
380
|
+
"dataset": DATASET,
|
|
381
|
+
"license": "CC BY 4.0",
|
|
382
|
+
"dataset_revision": revision_path.read_text(encoding="utf-8-sig").strip() if revision_path.is_file() else None,
|
|
383
|
+
"design": "retrospective_single_select_public_benchmark",
|
|
384
|
+
"adapter": f"{adapter.adapter_name}:{adapter.model}",
|
|
385
|
+
"seed": seed,
|
|
386
|
+
"sha256": {path.name: hashlib.sha256(path.read_bytes()).hexdigest()
|
|
387
|
+
for path in (catalog_path, earlier_path, later_path)},
|
|
388
|
+
"evaluation_participants": len(test_people),
|
|
389
|
+
"participants_with_paired_answers": len(majority_deltas),
|
|
390
|
+
"reference_participants": len(reference_people),
|
|
391
|
+
"calibration_participants": len(calibration_people),
|
|
392
|
+
"calibration_question_columns": calibration_items,
|
|
393
|
+
"evaluation_question_columns": test_items,
|
|
394
|
+
"paired_evaluation_answers": len(correctness),
|
|
395
|
+
"personal": {
|
|
396
|
+
"ungated_retrieval_accuracy": fmean(correctness),
|
|
397
|
+
"gate_coverage": len(answered) / len(correctness),
|
|
398
|
+
"gate_selective_accuracy": fmean(answered) if answered else None,
|
|
399
|
+
"escalations_requiring_owner": len(correctness) - len(answered),
|
|
400
|
+
"offline_owner_resolutions_replayed": len(owner_replays),
|
|
401
|
+
"incorrect_approvals": len(answered) - sum(answered),
|
|
402
|
+
"expected_calibration_error": compute_ece(confidences, correctness),
|
|
403
|
+
"persona_prompt_accuracy": fmean(persona_correct),
|
|
404
|
+
"earlier_wave_population_majority_accuracy": fmean(majority_correct),
|
|
405
|
+
"human_retest_agreement": fmean(repeat_correct),
|
|
406
|
+
"participant_bootstrap_95pct_accuracy_difference_vs_majority": _interval(
|
|
407
|
+
[fmean(deltas) for deltas in majority_deltas.values()],
|
|
408
|
+
draws=2000, seed=int(_rank(seed, "bootstrap")[:8], 16), tail=0.025,
|
|
409
|
+
),
|
|
410
|
+
},
|
|
411
|
+
"published_comparison": _compare_published(folder, paired_cases, items) if compare else None,
|
|
412
|
+
"cohort_question_count": len(cohort),
|
|
413
|
+
"cohort_distribution": cohort_metrics,
|
|
414
|
+
}
|