Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
11850d0
Price the analysis cost fallback only where row usage supports it
MaxGhenis Nov 20, 2026
0779cba
Say how batch rows share a request's usage in the fallback docstring
MaxGhenis Nov 20, 2026
200981b
Fill a cache-rate cost only from rows that each record one response (…
MaxGhenis Nov 20, 2026
9985a80
Report a cost effort_sensitivity cannot establish as null (review r1)
MaxGhenis Nov 20, 2026
0de3248
Merge origin/main (ab896ddc, #274) into fix/analysis-cost-fallback
MaxGhenis Nov 20, 2026
3a9abe3
Read the frozen cost and latency with get in --check-board (review r2)
MaxGhenis Nov 21, 2026
f68eff2
Refuse a freeze whose board lacks a model's cost, by name, before any…
MaxGhenis Nov 21, 2026
c9451f2
Accept only one-response count pairs and sum uncached tokens per row …
MaxGhenis Nov 21, 2026
375b86f
Report null for run figures some row does not record (review r2)
MaxGhenis Nov 21, 2026
314c273
Say when a model reaches the cost fallback and what a GPT row can pro…
MaxGhenis Nov 21, 2026
b3f9542
Read the frozen exact, within-1% and parsed counts with get too (revi…
MaxGhenis Nov 21, 2026
aacced1
Keep a run's tokens and time window when one household failed
MaxGhenis Nov 21, 2026
b7cb1c6
Refuse a negative or infinite published cost; say how a new model get…
MaxGhenis Nov 21, 2026
9135560
Drop general claims about when the harness records a cost (review r3)
MaxGhenis Nov 21, 2026
3797be1
Limit comments and docstrings to what the code and tests show
MaxGhenis Nov 21, 2026
7eb2422
Narrow four more comments a second claims check flagged
MaxGhenis Nov 21, 2026
b33ec0a
State the fill trigger as an empty cost sum (review r4)
MaxGhenis Nov 21, 2026
0513543
State when costUsd is left out as an empty cost sum (review r4)
MaxGhenis Nov 21, 2026
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
161 changes: 137 additions & 24 deletions policybench/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from policybench.config import (
BINARY_PROGRAMS,
GPT_RESPONSES_MODELS,
PRICE_OVERRIDES_PER_1M,
SEED,
)
Expand Down Expand Up @@ -1456,6 +1457,127 @@ def household_latency_seconds(predictions: pd.DataFrame) -> pd.Series:
)


# The row columns that count the provider responses a row's usage sums:
# eval_no_tools.NO_TOOLS_CALL_PROVENANCE_COLUMNS without the time (analysis
# does not import eval_no_tools, which imports litellm).
RESPONSE_COUNT_COLUMNS = ("live_calls", "cache_hit_calls")


def _override_fallback_cost(
rows: pd.DataFrame, model: str, rates: dict[str, float]
) -> float | None:
"""One model's cost from its price override, or None when it is unknown.

The rows priced are those that recorded both prompt and completion token
counts. A row missing either count adds nothing, and a model with no row
to price (Claude Fable 5's frozen board rows record no usage) gets no
cost, not $0.

A row's counts can sum several provider responses (a household's
re-requests and repair rounds in ``eval_no_tools.run_no_tools_eval``, a
batch cell's repair rounds), and can be an equal share of counts that
several rows divide. ``live_calls`` plus ``cache_hit_calls`` counts the
responses a row sums, or more when a response reported no usage.

- An override with only input and output rates prices the rows' summed
prompt tokens, cached ones included, at the input rate and their
completion tokens at the output rate. The sums take in every response
a row adds up, including one that reported a prompt count and no
completion count, or the reverse, which
``eval_no_tools._reconstruct_token_cost`` would not price.
- The Responses-API GPT models (``GPT_RESPONSES_MODELS``) charge every
token of a request above 272k prompt tokens at a higher rate. A row
holds a share of its responses' usage, and no row records how many
rows share a response, so a row at or below 272k does not show which
rate its request paid: a sum over a household's rows bounds a
request's prompt only when the frame holds every row the request was
split among, unrepaired, which the rows cannot show. A row that
records one response and a prompt share above 272k does prove the
higher rate for that response, and pricing the model that way would
need every priced row to prove it. The fill does not attempt it:
these models get no cost.
- An override with a ``cache_read`` or ``cache_write`` rate prices cached
and cache-write tokens at those rates (a rate it does not list is the
input rate), bounding each row's counts by its prompt count as the
reconstruction bounds a response's. The bound of a sum is not the sum
of the bounds, so it needs rows that each hold one response's usage:
every priced row must record one response (``live_calls`` and
``cache_hit_calls`` of 1 and 0, or 0 and 1), a cached count, and, if
the override lists a cache-write rate, a cache-write count (with no
such rate, cache-write tokens price at the input rate like uncached
ones, so their count changes nothing). A row's counts are then that
response's counts divided among the rows sharing it, and each row
prices to its share of the response's cost. Otherwise the model gets
no cost: an empty count may be one the provider did not report or a
column another model's rows brought into the frame, and an empty
response count may be a row written before the column existed.

The rates are the override's, as the reconstruction applies an
override: at any prompt length, since the GPT long-context rate is the
only length tier it applies to an override (the Claude Haiku 5.5 entry
lists the rates for prompts up to 100,000 tokens).
"""
if model in GPT_RESPONSES_MODELS:
return None
token_columns = ["prompt_tokens", "completion_tokens"]
if not set(token_columns) <= set(rows.columns):
return None
priced = rows.dropna(subset=token_columns)
if priced.empty:
return None
# The same grouped sum the published fallback costs were computed from,
# so an input-and-output override reproduces them to the bit. The model's
# own group: pandas 2 also gives a categorical column's other categories
# a group (all zero) unless observed is set.
sums = (
priced.groupby("model", observed=True)[token_columns]
.sum()
.loc[priced["model"].iloc[0]]
)
prompt = float(sums["prompt_tokens"])
completion = float(sums["completion_tokens"])
if "cache_read" not in rates and "cache_write" not in rates:
return prompt * rates["input"] / 1e6 + completion * rates["output"] / 1e6
# The cached count prices at the cache-read rate (the input rate when
# the override lists none) and bounds the cache-write count; with no
# cache-write rate, cache-write tokens price
# at the input rate like uncached ones, so their count changes nothing.
counts = ["cached_prompt_tokens"]
if "cache_write" in rates:
counts.append("cache_write_prompt_tokens")
needed = [*counts, *RESPONSE_COUNT_COLUMNS]
if not set(needed) <= set(priced.columns) or priced[needed].isna().any().any():
return None
# One response, live or replayed: the counts are (1, 0) or (0, 1). A sum
# of 1 would also pass (-1, 2) or (0.5, 0.5), which no runner writes. The
# counts compare as floats, so a 1.0 (a count column with an empty cell
# elsewhere can be a float column) still passes.
live, replayed = (priced[column].astype(float) for column in RESPONSE_COUNT_COLUMNS)
one_response = ((live == 1) & (replayed == 0)) | ((live == 0) & (replayed == 1))
if not one_response.all():
return None

def recorded(column: str) -> pd.Series:
if column not in counts:
return pd.Series(0.0, index=priced.index)
return priced[column].astype(float).clip(lower=0.0)

row_prompt = priced["prompt_tokens"].astype(float)
cached = np.minimum(recorded("cached_prompt_tokens"), row_prompt)
cache_write = np.minimum(recorded("cache_write_prompt_tokens"), row_prompt - cached)
# Each row's uncached count is non-negative after the bounds. Summing the
# rows' counts, rather than subtracting the cache sums from the grouped
# prompt sum (the two sums round differently), keeps a fully cached
# prompt from pricing below zero.
uncached = row_prompt - cached - cache_write
return (
float(uncached.sum()) * rates["input"]
+ float(cached.sum()) * rates.get("cache_read", rates["input"])
+ float(cache_write.sum()) * rates.get("cache_write", rates["input"])
+ completion * rates["output"]
) / 1e6


def model_cost_latency(
predictions: pd.DataFrame,
price_overrides: dict[str, dict[str, float]] | None = None,
Expand All @@ -1466,12 +1588,16 @@ def model_cost_latency(
a per-household figure. Latency is the *median* per-household request-time —
each household's calls summed, then the median across households — which is
robust to the occasional rate-limit retry that inflates the mean. When a
model's reconstructed cost is missing (a provider preview model not yet in
litellm's price map), it is filled from ``price_overrides`` by pricing the
rows that recorded both prompt and completion token counts. A row missing
either count adds nothing, as ``eval_no_tools._reconstruct_token_cost``
prices no such row, and a model with no row to price (Claude Fable 5's
frozen board rows record no usage) gets no cost, not $0.
model's summed ``total_cost_usd`` is empty, :func:`_override_fallback_cost`
fills it from ``price_overrides`` in the cases that function lists, and
otherwise the model gets no cost and no ``costUsd`` key. The sum is empty
when no row records a cost, and also when the recorded costs include both
+inf and -inf, whose sum is NaN. The fill can be invoked
for a model whose run had a price for it: a batch cell merged from a
response that reported only a prompt count and a repair that reported
only a completion count holds both counts and no cost
(tests/test_cost_latency.py,
``test_a_batch_cell_merged_from_two_partial_count_responses_invokes_the_fill``).
"""
if predictions.empty or "model" not in predictions.columns:
return {}
Expand All @@ -1483,28 +1609,15 @@ def model_cost_latency(
household_latency_seconds(predictions).groupby("model").median()
)
overrides = price_overrides or {}
token_columns = ["prompt_tokens", "completion_tokens"]
priceable = pd.DataFrame(columns=token_columns)
if set(token_columns) <= set(predictions.columns):
priceable = (
predictions.dropna(subset=token_columns)
.groupby("model")[token_columns]
.sum()
)
out: dict[str, dict[str, float]] = {}
for _, row in usage.iterrows():
model = str(row["model"])
cost = row.get("total_cost_usd")
if (
(cost is None or pd.isna(cost))
and model in overrides
and row["model"] in priceable.index
):
price = overrides[model]
prompt, completion = priceable.loc[row["model"], token_columns]
cost = (
float(prompt) * price["input"] / 1e6
+ float(completion) * price["output"] / 1e6
if (cost is None or pd.isna(cost)) and model in overrides:
cost = _override_fallback_cost(
predictions.loc[predictions["model"] == row["model"]],
model,
overrides[model],
)
entry: dict[str, float] = {}
if cost is not None and not pd.isna(cost):
Expand Down
6 changes: 3 additions & 3 deletions policybench/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,9 +305,9 @@
# response the LiteLLM disk cache replays at the replay
# (eval_no_tools._extract_usage_metadata; eval-no-tools enables the
# cache); and, for a model whose usage records no cost,
# analysis.model_cost_latency computes one from the current entry's
# input and output rates. Once the entry changes, each would put the
# December rate on a request made in November. The pricing page
# analysis.model_cost_latency can compute one from the current entry's
# input, output and cache-read rates. Once the entry changes, each would
# put the December rate on a request made in November. The pricing page
# lists one rate at every prompt length, implicit caching only, and no
# free tier for this model. litellm 1.95.0's bundled price map has no
# gemini-4 id, and its remote map priced the 2026-11-14 gauntlet's calls
Expand Down
114 changes: 87 additions & 27 deletions scripts/effort_sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,39 +308,87 @@ def paired_difference(
}


def _utc(seconds: float) -> str:
def _utc(seconds: float | None) -> str | None:
if seconds is None or pd.isna(seconds):
return None
return pd.Timestamp(float(seconds), unit="s").strftime("%Y-%m-%dT%H:%M:%SZ")


def _every_row(rows: pd.DataFrame, column: str) -> pd.Series | None:
"""The column when every row records it, else None: rows written before
the column existed lack it, and an empty value is not recorded, not zero."""
if rows.empty or column not in rows.columns or rows[column].isna().any():
return None
return rows[column]


def _recorded(rows: pd.DataFrame, column: str) -> pd.Series | None:
"""The values the rows record in a column, or None when none does (or
the column is absent)."""
if column not in rows.columns:
return None
values = rows[column].dropna()
return None if values.empty else values


def _float_or_none(value: float | None) -> float | None:
return None if value is None else float(value)


def _close(mine: float | None, frozen: float | None) -> bool:
"""Whether a recomputed figure is within 1e-9 of the frozen one. A figure
neither side records matches; a figure only one side records does not."""
if mine is None and frozen is None:
return True
if mine is None or frozen is None:
return False
return math.isclose(mine, frozen, rel_tol=0, abs_tol=1e-9)


def run_stats(predictions: pd.DataFrame, model: str) -> dict:
"""Cost, output tokens, median latency, calls and parse failures of one row."""
rows = predictions[predictions["model"] == model]
cost = model_cost_latency(rows, PRICE_OVERRIDES_PER_1M)[model]
by_household = rows.groupby("scenario_id")
# live_calls counts the answered provider calls behind a household's rows
# (repeated on each row); rows written before the column existed leave it
# empty, and then the count is not recorded rather than zero.
recorded = bool(rows["live_calls"].notna().all())
live_calls = by_household["live_calls"].first()
# model_cost_latency leaves out a cost it cannot establish (and a latency
# no row timed), and the model itself when it has no cost, no latency and
# no total tokens; those are null here.
cost = model_cost_latency(rows, PRICE_OVERRIDES_PER_1M).get(model, {})
# live_calls and cache_hit_calls count the answered and replayed
# responses behind a row. A household run repeats a household's counts
# on each of its rows, so this reads each household's first row. A count
# some row leaves empty (rows written before its column existed) is
# null, not zero.
live = _every_row(rows, "live_calls")
live_calls = None if live is None else live.groupby(rows["scenario_id"]).first()
hits = _every_row(rows, "cache_hit_calls")
# A household none of whose requests was answered records no usage and
# no request times, so the output tokens and the request window come
# from the rows that record them, and are null only when none does.
completion = _recorded(rows, "completion_tokens")
started = _recorded(rows, "request_started_at")
completed = _recorded(rows, "request_completed_at")
parsed = rows["prediction"].notna()
return {
"households": int(rows["scenario_id"].nunique()),
"outputs": int(len(rows)),
"outputs_parsed": int(parsed.sum()),
"parse_failures": int((~parsed).sum()),
"cost_usd": float(cost["costUsd"]),
"cost_per_household_usd": float(cost["costPerHousehold"]),
"median_household_seconds": float(cost["latencySeconds"]),
"output_tokens": int(round(float(rows["completion_tokens"].sum()))),
"answered_calls": int(live_calls.sum()) if recorded else None,
"cost_usd": _float_or_none(cost.get("costUsd")),
"cost_per_household_usd": _float_or_none(cost.get("costPerHousehold")),
"median_household_seconds": _float_or_none(cost.get("latencySeconds")),
"output_tokens": (
None if completion is None else int(round(float(completion.sum())))
),
"answered_calls": None if live_calls is None else int(live_calls.sum()),
"households_with_a_second_answered_call": (
int((live_calls > 1).sum()) if recorded else None
None if live_calls is None else int((live_calls > 1).sum())
),
"cache_hit_calls": (
int(by_household["cache_hit_calls"].first().sum()) if recorded else None
None
if hits is None
else int(hits.groupby(rows["scenario_id"]).first().sum())
),
"first_request_utc": _utc(rows["request_started_at"].min()),
"last_response_utc": _utc(rows["request_completed_at"].max()),
"first_request_utc": None if started is None else _utc(started.min()),
"last_response_utc": None if completed is None else _utc(completed.max()),
}


Expand All @@ -353,15 +401,23 @@ def check_board(inputs: ScoringInputs, board: pd.DataFrame) -> dict:
for model in BOARD_MODELS:
row = stats[model]
mine = run_stats(board, model)
# A frozen row can lack a figure: the dashboard drops a cost, latency,
# exact or within-1% rate it cannot establish (the key is absent, not
# null). Read each with get: a figure the frozen row lacks fails the
# comparison when the recomputation has it, and a cost or latency
# that neither side has passes.
report[model] = {
"exact": (scores[model]["exact"], row["exact"]),
"within1pct": (scores[model]["within1pct"], row["within1pct"]),
"score": (scores[model]["score"], row["score"]),
"household_mean_exact": (100 * float(wide[model].mean()), row["exact"]),
"cost_usd": (mine["cost_usd"], row["costUsd"]),
"exact": (scores[model]["exact"], row.get("exact")),
"within1pct": (scores[model]["within1pct"], row.get("within1pct")),
"score": (scores[model]["score"], row.get("score")),
"household_mean_exact": (
100 * float(wide[model].mean()),
row.get("exact"),
),
"cost_usd": (mine["cost_usd"], row.get("costUsd")),
"median_household_seconds": (
mine["median_household_seconds"],
row["latencySeconds"],
row.get("latencySeconds"),
),
"n_parsed": (
int(
Expand All @@ -372,7 +428,7 @@ def check_board(inputs: ScoringInputs, board: pd.DataFrame) -> dict:
.notna()
.sum()
),
row["nParsed"],
row.get("nParsed"),
),
}
return report
Expand Down Expand Up @@ -559,8 +615,12 @@ def probe_record(path: Path) -> dict:
}


def lockfile_litellm(before_utc: str) -> dict:
"""The repository lockfile's litellm pin as last changed before a time."""
def lockfile_litellm(before_utc: str | None) -> dict:
"""The repository lockfile's litellm pin as last changed before a time;
null when the rows record no first request (git would read
``--before=None`` as now and return today's pin)."""
if before_utc is None:
return {"lockfile_commit": None, "litellm": None}
commit = subprocess.run(
["git", "log", "-1", "--format=%H", f"--before={before_utc}", "--", "uv.lock"],
cwd=ROOT,
Expand Down Expand Up @@ -614,7 +674,7 @@ def main() -> None:
if name in ("exact", "within1pct", "score", "n_parsed")
)
close_match = all(
math.isclose(mine, frozen, rel_tol=0, abs_tol=1e-9)
_close(mine, frozen)
for checks in report.values()
for mine, frozen in checks.values()
)
Expand Down
Loading