diff --git a/src/synthbench/cli.py b/src/synthbench/cli.py index d811ce09..5d4d80e5 100644 --- a/src/synthbench/cli.py +++ b/src/synthbench/cli.py @@ -68,6 +68,7 @@ def _provider_kwargs( prompt_template=None, effort=None, elicitation=None, + persona_pack=None, ): """Build constructor kwargs appropriate for *provider_name*. @@ -109,6 +110,13 @@ def _provider_kwargs( "--elicitation is only supported by the althing provider." ) kwargs["elicitation"] = elicitation + if persona_pack is not None: + if provider_name not in ("althing", "synthpanel"): + raise click.UsageError( + "--persona-pack is only supported by the althing provider " + "(althing is the conditioning harness)." + ) + kwargs["persona_pack"] = persona_pack if effort is not None: if provider_name in ("althing", "synthpanel"): raise click.UsageError( @@ -269,6 +277,18 @@ def main(): "(tpl=structured) — a distinct leaderboard identity." ), ) +@click.option( + "--persona-pack", + default=None, + help=( + "althing population pack to condition on (althing only), e.g. " + "global-respondents. Each question is answered by the pack's " + "personas that match the question's respondent population (for " + "globalopinionqa, the countries that answered it), with samples " + "split as althing allocates them. Stamped as pack=: a distinct " + "leaderboard identity." + ), +) # sb-ymux: `synthbench run --submit` wiring. Keeping all submission flags on # the `run` subcommand (not a new subcommand) means a user's first try at # "benchmark → leaderboard" is literally one invocation. --wait folds the @@ -345,6 +365,7 @@ def run( effort, prompt_template, elicitation, + persona_pack, submit_after, wait, submit_api_key, @@ -411,6 +432,7 @@ def run( effort, prompt_template, elicitation, + persona_pack=persona_pack, submit_after=submit_after, wait=wait, submit_api_key=submit_api_key, @@ -424,12 +446,12 @@ def run( def _run_benchmark_or_exit(coro) -> None: - """Run a benchmark coroutine, turning an empty question set into a clean CLI error.""" - from synthbench.runner import EmptyQuestionSetError + """Run a benchmark coroutine, turning setup errors into a clean CLI exit.""" + from synthbench.runner import EmptyQuestionSetError, PopulationUnsupportedError try: asyncio.run(coro) - except EmptyQuestionSetError as exc: + except (EmptyQuestionSetError, PopulationUnsupportedError) as exc: click.echo(f"Error: {exc}", err=True) sys.exit(2) @@ -455,6 +477,7 @@ async def _run_async( prompt_template=None, elicitation=None, *, + persona_pack=None, submit_after: bool = False, wait: bool = False, submit_api_key=None, @@ -507,6 +530,7 @@ async def _run_async( prompt_template=prompt_template, effort=effort, elicitation=elicitation, + persona_pack=persona_pack, ) try: prov = load_provider(provider_name, **provider_kwargs) @@ -558,6 +582,8 @@ async def _run_async( click.echo(f" Dataset: {ds.name}") click.echo(f" Questions: {suite_label}") click.echo(f" Samples/q: {samples}") + if persona_pack: + click.echo(f" Persona pack: {persona_pack}") if effort: click.echo(f" Effort: {effort}") if demographics: diff --git a/src/synthbench/datasets/base.py b/src/synthbench/datasets/base.py index 3cd190a5..ee8441d4 100644 --- a/src/synthbench/datasets/base.py +++ b/src/synthbench/datasets/base.py @@ -49,6 +49,12 @@ class Question: human_distribution: dict[str, float] survey: str = "" topic: str = "" + respondent_population: dict[str, list[str]] | None = None + """Who the human answers come from, as ``{attribute: members}`` with one + entry per group the ground truth averages over (repeats kept), e.g. + ``{"country": ["Brazil", "Brazil", "Japan"]}``. Passed to providers that + condition on a population pack (althing ``persona_pack``). ``None`` when + the dataset doesn't expose it.""" def __post_init__(self): total = sum(self.human_distribution.values()) diff --git a/src/synthbench/datasets/globalopinionqa.py b/src/synthbench/datasets/globalopinionqa.py index bd8c83e0..84145072 100644 --- a/src/synthbench/datasets/globalopinionqa.py +++ b/src/synthbench/datasets/globalopinionqa.py @@ -12,6 +12,7 @@ import hashlib import json +import re from pathlib import Path from synthbench.datasets.base import Dataset, Question @@ -70,6 +71,34 @@ def _aggregate_distributions( return dist +# Label variants in GlobalOpinionQA (Pew Global Attitudes + WVS) mapped to +# the plain country names used by althing's global-respondents pack. +_COUNTRY_ALIASES = { + "Britain": "Great Britain", + "Czech Rep.": "Czechia", + "S. Korea": "South Korea", + "S. Africa": "South Africa", + "Palest. ter.": "Palestinian territories", + "Taiwan ROC": "Taiwan", + "Bosnia Herzegovina": "Bosnia and Herzegovina", + "Hong Kong SAR": "Hong Kong", + "Macau SAR": "Macau", +} +_SAMPLE_NOTE_RE = re.compile( + r"\s*\((?:Non-national|Current national|Old national) sample\)$" +) + + +def canonical_country(label: str) -> str: + """Plain country name for a GlobalOpinionQA selections label. + + Drops sample annotations ("Brazil (Non-national sample)" -> "Brazil") + and maps abbreviations ("S. Korea" -> "South Korea"). + """ + base = _SAMPLE_NOTE_RE.sub("", label).strip() + return _COUNTRY_ALIASES.get(base, base) + + class GlobalOpinionQADataset(Dataset): """GlobalOpinionQA: 2,556 questions across 138 countries.""" @@ -138,10 +167,22 @@ def _load_cached(self, path: Path) -> list[Question]: options=options, human_distribution=dist, survey=q.get("survey", ""), + respondent_population=self._respondent_population(q["selections"]), ) ) return questions + def _respondent_population(self, selections: dict) -> dict[str, list[str]]: + """Countries this question's ground truth averages over, as plain names. + + One entry per ``selections`` label, so a country surveyed twice (a + national and a non-national sample) appears twice, matching its + weight in the aggregate. With ``--country`` the target is that one + country. + """ + labels = [self._country] if self._country is not None else sorted(selections) + return {"country": [canonical_country(label) for label in labels]} + def _save_cache(self, raw_rows: list[dict]) -> None: self._data_dir.mkdir(parents=True, exist_ok=True) data = { @@ -231,6 +272,7 @@ def _download_and_process(self) -> list[Question]: options=options, human_distribution=dist, survey=survey, + respondent_population=self._respondent_population(selections), ) ) diff --git a/src/synthbench/providers/althing.py b/src/synthbench/providers/althing.py index c1c76fbe..7b10cde2 100644 --- a/src/synthbench/providers/althing.py +++ b/src/synthbench/providers/althing.py @@ -24,6 +24,7 @@ Provider, ProviderError, Response, + pool_distributions, ) _LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" @@ -59,6 +60,26 @@ _HAS_SYNTH_PANEL_API = False +def _load_population_pack(pack_id: str, *, use_api: bool) -> list[dict[str, Any]]: + """Load an althing population pack, failing early with a clear message.""" + if not use_api: + raise ImportError( + "persona_pack requires the althing Python API (it is not supported by the " + "althing CLI fallback or with --prompt-template)." + ) + try: + from althing.population import load_pack_personas + except ImportError as exc: + raise ImportError( + "persona_pack requires althing with population packs (althing.population). " + "Upgrade althing." + ) from exc + try: + return load_pack_personas(pack_id) + except FileNotFoundError as exc: + raise ImportError(f"althing persona pack {pack_id!r} not found") from exc + + def _pick_raw_sample(samples: list[tuple[str, Any]], counts: Counter) -> dict | None: """Pick one auditable ``{"raw_text", "selected_option"}`` sample. @@ -278,8 +299,13 @@ class AlthingProvider(Provider): to ``althing panel run`` via subprocess. Supports althing v0.6.0+ flags: --models, --temperature, --profile. + + With ``persona_pack`` set, questions are answered by an althing + population pack (see :meth:`get_population_distribution`). """ + persona_pack: str | None = None + def __init__( self, model: str = "haiku", @@ -288,6 +314,7 @@ def __init__( prompt_template: str | None = None, althing_path: str | None = None, elicitation: str = "natural", + persona_pack: str | None = None, ): if elicitation not in ELICITATION_MODES: raise ValueError( @@ -318,6 +345,12 @@ def __init__( self._use_api = _HAS_SYNTH_PANEL_API and prompt_template is None self._client: Any = None self._executor: ThreadPoolExecutor | None = None + self.persona_pack = persona_pack + self._pack_personas: list[dict[str, Any]] = [] + if persona_pack is not None: + self._pack_personas = _load_population_pack( + persona_pack, use_api=self._use_api + ) if self._use_api: self._client = LLMClient() @@ -354,6 +387,10 @@ def name(self) -> str: # forced extraction is a different elicitation surface, not a # silent change to the natural-prose rows. parts.append("tpl=structured") + if self.persona_pack: + # Population-conditioned runs are a different experiment: the + # knob feeds build_config_id so they get their own config_id. + parts.append(f"pack={self.persona_pack}") return " ".join(parts) @property @@ -389,6 +426,10 @@ def prompt_template_source(self) -> str: except OSError: override = "" base += "\n---template---\n" + override + if self.persona_pack: + base += f"\n---persona-pack:{self.persona_pack}---\n" + json.dumps( + self._pack_personas, sort_keys=True + ) return base # ================================================================== @@ -405,10 +446,19 @@ async def respond( # ── Direct API path ────────────────────────────────────────── def _build_api_request( - self, question: str, options: list[str], persona: PersonaSpec | None + self, + question: str, + options: list[str], + persona: PersonaSpec | None, + system: str | None = None, ) -> "CompletionRequest": - """Build one CompletionRequest, honouring the elicitation mode.""" - system = _build_system_prompt(persona) + """Build one CompletionRequest, honouring the elicitation mode. + + *system* overrides the persona prompt (population packs render + theirs with althing's ``persona_system_prompt``). + """ + if system is None: + system = _build_system_prompt(persona) user_text = _build_question_text(question, options) kwargs: dict[str, Any] = {} if self._elicitation == "structured": @@ -505,12 +555,54 @@ async def get_distribution( # ── Direct API path ────────────────────────────────────────── + async def get_population_distribution( + self, + question: str, + options: list[str], + *, + population: dict[str, list[str]], + n_samples: int, + seed: str, + ) -> Distribution: + """Sample *question* across the persona pack, matched to *population*. + + althing decides which personas answer and how many samples each + gets (``althing.population.allocate_population``) and renders each + persona's system prompt; this provider samples every share and + pools them by sample count. + """ + from althing.population import allocate_population + from althing.prompts import persona_system_prompt + + if len(population) != 1: + raise ProviderError( + f"population must have exactly one attribute, got {sorted(population)}" + ) + ((key, members),) = population.items() + allocation = allocate_population( + self._pack_personas, + key=key, + members=members, + n_samples=n_samples, + seed=seed, + ) + dists = await asyncio.gather( + *( + self._get_distribution_api( + question, options, None, k, system=persona_system_prompt(persona) + ) + for persona, k in allocation + ) + ) + return pool_distributions(list(dists), len(options)) + async def _get_distribution_api( self, question: str, options: list[str], persona: PersonaSpec | None, n_samples: int | None, + system: str | None = None, ) -> Distribution: """Concurrent direct API calls — no subprocess overhead. @@ -521,7 +613,7 @@ async def _get_distribution_api( a fabricated distribution. """ effective_samples = n_samples if n_samples is not None else 30 - request = self._build_api_request(question, options, persona) + request = self._build_api_request(question, options, persona, system=system) loop = asyncio.get_running_loop() diff --git a/src/synthbench/providers/base.py b/src/synthbench/providers/base.py index 199c9be4..6e24fdb2 100644 --- a/src/synthbench/providers/base.py +++ b/src/synthbench/providers/base.py @@ -196,6 +196,52 @@ async def close(self) -> None: def name(self) -> str: ... +def pool_distributions(dists: list[Distribution], n_options: int) -> Distribution: + """Pool distributions sampled under different personas, weighted by samples. + + Each input's ``probabilities`` and ``refusal_probability`` are fractions + of its own ``n_samples``; pooling converts them back to counts so a + persona with 2 samples weighs twice one with 1. Parse failures, token + usage, and infra-error counts are summed; the first raw sample is kept. + """ + counts = [0.0] * n_options + refusals = 0.0 + total = 0 + parse_failures = 0 + usage: dict[str, int] = {} + infra_errors = 0 + raw_sample = None + for d in dists: + n = d.n_samples or 0 + total += n + refusals += d.refusal_probability * n + parse_failures += d.n_parse_failures + for i, p in enumerate(d.probabilities[:n_options]): + counts[i] += p * n + meta = d.metadata or {} + for k, v in (meta.get("usage") or {}).items(): + if isinstance(v, (int, float)): + usage[k] = usage.get(k, 0) + v + infra_errors += meta.get("n_infra_errors", 0) or 0 + if raw_sample is None and isinstance(meta.get("raw_sample"), dict): + raw_sample = meta["raw_sample"] + metadata: dict = {} + if usage: + metadata["usage"] = usage + if infra_errors: + metadata["n_infra_errors"] = infra_errors + if raw_sample is not None: + metadata["raw_sample"] = raw_sample + return Distribution( + probabilities=[c / total if total else 0.0 for c in counts], + refusal_probability=refusals / total if total else 0.0, + method="sampling", + n_samples=total, + n_parse_failures=parse_failures, + metadata=metadata or None, + ) + + def build_persona_system_prompt(base_system: str, persona: PersonaSpec | None) -> str: """Build system prompt with optional persona conditioning. diff --git a/src/synthbench/runner.py b/src/synthbench/runner.py index bc9553ac..710946a5 100644 --- a/src/synthbench/runner.py +++ b/src/synthbench/runner.py @@ -27,6 +27,10 @@ from synthbench.stats import bootstrap_ci, question_set_hash +class PopulationUnsupportedError(ValueError): + """Raised when a population-conditioned run targets a dataset without populations.""" + + class EmptyQuestionSetError(ValueError): """Raised when a run would evaluate zero questions. @@ -448,12 +452,29 @@ async def run( ) ) - # Use batched evaluation when provider supports it - use_batch = self.provider.supports_distribution and hasattr( - self.provider, "batch_get_distribution" + # A provider with a persona pack conditions each question on the + # population its ground truth comes from (althing population packs). + persona_pack = getattr(self.provider, "persona_pack", None) + if persona_pack: + missing = [q.key for q in questions if not q.respondent_population] + if missing: + raise PopulationUnsupportedError( + f"--persona-pack needs each question's respondent population, which " + f"dataset '{self.dataset.name}' does not provide ({len(missing)} of " + f"{len(questions)} questions lack it). Supported on globalopinionqa." + ) + + # Use batched evaluation when provider supports it. Population runs + # sample per persona, which batch APIs don't take. + use_batch = ( + not persona_pack + and self.provider.supports_distribution + and hasattr(self.provider, "batch_get_distribution") ) - if use_batch: + if persona_pack: + results = await self._run_population(questions, progress_callback) + elif use_batch: results = await self._run_batched(questions, progress_callback) else: results = [] @@ -480,6 +501,7 @@ async def run( # Same contract for option matching (synthbench#352): absent # on pre-v2 files (= v1); never feeds build_config_id. "option_parser_version": OPTION_PARSER_VERSION, + **({"persona_pack": persona_pack} if persona_pack else {}), **_provider_reproducibility_hashes(self.provider), }, elapsed_seconds=elapsed, @@ -611,6 +633,36 @@ async def process_batch(batch_idx: int, batch: list[Question]): return [r for r in all_results if r is not None] + async def _run_population( + self, + questions: list[Question], + progress_callback=None, + ) -> list[QuestionResult]: + """Evaluate questions conditioned on each question's respondent population.""" + total = len(questions) + done = 0 + + async def one(question: Question) -> QuestionResult: + nonlocal done + async with self._semaphore: + t0 = time.monotonic() + dist = await self.provider.get_population_distribution( + question.text, + question.options, + population=question.respondent_population, + n_samples=self.samples_per_question, + seed=question.key, + ) + qr = self._build_question_result( + question, dist, latency_seconds=time.monotonic() - t0 + ) + done += 1 + if progress_callback: + progress_callback(done, total, qr) + return qr + + return list(await asyncio.gather(*(one(q) for q in questions))) + def _build_question_result( self, question: Question, diff --git a/tests/test_population_conditioning.py b/tests/test_population_conditioning.py new file mode 100644 index 00000000..fd912cfc --- /dev/null +++ b/tests/test_population_conditioning.py @@ -0,0 +1,261 @@ +"""Tests for population conditioning via althing persona packs (--persona-pack).""" + +from __future__ import annotations + +import json +from collections import Counter + +import click +import pytest + +from synthbench.cli import _provider_kwargs +from synthbench.config_id import build_config_id +from synthbench.datasets.base import Dataset, Question +from synthbench.datasets.globalopinionqa import ( + GlobalOpinionQADataset, + canonical_country, +) +from synthbench.providers.base import ( + Distribution, + Provider, + Response, + pool_distributions, +) +from synthbench.runner import BenchmarkRunner, PopulationUnsupportedError + + +def _question(key="GOQA_1", population=None) -> Question: + return Question( + key=key, + text="Do you approve?", + options=["Approve", "Disapprove"], + human_distribution={"Approve": 0.6, "Disapprove": 0.4}, + respondent_population=population, + ) + + +class _Dataset(Dataset): + def __init__(self, questions): + self._questions = questions + + @property + def name(self) -> str: + return "population-mock" + + def load(self, n=None): + return list(self._questions) + + def info(self) -> dict: + return {} + + +class _PackProvider(Provider): + """Stands in for AlthingProvider(persona_pack=...).""" + + persona_pack = "global-respondents" + + def __init__(self): + self.calls = [] + + @property + def name(self) -> str: + return "althing/mock pack=global-respondents" + + async def respond(self, question, options, *, persona=None) -> Response: + raise AssertionError("population runs must not use respond()") + + async def get_population_distribution( + self, question, options, *, population, n_samples, seed + ): + self.calls.append((population, n_samples, seed)) + return Distribution(probabilities=[0.25, 0.75], n_samples=n_samples) + + +# --------------------------------------------------------------------------- +# GlobalOpinionQA populations +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("label", "expected"), + [ + ("Brazil", "Brazil"), + ("Brazil (Non-national sample)", "Brazil"), + ("India (Old national sample)", "India"), + ("S. Korea", "South Korea"), + ("Britain", "Great Britain"), + ("Czech Rep.", "Czechia"), + ("Palest. ter.", "Palestinian territories"), + ], +) +def test_canonical_country(label, expected): + assert canonical_country(label) == expected + + +def _write_cache(tmp_path): + data = { + "dataset": "globalopinionqa", + "questions": [ + { + "key": "GOQA_1", + "text": "Do you approve?", + "options": ["Approve", "Disapprove"], + "selections": { + "Brazil": [0.7, 0.3], + "Brazil (Non-national sample)": [0.6, 0.4], + "S. Korea": [0.2, 0.8], + }, + "survey": "", + } + ], + } + (tmp_path / "questions.json").write_text(json.dumps(data), encoding="utf-8") + + +def test_globalopinionqa_population_keeps_repeats(tmp_path): + _write_cache(tmp_path) + (q,) = GlobalOpinionQADataset(data_dir=tmp_path).load() + assert q.respondent_population == {"country": ["Brazil", "Brazil", "South Korea"]} + + +def test_globalopinionqa_population_with_country_filter(tmp_path): + _write_cache(tmp_path) + (q,) = GlobalOpinionQADataset(data_dir=tmp_path, country="S. Korea").load() + assert q.respondent_population == {"country": ["South Korea"]} + + +def test_population_matches_global_respondents_pack(): + """Every canonical GlobalOpinionQA country must exist in althing's pack.""" + population = pytest.importorskip("althing.population") + from synthbench.datasets.globalopinionqa import _COUNTRY_ALIASES + + countries = { + p["country"] for p in population.load_pack_personas("global-respondents") + } + assert set(_COUNTRY_ALIASES.values()) <= countries + + +# --------------------------------------------------------------------------- +# Pooling +# --------------------------------------------------------------------------- + + +def test_pool_distributions_weights_by_sample_count(): + pooled = pool_distributions( + [ + Distribution( + probabilities=[1.0, 0.0], + n_samples=20, + metadata={"usage": {"input_tokens": 5}}, + ), + Distribution( + probabilities=[0.0, 0.5], + n_samples=10, + refusal_probability=0.5, + n_parse_failures=2, + metadata={ + "usage": {"input_tokens": 7}, + "raw_sample": {"raw_text": "B", "selected_option": "B"}, + }, + ), + ], + 2, + ) + assert pooled.n_samples == 30 + assert pooled.probabilities == pytest.approx([20 / 30, 5 / 30]) + assert pooled.refusal_probability == pytest.approx(5 / 30) + assert pooled.n_parse_failures == 2 + assert pooled.metadata["usage"] == {"input_tokens": 12} + assert pooled.metadata["raw_sample"]["raw_text"] == "B" + + +# --------------------------------------------------------------------------- +# Runner +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_runner_passes_population_and_stamps_pack(): + population = {"country": ["Brazil", "Japan"]} + provider = _PackProvider() + runner = BenchmarkRunner( + dataset=_Dataset([_question(population=population)]), + provider=provider, + samples_per_question=12, + ) + result = await runner.run() + + assert provider.calls == [(population, 12, "GOQA_1")] + assert result.questions[0].model_distribution["Disapprove"] == pytest.approx(0.75) + assert result.config["persona_pack"] == "global-respondents" + assert result.provider_name.endswith("pack=global-respondents") + + +@pytest.mark.asyncio +async def test_runner_rejects_dataset_without_population(): + runner = BenchmarkRunner( + dataset=_Dataset([_question()]), + provider=_PackProvider(), + samples_per_question=3, + ) + with pytest.raises(PopulationUnsupportedError, match="population-mock"): + await runner.run() + + +def test_pack_runs_get_their_own_config_id(): + base, _ = build_config_id( + "althing/claude-code:haiku tpl=structured", dataset="globalopinionqa" + ) + pack, _ = build_config_id( + "althing/claude-code:haiku tpl=structured pack=global-respondents", + dataset="globalopinionqa", + ) + assert base != pack + + +def test_persona_pack_rejected_for_non_althing_providers(): + with pytest.raises(click.UsageError, match="althing"): + _provider_kwargs( + "raw-anthropic", model="haiku", persona_pack="global-respondents" + ) + assert _provider_kwargs( + "althing", model="haiku", persona_pack="global-respondents" + )["persona_pack"] == ("global-respondents") + + +# --------------------------------------------------------------------------- +# AlthingProvider.get_population_distribution (needs althing.population) +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_althing_provider_samples_each_allocated_persona(): + pytest.importorskip("althing.population") + from synthbench.providers.althing import AlthingProvider + + prov = AlthingProvider(model="haiku", persona_pack="global-respondents") + seen: Counter = Counter() + + class _Client: + def send(self, request): + country = request.system.split("Country: ")[1].split(".")[0] + seen[country] += 1 + from althing.llm.models import CompletionResponse, TextBlock + + answer = "A" if country == "Japan" else "B" + return CompletionResponse( + id="x", model="haiku", content=[TextBlock(text=answer)] + ) + + prov._client = _Client() + dist = await prov.get_population_distribution( + "Do you approve?", + ["Approve", "Disapprove"], + population={"country": ["Brazil", "Brazil", "Japan"]}, + n_samples=30, + seed="GOQA_1", + ) + assert seen == {"Brazil": 20, "Japan": 10} + assert dist.n_samples == 30 + assert dist.probabilities == pytest.approx([10 / 30, 20 / 30]) + assert "pack=global-respondents" in prov.name