Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions src/synthbench/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ def _provider_kwargs(
prompt_template=None,
effort=None,
elicitation=None,
persona_pack=None,
):
"""Build constructor kwargs appropriate for *provider_name*.

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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=<id>: 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
Expand Down Expand Up @@ -345,6 +365,7 @@ def run(
effort,
prompt_template,
elicitation,
persona_pack,
submit_after,
wait,
submit_api_key,
Expand Down Expand Up @@ -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,
Expand All @@ -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)

Expand All @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
6 changes: 6 additions & 0 deletions src/synthbench/datasets/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
42 changes: 42 additions & 0 deletions src/synthbench/datasets/globalopinionqa.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import hashlib
import json
import re
from pathlib import Path

from synthbench.datasets.base import Dataset, Question
Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -231,6 +272,7 @@ def _download_and_process(self) -> list[Question]:
options=options,
human_distribution=dist,
survey=survey,
respondent_population=self._respondent_population(selections),
)
)

Expand Down
100 changes: 96 additions & 4 deletions src/synthbench/providers/althing.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
Provider,
ProviderError,
Response,
pool_distributions,
)

_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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",
Expand All @@ -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(
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

# ==================================================================
Expand All @@ -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":
Expand Down Expand Up @@ -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.

Expand All @@ -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()

Expand Down
Loading
Loading