Skip to content
Draft
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
12 changes: 3 additions & 9 deletions policybench/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1863,19 +1863,13 @@ def main():
reference_policyengine_bundles,
resolve_reference_digest,
)
from policybench.reference_exclusions import (
exclusions_path_for,
load_reference_exclusions,
split_reference,
)
from policybench.reference_exclusions import split_reference_csv

gt = pd.read_csv(args.ground_truth)
# An adjacent reference_exclusions.json removes outputs whose reference
# depends on an input the data never carried; they are scored for no model.
reference_exclusions = load_reference_exclusions(
exclusions_path_for(Path(args.ground_truth))
gt, excluded_reference, reference_exclusions = split_reference_csv(
Path(args.ground_truth)
)
gt, excluded_reference = split_reference(gt, reference_exclusions)
if not excluded_reference.empty:
print(
f"reference exclusions: {len(excluded_reference)} outputs removed "
Expand Down
6 changes: 4 additions & 2 deletions policybench/held_references.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,13 +277,15 @@ def apply_held_references(
),
None,
)
# As the flag gives them: a malformed cluster is listed, not coerced.
# A malformed cluster still gets a report entry.
predictions = cluster.get("predictions")
predictions = dict(predictions) if isinstance(predictions, dict) else {}
listed = {
"answer": cluster.get("answer"),
"n_models": cluster.get("n_models"),
"n_top": cluster.get("n_top", 0),
"models": list(cluster.get("models") or []),
"predictions": dict(cluster.get("predictions") or {}),
"predictions": predictions,
}
if covering is None:
unexplained.append(listed)
Expand Down
41 changes: 36 additions & 5 deletions policybench/reference_exclusions.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,12 +145,17 @@ def verify_exclusions_against_reference(
"""Every excluded output must exist and carry the recorded frozen value."""
if not exclusions:
return
indexed = reference.set_index(["scenario_id", "variable"])["value"]
indexed = reference.set_index(
[reference["scenario_id"].map(str), reference["variable"].map(str)]
)["value"]
for entry in exclusions:
key = (str(entry["scenario_id"]), str(entry["variable"]))
if key not in indexed.index:
raise ReferenceExclusionError(f"excluded output {key} is not a reference")
actual, frozen = float(indexed[key]), float(entry["frozen_value"])
matches = indexed.loc[[key]]
if len(matches) != 1:
raise ReferenceExclusionError(f"excluded output {key} is ambiguous")
actual, frozen = float(matches.iloc[0]), float(entry["frozen_value"])
if not math.isfinite(actual) or not math.isfinite(frozen):
raise ReferenceExclusionError(
f"excluded output {key}: non-finite reference"
Expand Down Expand Up @@ -183,9 +188,35 @@ def split_reference(
)


def scored_reference_for(reference_path: Path) -> tuple[pd.DataFrame, list[dict]]:
"""Read a reference CSV and drop its excluded outputs."""
def split_reference_csv(
reference_path: Path,
) -> tuple[pd.DataFrame, pd.DataFrame, list[dict]]:
"""Split a reference CSV using its adjacent exclusion record."""
reference = pd.read_csv(reference_path)
exclusions = load_reference_exclusions(exclusions_path_for(reference_path))
scored, _ = split_reference(reference, exclusions)
if exclusions and not reference.empty:
# Keep the inferred dtypes for joins and guard the spelling of each key.
columns = ["scenario_id", "variable"]
raw_keys = pd.read_csv(
reference_path, usecols=columns, dtype=str, keep_default_na=False
)
keys = exclusion_keys(exclusions)
for raw_key, parsed in zip(
raw_keys[columns].itertuples(index=False, name=None),
reference[columns].itertuples(index=False, name=None),
strict=True,
):
parsed_key = tuple(map(str, parsed))
if raw_key != parsed_key and (raw_key in keys or parsed_key in keys):
raise ReferenceExclusionError(
f"ambiguous exclusion key: CSV key {raw_key} "
f"was parsed as {parsed_key}"
)
scored, excluded = split_reference(reference, exclusions)
return scored, excluded, exclusions


def scored_reference_for(reference_path: Path) -> tuple[pd.DataFrame, list[dict]]:
"""Read a reference CSV and drop its excluded outputs."""
scored, _, exclusions = split_reference_csv(reference_path)
return scored, exclusions
25 changes: 25 additions & 0 deletions tests/test_cli_analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
from pathlib import Path

import pandas as pd
import pytest

from policybench.cli import main
from policybench.reference_exclusions import ReferenceExclusionError

BUNDLE = {
"model_package": "policyengine-us",
Expand Down Expand Up @@ -130,3 +132,26 @@ def test_analyze_export_keeps_excluded_rows_and_the_exclusion_record(
for models in variables.values()
)
assert row_count == 6


def test_analyze_rejects_exclusion_for_a_coerced_csv_id(tmp_path, monkeypatch):
reference_path = tmp_path / "reference_outputs.csv"
reference_path.write_text("scenario_id,variable,value\n042,ssi,0\n43,snap,500\n")
(tmp_path / "reference_exclusions.json").write_text(
json.dumps({"exclusions": [{**EXCLUSION, "scenario_id": "42"}]})
)
monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
monkeypatch.setattr(
"sys.argv",
[
"policybench",
"analyze",
"-g",
str(reference_path),
"-p",
str(tmp_path / "predictions.csv"),
],
)

with pytest.raises(ReferenceExclusionError, match="was parsed as"):
main()
19 changes: 14 additions & 5 deletions tests/test_held_references.py
Original file line number Diff line number Diff line change
Expand Up @@ -1496,13 +1496,22 @@ def test_disk_loader_validates_document(tmp_path):
load_held_references(path)


def test_predictions_must_be_a_mapping():
@pytest.mark.parametrize(
"predictions",
[[[model, 50.0] for model in MEMBERS], [50.0]],
ids=["pairs", "values"],
)
def test_predictions_must_be_a_mapping(predictions):
flag = _flag()
cluster = flag["clusters"][0]
cluster["predictions"] = [[model, 50.0] for model in cluster["models"]]
flag["clusters"][0]["predictions"] = predictions
original = copy.deepcopy(flag)
kept, report = apply_held_references([flag], [_record()], PROMPTS)
assert kept == [flag]
assert report["not_applied"][0]["reason"] == "unexplained_consensus"
assert flag == original
assert kept == [original]
(stale,) = report["not_applied"]
assert stale["reason"] == "unexplained_consensus"
(unexplained,) = stale["unexplained_clusters"]
assert unexplained["predictions"] == {}


def test_integer_member_predictions_receive_the_correct_explanation():
Expand Down
75 changes: 68 additions & 7 deletions tests/test_reference_exclusion_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
ReferenceExclusionError,
exclusion_lookup,
load_reference_exclusions,
scored_reference_for,
split_reference,
verify_exclusions_against_reference,
)
Expand All @@ -35,8 +36,13 @@ def test_exclusion_nonnumeric_string(tmp_path):

@pytest.mark.parametrize(
("frozen_value", "alternative_value"),
[(0, 1e-6), (1e-6, 0)],
ids=["alternative-higher", "alternative-lower"],
[(0, 1e-6), (1e-6, 0), (1e-6, 2e-6), (2e-6, 1e-6)],
ids=[
"alternative-higher",
"alternative-lower",
"nonzero-alternative-higher",
"nonzero-alternative-lower",
],
)
def test_exclusion_readings_at_micro_threshold(
tmp_path, frozen_value, alternative_value
Expand Down Expand Up @@ -69,6 +75,54 @@ def test_exclusion_keys_normalize_scenario_id():
assert excluded["scenario_id"].tolist() == ["42"]


def test_exclusion_keys_normalize_reference_scenario_id():
reference = _reference().assign(scenario_id=[42, 42, 43])
_, excluded = split_reference(reference, [_entry(scenario_id="42")])
assert list(zip(excluded["scenario_id"], excluded["variable"])) == [(42, "ssi")]


@pytest.mark.parametrize("csv_id", ["042", "42"])
def test_scored_reference_checks_csv_key_spelling(tmp_path, csv_id):
reference_path = tmp_path / "reference_outputs.csv"
reference_path.write_text(
f"scenario_id,variable,value\n{csv_id},ssi,0\n43,snap,500\n"
)
(tmp_path / FILENAME).write_text(
json.dumps({"exclusions": [_entry(scenario_id="42")]})
)

if csv_id == "042":
with pytest.raises(ReferenceExclusionError, match="was parsed as"):
scored_reference_for(reference_path)
return

scored, _ = scored_reference_for(reference_path)
expected = pd.read_csv(reference_path).iloc[1:].reset_index(drop=True)
pd.testing.assert_frame_equal(scored, expected)


@pytest.fixture
def reference_with_colliding_keys():
return _reference().assign(
scenario_id=pd.Series([42, "42", "43"], dtype=object),
variable=["ssi", "ssi", "snap"],
value=[0.0, 0.0, 500.0],
)


def test_split_excludes_unique_key_among_colliding_keys(reference_with_colliding_keys):
reference = reference_with_colliding_keys
entry = _entry(scenario_id="43", variable="snap", frozen_value=500.0)
scored, excluded = split_reference(reference, [entry])
pd.testing.assert_frame_equal(scored, reference.iloc[:2])
pd.testing.assert_frame_equal(excluded, reference.iloc[2:].reset_index(drop=True))


def test_split_rejects_requested_colliding_key(reference_with_colliding_keys):
with pytest.raises(ReferenceExclusionError, match="ambiguous"):
split_reference(reference_with_colliding_keys, [_entry(scenario_id="42")])


def test_exclusion_lookup_preserves_key_order_and_entry():
record = _entry(scenario_id=42)
assert exclusion_lookup([record]) == {("42", "ssi"): record}
Expand All @@ -89,10 +143,14 @@ def test_exclusion_reference_tolerance_boundary(at_tolerance, outside_tolerance)


def test_no_exclusions_returns_empty_slice():
reference = _reference().rename_axis("source")
reference = _reference().set_axis(pd.Index([10, 20, 30], name="source"))
original = reference.copy()
expected_scored = original.reset_index(drop=True)
expected_excluded = original.iloc[:0]
scored, excluded = split_reference(reference, [])
pd.testing.assert_frame_equal(scored, reference.reset_index(drop=True))
pd.testing.assert_frame_equal(excluded, reference.iloc[:0])
pd.testing.assert_frame_equal(reference, original, check_exact=True)
pd.testing.assert_frame_equal(scored, expected_scored)
pd.testing.assert_frame_equal(excluded, expected_excluded)


def test_split_refuses_a_mismatched_frozen_value():
Expand All @@ -101,9 +159,12 @@ def test_split_refuses_a_mismatched_frozen_value():


def test_split_preserves_scored_columns_and_reindexes():
reference = _reference()
reference = _reference().set_axis(pd.Index([10, 20, 30], name="source"))
original = reference.copy()
expected = original.iloc[1:].reset_index(drop=True)
scored, _ = split_reference(reference, [_entry()])
pd.testing.assert_frame_equal(scored, reference.iloc[1:].reset_index(drop=True))
pd.testing.assert_frame_equal(reference, original, check_exact=True)
pd.testing.assert_frame_equal(scored, expected)


@pytest.mark.parametrize(
Expand Down