elicitor 0.1.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.
- elicitor/__init__.py +22 -0
- elicitor/__main__.py +3 -0
- elicitor/analysis/__init__.py +1 -0
- elicitor/analysis/descriptive.py +176 -0
- elicitor/analysis/figures.py +101 -0
- elicitor/analysis/judge_report.py +647 -0
- elicitor/analysis/report.py +382 -0
- elicitor/analysis/stats.py +107 -0
- elicitor/answer_model.py +79 -0
- elicitor/backstories.py +87 -0
- elicitor/belief.py +81 -0
- elicitor/bundled/data/travel/backstories.jsonl +60 -0
- elicitor/bundled/data/travel/catalog.jsonl +200 -0
- elicitor/bundled/data/travel/personas.jsonl +60 -0
- elicitor/bundled/data/travel/prompts/backstory.txt +15 -0
- elicitor/bundled/data/travel/prompts/imagine.txt +14 -0
- elicitor/bundled/data/travel/prompts/judge.txt +17 -0
- elicitor/bundled/data/travel/prompts/pair.txt +21 -0
- elicitor/bundled/data/travel/prompts/phrase.txt +13 -0
- elicitor/bundled/data/travel/prompts/plan.txt +12 -0
- elicitor/bundled/data/travel/prompts/simulate.txt +19 -0
- elicitor/bundled/data/travel/prompts/styles.toml +9 -0
- elicitor/bundled/data/travel/prompts/update.txt +19 -0
- elicitor/bundled/data/travel/schema.toml +129 -0
- elicitor/bundled/experiments/demo.toml +35 -0
- elicitor/calibration.py +203 -0
- elicitor/catalog.py +42 -0
- elicitor/cli.py +319 -0
- elicitor/datagen.py +40 -0
- elicitor/demo.py +115 -0
- elicitor/episode.py +152 -0
- elicitor/experiments/__init__.py +1 -0
- elicitor/experiments/config.py +159 -0
- elicitor/experiments/health.py +144 -0
- elicitor/experiments/runner.py +308 -0
- elicitor/experiments/store.py +210 -0
- elicitor/jsonl.py +20 -0
- elicitor/judge.py +476 -0
- elicitor/llm/__init__.py +10 -0
- elicitor/llm/cache.py +73 -0
- elicitor/llm/client.py +389 -0
- elicitor/llm/mock.py +117 -0
- elicitor/llm/providers.py +218 -0
- elicitor/llm/roles.py +240 -0
- elicitor/metrics.py +70 -0
- elicitor/personas.py +96 -0
- elicitor/phrasing.py +101 -0
- elicitor/questions.py +83 -0
- elicitor/recommender.py +91 -0
- elicitor/resources.py +33 -0
- elicitor/rng.py +17 -0
- elicitor/schema.py +142 -0
- elicitor/selectors/__init__.py +64 -0
- elicitor/selectors/eig.py +90 -0
- elicitor/selectors/eig_mc.py +97 -0
- elicitor/selectors/entropy.py +27 -0
- elicitor/selectors/fixed.py +24 -0
- elicitor/selectors/random.py +24 -0
- elicitor/session.py +214 -0
- elicitor/simulator/__init__.py +42 -0
- elicitor/simulator/llm.py +57 -0
- elicitor/simulator/oracle.py +52 -0
- elicitor/updaters/__init__.py +37 -0
- elicitor/updaters/llm.py +65 -0
- elicitor/updaters/rule.py +173 -0
- elicitor-0.1.0.dist-info/METADATA +283 -0
- elicitor-0.1.0.dist-info/RECORD +71 -0
- elicitor-0.1.0.dist-info/WHEEL +5 -0
- elicitor-0.1.0.dist-info/entry_points.txt +2 -0
- elicitor-0.1.0.dist-info/licenses/LICENSE +21 -0
- elicitor-0.1.0.dist-info/top_level.txt +1 -0
elicitor/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Elicitor: preference elicitation by expected information gain."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from elicitor.belief import Belief
|
|
6
|
+
from elicitor.catalog import Item, load_catalog
|
|
7
|
+
from elicitor.questions import Question
|
|
8
|
+
from elicitor.schema import Schema, load_schema
|
|
9
|
+
from elicitor.session import Recommendation, Session, understood
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"Belief",
|
|
13
|
+
"Item",
|
|
14
|
+
"Question",
|
|
15
|
+
"Recommendation",
|
|
16
|
+
"Schema",
|
|
17
|
+
"Session",
|
|
18
|
+
"__version__",
|
|
19
|
+
"load_catalog",
|
|
20
|
+
"load_schema",
|
|
21
|
+
"understood",
|
|
22
|
+
]
|
elicitor/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Statistics, tables and figures over finished runs (SPEC §13, M4)."""
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Descriptive tables for H3 and H4 of the frozen hypotheses (SPEC §13 M6, Decision Q13).
|
|
2
|
+
|
|
3
|
+
Neither table is a test: the style table splits the LLM − rule updater gap by answer style
|
|
4
|
+
(12 eval personas per style), and the correlation table relates final belief quality to regret
|
|
5
|
+
across episodes, which are not independent within a persona. So there are CIs but no p-values.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import itertools
|
|
11
|
+
import tomllib
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TYPE_CHECKING, Any
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from scipy import stats
|
|
17
|
+
|
|
18
|
+
from elicitor.analysis.stats import bootstrap_mean_ci
|
|
19
|
+
from elicitor.experiments.config import Arm
|
|
20
|
+
from elicitor.personas import STYLES, load_personas
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from elicitor.analysis.report import Run
|
|
24
|
+
|
|
25
|
+
STYLE_METRICS = ("mass_on_truth", "map_accuracy")
|
|
26
|
+
CORRELATION_METRICS = ("mass_on_truth", "map_accuracy") # each against final regret
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def persona_styles(run: Run, root: str | Path) -> dict[str, str] | None:
|
|
30
|
+
"""Style of every persona of the run, from `data/<domain>/personas.jsonl` under `root`.
|
|
31
|
+
|
|
32
|
+
None when the file is missing or does not cover the run's personas: the episodes do not
|
|
33
|
+
store styles, so the style table is skipped rather than guessed.
|
|
34
|
+
"""
|
|
35
|
+
domain = tomllib.loads(run.state.get("config", "")).get("domain")
|
|
36
|
+
path = Path(root) / "data" / str(domain) / "personas.jsonl"
|
|
37
|
+
if domain is None or not path.exists():
|
|
38
|
+
return None
|
|
39
|
+
styles = {p.id: p.style for p in load_personas(path)}
|
|
40
|
+
if not set(run.state["personas"]) <= set(styles):
|
|
41
|
+
return None
|
|
42
|
+
return styles
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def updater_pairs(arms: list[str]) -> list[tuple[str, str]]:
|
|
46
|
+
"""(rule arm, llm arm) for every selector and phraser that has both updaters."""
|
|
47
|
+
names = set(arms)
|
|
48
|
+
pairs = []
|
|
49
|
+
for name in arms:
|
|
50
|
+
arm = Arm.parse(name)
|
|
51
|
+
if arm.updater != "llm":
|
|
52
|
+
continue
|
|
53
|
+
rule = Arm(arm.selector, "rule", arm.phraser).name
|
|
54
|
+
if rule in names:
|
|
55
|
+
pairs.append((rule, name))
|
|
56
|
+
return pairs
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _persona_means(run: Run, metric: str) -> dict[tuple[str, int, str], float]:
|
|
60
|
+
"""Final metric averaged over replicates: {(arm, budget, persona): mean}."""
|
|
61
|
+
groups: dict[tuple[str, int, str], list[float]] = {}
|
|
62
|
+
for e in run.episodes:
|
|
63
|
+
groups.setdefault((e["arm"], e["budget"], e["persona"]), []).append(
|
|
64
|
+
float(e["final_metrics"][metric])
|
|
65
|
+
)
|
|
66
|
+
return {key: float(np.mean(v)) for key, v in groups.items()}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def style_table(run: Run, styles: dict[str, str], resamples: int) -> list[dict[str, Any]]:
|
|
70
|
+
rows = []
|
|
71
|
+
for metric in STYLE_METRICS:
|
|
72
|
+
means = _persona_means(run, metric)
|
|
73
|
+
for (rule, llm), budget, style in itertools.product(
|
|
74
|
+
updater_pairs(run.arms), run.budgets, STYLES
|
|
75
|
+
):
|
|
76
|
+
personas = sorted(
|
|
77
|
+
p
|
|
78
|
+
for p in run.state["personas"]
|
|
79
|
+
if styles[p] == style and (rule, budget, p) in means and (llm, budget, p) in means
|
|
80
|
+
)
|
|
81
|
+
if not personas:
|
|
82
|
+
continue
|
|
83
|
+
a = np.array([means[(rule, budget, p)] for p in personas])
|
|
84
|
+
b = np.array([means[(llm, budget, p)] for p in personas])
|
|
85
|
+
low, high = bootstrap_mean_ci(b - a, resamples)
|
|
86
|
+
arm = Arm.parse(llm)
|
|
87
|
+
rows.append(
|
|
88
|
+
{"metric": metric, "selector": arm.selector, "phraser": arm.phraser,
|
|
89
|
+
"budget": budget, "style": style, "personas": len(personas),
|
|
90
|
+
"rule": a.mean(), "llm": b.mean(), "gap": (b - a).mean(),
|
|
91
|
+
"ci_low": low, "ci_high": high}
|
|
92
|
+
) # fmt: skip
|
|
93
|
+
return rows
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def spearman(x: np.ndarray, y: np.ndarray) -> float:
|
|
97
|
+
"""Spearman correlation; NaN when either side is constant (no ranking to compare)."""
|
|
98
|
+
if x.size < 2 or np.ptp(x) == 0 or np.ptp(y) == 0:
|
|
99
|
+
return float("nan")
|
|
100
|
+
return float(stats.spearmanr(x, y).statistic)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def correlation_table(run: Run) -> list[dict[str, Any]]:
|
|
104
|
+
rows = []
|
|
105
|
+
for arm, budget in itertools.product(run.arms, run.budgets):
|
|
106
|
+
episodes = [e for e in run.episodes if e["arm"] == arm and e["budget"] == budget]
|
|
107
|
+
if not episodes or "regret" not in episodes[0]["final_metrics"]:
|
|
108
|
+
continue
|
|
109
|
+
regret = np.array([e["final_metrics"]["regret"] for e in episodes], dtype=float)
|
|
110
|
+
row: dict[str, Any] = {
|
|
111
|
+
"arm": arm,
|
|
112
|
+
"budget": budget,
|
|
113
|
+
"episodes": len(episodes),
|
|
114
|
+
"zero_regret_share": float((regret == 0).mean()),
|
|
115
|
+
}
|
|
116
|
+
for metric in CORRELATION_METRICS:
|
|
117
|
+
x = np.array([e["final_metrics"][metric] for e in episodes], dtype=float)
|
|
118
|
+
row[f"rho_{metric}"] = spearman(x, regret)
|
|
119
|
+
rows.append(row)
|
|
120
|
+
return rows
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _rho(value: float) -> str:
|
|
124
|
+
return "n/a" if np.isnan(value) else f"{value:+.2f}"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def markdown(styles: list[dict[str, Any]] | None, correlations: list[dict[str, Any]]) -> list[str]:
|
|
128
|
+
lines: list[str] = []
|
|
129
|
+
if styles:
|
|
130
|
+
lines += [
|
|
131
|
+
"",
|
|
132
|
+
"## Updater gap by answer style (H3, descriptive)",
|
|
133
|
+
"",
|
|
134
|
+
"LLM − rule updater, final value, persona means (replicates averaged first) with 95 %"
|
|
135
|
+
" bootstrap CIs over the personas of each style. No test.",
|
|
136
|
+
]
|
|
137
|
+
present = [s for s in STYLES if any(r["style"] == s for r in styles)]
|
|
138
|
+
for metric in STYLE_METRICS:
|
|
139
|
+
rows = [r for r in styles if r["metric"] == metric]
|
|
140
|
+
if not rows:
|
|
141
|
+
continue
|
|
142
|
+
n = {s: next(r["personas"] for r in rows if r["style"] == s) for s in present}
|
|
143
|
+
lines += ["", f"### {metric}", ""]
|
|
144
|
+
header = " | ".join(f"{s} (n={n[s]})" for s in present)
|
|
145
|
+
lines.append(f"| selector | phraser | K | {header} |")
|
|
146
|
+
lines.append("|---|---|---|" + "---|" * len(present))
|
|
147
|
+
cell = {(r["selector"], r["phraser"], r["budget"], r["style"]): r for r in rows}
|
|
148
|
+
keys = dict.fromkeys((r["selector"], r["phraser"], r["budget"]) for r in rows)
|
|
149
|
+
for sel, phr, k in keys:
|
|
150
|
+
entries = []
|
|
151
|
+
for s in present:
|
|
152
|
+
r = cell.get((sel, phr, k, s))
|
|
153
|
+
entries.append(
|
|
154
|
+
f"{r['gap']:+.3f} [{r['ci_low']:+.3f}, {r['ci_high']:+.3f}]" if r else "—"
|
|
155
|
+
)
|
|
156
|
+
lines.append(f"| `{sel}` | `{phr}` | {k} | " + " | ".join(entries) + " |")
|
|
157
|
+
if correlations:
|
|
158
|
+
lines += [
|
|
159
|
+
"",
|
|
160
|
+
"## Final belief vs regret (H4, descriptive)",
|
|
161
|
+
"",
|
|
162
|
+
"Spearman correlation over episodes (persona × replicate) between a final belief metric"
|
|
163
|
+
" and final regret; negative means a better belief goes with lower regret. Episodes of"
|
|
164
|
+
" one persona are not independent, so no p-value.",
|
|
165
|
+
"",
|
|
166
|
+
"| arm | K | episodes | zero regret | ρ(mass_on_truth, regret)"
|
|
167
|
+
" | ρ(map_accuracy, regret) |",
|
|
168
|
+
"|---|---|---|---|---|---|",
|
|
169
|
+
]
|
|
170
|
+
for r in correlations:
|
|
171
|
+
lines.append(
|
|
172
|
+
f"| `{r['arm']}` | {r['budget']} | {r['episodes']} | "
|
|
173
|
+
f"{r['zero_regret_share']:.2f} | {_rho(r['rho_mass_on_truth'])} | "
|
|
174
|
+
f"{_rho(r['rho_map_accuracy'])} |"
|
|
175
|
+
)
|
|
176
|
+
return lines
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Per-turn curve figures (SPEC §12, §16): one metric and budget per figure, one line per arm.
|
|
2
|
+
|
|
3
|
+
Colour follows the selector and line style the updater and phraser, so an arm keeps its look in
|
|
4
|
+
every figure of a run, and colour never has to tell more than eight arms apart. The band is
|
|
5
|
+
±1.96 standard errors over personas.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import matplotlib
|
|
14
|
+
|
|
15
|
+
matplotlib.use("Agg")
|
|
16
|
+
import matplotlib.pyplot as plt # noqa: E402
|
|
17
|
+
|
|
18
|
+
from elicitor.experiments.config import Arm # noqa: E402
|
|
19
|
+
|
|
20
|
+
# Categorical colours in a fixed order (validated for colour-vision deficiency as a set).
|
|
21
|
+
COLORS = ("#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948")
|
|
22
|
+
LINESTYLES = ("solid", (0, (5, 2)), (0, (1, 1.5)), (0, (5, 1.5, 1, 1.5)))
|
|
23
|
+
INK = "#0b0b0b"
|
|
24
|
+
INK_MUTED = "#52514e"
|
|
25
|
+
GRID = "#e4e3df"
|
|
26
|
+
|
|
27
|
+
LABELS = {
|
|
28
|
+
"mass_on_truth": "probability on the true value",
|
|
29
|
+
"map_accuracy": "MAP accuracy",
|
|
30
|
+
"log_loss": "log loss (bits)",
|
|
31
|
+
"mean_entropy": "entropy (bits)",
|
|
32
|
+
"regret": "regret of the top item",
|
|
33
|
+
"hit@1": "hit@1",
|
|
34
|
+
"hit@5": "hit@5",
|
|
35
|
+
"hit@10": "hit@10",
|
|
36
|
+
"violations": "constraint violations",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def arm_styles(arms: list[str]) -> dict[str, dict[str, Any]]:
|
|
41
|
+
"""Colour by selector, line style by (updater, phraser), both in order of first appearance."""
|
|
42
|
+
parsed = {a: Arm.parse(a) for a in arms}
|
|
43
|
+
selectors = list(dict.fromkeys(p.selector for p in parsed.values()))
|
|
44
|
+
variants = list(dict.fromkeys((p.updater, p.phraser) for p in parsed.values()))
|
|
45
|
+
if len(selectors) > len(COLORS) or len(variants) > len(LINESTYLES):
|
|
46
|
+
raise ValueError("too many selectors or updater/phraser variants for one figure")
|
|
47
|
+
return {
|
|
48
|
+
a: {
|
|
49
|
+
"color": COLORS[selectors.index(p.selector)],
|
|
50
|
+
"linestyle": LINESTYLES[variants.index((p.updater, p.phraser))],
|
|
51
|
+
"label": f"{p.selector} · {p.updater} · {p.phraser}",
|
|
52
|
+
}
|
|
53
|
+
for a, p in parsed.items()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def plot_curves(
|
|
58
|
+
rows: list[dict[str, Any]],
|
|
59
|
+
metric: str,
|
|
60
|
+
budget: int,
|
|
61
|
+
arms: list[str],
|
|
62
|
+
path: str | Path,
|
|
63
|
+
title: str = "",
|
|
64
|
+
) -> Path:
|
|
65
|
+
"""`rows` are the curve-table rows of one metric and budget."""
|
|
66
|
+
styles = arm_styles(arms)
|
|
67
|
+
fig, ax = plt.subplots(figsize=(6.4, 4.0), dpi=150)
|
|
68
|
+
for arm in arms:
|
|
69
|
+
points = sorted((r for r in rows if r["arm"] == arm), key=lambda r: r["turn"])
|
|
70
|
+
if not points:
|
|
71
|
+
continue
|
|
72
|
+
turns = [r["turn"] for r in points]
|
|
73
|
+
mean = [r["mean"] for r in points]
|
|
74
|
+
low = [r["mean"] - 1.96 * r["se"] for r in points]
|
|
75
|
+
high = [r["mean"] + 1.96 * r["se"] for r in points]
|
|
76
|
+
style = styles[arm]
|
|
77
|
+
ax.fill_between(turns, low, high, color=style["color"], alpha=0.12, linewidth=0)
|
|
78
|
+
ax.plot(
|
|
79
|
+
turns, mean, color=style["color"], linestyle=style["linestyle"], linewidth=2,
|
|
80
|
+
marker="o", markersize=4.5, markeredgecolor="white", markeredgewidth=1,
|
|
81
|
+
label=style["label"],
|
|
82
|
+
) # fmt: skip
|
|
83
|
+
ax.set_xlabel("turn (questions asked)", color=INK_MUTED)
|
|
84
|
+
ax.set_ylabel(LABELS.get(metric, metric), color=INK_MUTED)
|
|
85
|
+
ax.set_xticks(range(budget + 1))
|
|
86
|
+
ax.set_title(f"{title}: {LABELS.get(metric, metric)}, K = {budget}", color=INK, fontsize=10)
|
|
87
|
+
ax.grid(True, color=GRID, linewidth=0.8)
|
|
88
|
+
ax.set_axisbelow(True)
|
|
89
|
+
for side in ("top", "right"):
|
|
90
|
+
ax.spines[side].set_visible(False)
|
|
91
|
+
for side in ("left", "bottom"):
|
|
92
|
+
ax.spines[side].set_color(GRID)
|
|
93
|
+
ax.tick_params(colors=INK_MUTED)
|
|
94
|
+
ax.legend(title="selector · updater · phrasing", fontsize=8, title_fontsize=8, frameon=False)
|
|
95
|
+
fig.tight_layout()
|
|
96
|
+
path = Path(path)
|
|
97
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
98
|
+
# No software or date stamp, so the same data gives the same file.
|
|
99
|
+
fig.savefig(path, metadata={"Software": None})
|
|
100
|
+
plt.close(fig)
|
|
101
|
+
return path
|