ProWM-Bench / prowm_bench /scoring.py
simonlqy's picture
Initial release of ProWM-Bench v1.0.0 (part 4)
d9befd2 verified
Raw History Blame Contribute Delete
10.2 kB
"""The five paper metrics, with the original validation and denominators.
Prediction JSONL accepts either one row per request:
{"item_id": "...", "branch": "official_tests", "prediction": {...},
"finish_reason": "stop"}
or one row per item:
{"item_id": "...", "branches": {"official_tests": {"prediction": {...}}, ...}}
Use "response": "<raw assistant answer>" instead of prediction to score raw
JSON text. Duplicate item/branch pairs and unknown IDs are rejected. Missing,
truncated, unparsable and contract-invalid responses receive zero; they do not
shrink the eligible denominator. Scores use a 0..1 scale.
"""
from __future__ import annotations
import json
import math
from collections.abc import Mapping
from pathlib import Path
from ._compat import (
BRANCHES, _document_delta_grade, json_equal, normalize_text,
parse_answer, validate_oneshot_prediction,
)
from .dataset import Dataset, index_rows, read_jsonl
METRICS = ('Obs EM', 'Test Resolved', 'Test All-EM', 'Render Field-EM', 'Render DOM-DeltaF1')
BRANCH_METRICS = {
'observation_repository': METRICS[:1],
'official_tests': METRICS[1:3],
'render_product': METRICS[3:],
}
def load_predictions(path: str | Path, item_ids: set[str]) -> dict[tuple[str, str], dict]:
predictions = {}
for row in read_jsonl(Path(path)):
item_id = row.get('item_id')
if item_id not in item_ids:
raise ValueError(f'prediction names an unknown item_id: {item_id!r}')
if 'branch' in row and 'branches' in row:
raise ValueError('use either branch or branches, not both')
if 'branch' in row:
branch_rows = {row['branch']: row}
else:
branch_rows = row.get('branches')
if not isinstance(branch_rows, Mapping):
raise ValueError('prediction row requires branch or branches')
for branch, entry in branch_rows.items():
if branch not in BRANCHES:
raise ValueError(f'unknown prediction branch: {branch!r}')
key = item_id, branch
if key in predictions:
raise ValueError(f'duplicate prediction; repeated attempts are not allowed: {key}')
if not isinstance(entry, Mapping):
entry = {'prediction': entry}
elif 'prediction' not in entry and 'response' not in entry:
entry = {'prediction': dict(entry)}
if 'prediction' in entry and 'response' in entry:
raise ValueError('use either prediction or response, not both')
predictions[key] = dict(entry)
return predictions
def decode_prediction(entry: dict | None, *, allow_json_fences: bool = False) -> tuple[dict | None, str | None]:
if entry is None:
return None, 'missing'
finish = entry.get('finish_reason')
if finish is None:
responses = entry.get('trace', {}).get('responses') or []
if responses:
finish = responses[-1].get('finish_reason')
if finish in {'length', 'max_tokens'}:
return None, 'truncated'
if entry.get('error') or entry.get('discard_reason') or entry.get('discarded'):
return None, 'discarded'
value = entry.get('prediction') if 'prediction' in entry else entry.get('response')
try:
if isinstance(value, str):
if allow_json_fences:
text = value.strip()
lines = text.splitlines()
if len(lines) >= 3 and lines[0] in {'```', '```json'} and lines[-1] == '```':
value = '\n'.join(lines[1:-1])
value = parse_answer(value)
if not isinstance(value, dict):
return None, 'missing_or_non_object'
# Reject NaN/Infinity even for callers of the Python API.
json.dumps(value, allow_nan=False)
except (ValueError, TypeError, RecursionError):
return None, 'invalid_json'
return value, None
def score_item(public: dict, target: dict, predictions: dict[str, dict], *,
allow_json_fences: bool = False) -> dict:
"""Return per-item scores; None denotes an ineligible target, never a miss."""
test = target['branches']['official_tests']
render = target['branches']['render_product']
current = public['branches']['render_product']['current_product_state']
eligible = {
'Obs EM': True,
'Test Resolved': bool(test.get('available')),
'Test All-EM': bool(test.get('available')),
'Render Field-EM': len(render.get('decision_fields_scoreable') or []) > 0,
'Render DOM-DeltaF1': _document_delta_grade({}, render.get('document_tree'), current.get('document_tree'))['target_changed'],
}
scores = {name: 0.0 if eligible[name] else None for name in METRICS}
branches = {}
for branch in BRANCHES:
value, error = decode_prediction(predictions.get(branch), allow_json_fences=allow_json_fences)
p = public['branches'][branch]
t = target['branches'][branch]
if error is None:
environment_schema = (p.get('output_schema') or {}).get('environment') or {}
patch = 'repository_patch' if ('repository_patch' in environment_schema or
'repository_patch' in (t.get('environment') or {})) else 'step_patch'
try:
error = validate_oneshot_prediction(
branch, value,
required_oracle_ids=tuple(str(v['oracle_id']) for v in p.get('oracle_queries', []) if v.get('oracle_id')),
required_decision_fields=tuple(str(v) for v in p.get('decision_relevant_fields', [])),
environment_patch_field=patch,
)
except (ValueError, TypeError, AttributeError, OverflowError):
error = 'invalid_contract_types'
branches[branch] = {'valid': error is None, 'error': error}
if error is not None:
continue
if branch == 'observation_repository':
scores['Obs EM'] = float(normalize_text(value['observation'].get('output_text')) ==
normalize_text(t['observation'].get('output_text')))
elif branch == 'official_tests' and bool(t.get('available')):
scores['Test Resolved'] = float(t.get('resolved') is not None and json_equal(value.get('resolved'), t['resolved']))
# Explicit null is allowed by the one-shot contract, but the
# original scorer does not turn it into a submitted "unknown".
predicted = {v['oracle_id']: v['status'] for v in value['oracles']
if isinstance(v.get('status'), str)}
oracles = {str(v['oracle_id']): v for v in t.get('oracles', []) if v.get('oracle_id') and v.get('scoreable') is True}
scores['Test All-EM'] = float(bool(oracles) and all(
predicted.get(key, 'missing') == str(v.get('status') or 'unknown') for key, v in oracles.items()))
elif branch == 'render_product':
if eligible['Render Field-EM']:
scores['Render Field-EM'] = float(all(
field in value['decision_fields'] and json_equal(value['decision_fields'][field], t['decision_fields'].get(field))
for field in t['decision_fields_scoreable']))
if eligible['Render DOM-DeltaF1']:
scores['Render DOM-DeltaF1'] = _document_delta_grade(
value.get('document_tree'), t.get('document_tree'), current.get('document_tree'))['changed_target_f1']
return {'item_id': public['item_id'], 'scores': scores, 'branches': branches}
def score(dataset: Dataset, predictions: str | Path, *, allow_json_fences: bool = False,
details: bool = False) -> dict:
"""Score against the complete frozen subset, even when predictions are partial."""
indexed = load_predictions(predictions, set(dataset.items))
targets = index_rows(dataset.directory / 'targets.jsonl')
if set(targets) != set(dataset.items):
raise ValueError('target membership differs from the frozen input population')
grades = [score_item(item, targets[item_id],
{b: indexed[item_id, b] for b in BRANCHES if (item_id, b) in indexed},
allow_json_fences=allow_json_fences)
for item_id, item in dataset.items.items()]
denominators = {name: sum(row['scores'][name] is not None for row in grades) for name in METRICS}
metrics = {name: (sum(row['scores'][name] or 0.0 for row in grades) / denominators[name]
if denominators[name] else None) for name in METRICS}
result = {
'schema': 'prowm-bench-five-metrics.v1', 'subset': dataset.subset,
'item_count': len(dataset), 'expected_branch_predictions': len(dataset) * len(BRANCHES),
'submitted_branch_predictions': len(indexed), 'metrics': metrics,
'percentages': {k: 100 * v if v is not None else None for k, v in metrics.items()},
'denominators': denominators, 'missing_policy': 'zero',
'allow_json_fences': allow_json_fences,
'valid_branches': {b: sum(row['branches'][b]['valid'] for row in grades) for b in BRANCHES},
}
if details:
result['items'] = grades
return result
def check_reference(dataset: Dataset) -> dict:
"""Compare all five metrics with the existing frozen experiment report."""
from .dataset import read_json
expected = read_json(dataset.root / 'examples/reference_metrics.json')['subsets'][dataset.subset]
actual = score(dataset, dataset.root / 'examples/reference_predictions' / (dataset.subset + '.jsonl'))
if actual['denominators'] != expected['denominators']:
raise ValueError(f'reference denominators differ for {dataset.subset}')
for name, value in expected['metrics'].items():
if not math.isclose(actual['metrics'][name], value, rel_tol=0, abs_tol=1e-12):
raise ValueError(f'reference score differs for {dataset.subset}/{name}: {actual["metrics"][name]} != {value}')
return {'ok': True, 'subset': dataset.subset, 'metrics': actual['metrics'], 'denominators': actual['denominators']}