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
35 changes: 34 additions & 1 deletion llmsql/evaluation/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
DEFAULT_LLMSQL_VERSION,
get_repo_id,
)
from llmsql.loggers.logging_config import log
from llmsql.utils.evaluation_utils import (
connect_sqlite,
evaluate_sample,
resolve_prediction_coverage,
)
from llmsql.utils.inference_utils import _maybe_download, resolve_workdir_path
from llmsql.utils.leaderboard_utils import (
Expand Down Expand Up @@ -65,7 +67,14 @@ def evaluate(
"arguments": {"num_fewshots": 5}}}``.

Returns:
dict: Metrics and mismatches.
dict: Metrics and mismatches, plus coverage counters ``expected``,
``answered``, ``missing`` and ``duplicates``. ``accuracy`` is
computed over the predictions, ``accuracy_over_benchmark`` counts
unanswered questions as wrong.

Raises:
ValueError: if a prediction references a ``question_id`` that is not
part of the benchmark.
"""

# Determine input type
Expand All @@ -90,6 +99,23 @@ def evaluate(
"outputs must be file path or list of dicts in format {'question_id': int, 'completion': str}"
)

# --- Drop duplicates / measure coverage against the benchmark ---
# Scoring the predictions file directly made partial runs (crash, --limit,
# filtered file) look like full results, and counted duplicate ids twice.
outputs_list, coverage = resolve_prediction_coverage(outputs_list, questions)

if coverage["duplicates"]:
log.warning(
f"{coverage['duplicates']} duplicate question_id(s) in the predictions "
f"file; keeping only the first prediction for each."
)
if coverage["missing"]:
log.warning(
f"Coverage {coverage['answered']}/{coverage['expected']} question(s): "
f"{coverage['missing']} benchmark question(s) have no prediction, so "
f"accuracy is computed over {coverage['answered']} answer(s) only."
)

# --- Connect to DB ---
conn = connect_sqlite(db_path)

Expand Down Expand Up @@ -127,6 +153,7 @@ def evaluate(
metrics["gold_none"],
metrics["sql_errors"],
metrics["exact_string_matches"],
coverage,
)

# --- Build report structure ---
Expand All @@ -135,7 +162,13 @@ def evaluate(
"model_name": model_name,
"version": version,
**metrics,
**coverage,
"accuracy": accuracy,
# Missing answers count as wrong, so a partial run cannot silently
# report a full-looking accuracy.
"accuracy_over_benchmark": (
metrics["matches"] / coverage["expected"] if coverage["expected"] else 0.0
),
"exact_string_match_accuracy": (
metrics["exact_string_matches"] / metrics["total"]
if metrics["total"]
Expand Down
117 changes: 107 additions & 10 deletions llmsql/utils/evaluation_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,94 @@ def normalize_sql(sql: str) -> str:
return re.sub(r"\s+", " ", sql.strip().rstrip(";").strip())


def normalize_question_id(value: Any) -> int:
"""
Coerce a ``question_id`` coming from a predictions file into an ``int``.

Other tools commonly serialise ids as strings (``"123"``), so an int-like
string is accepted and converted. Anything else fails with a message that
names the offending value.

Args:
value: raw ``question_id`` value from a prediction entry.

Returns:
The id as ``int``.

Raises:
TypeError: if the value is neither an int nor a string.
ValueError: if the value is a string that does not parse as an int.
"""
if isinstance(value, int):
return value

if isinstance(value, str):
text = value.strip()
try:
return int(text)
except ValueError:
raise ValueError(
f"question_id must be an int or an int-like string, got {value!r}."
) from None

raise TypeError(
f"question_id must be an int or an int-like string, got {type(value).__name__}."
)


def resolve_prediction_coverage(
outputs_list: list[dict[str, Any]],
questions: dict[int, dict[str, str]],
) -> tuple[list[dict[str, Any]], dict[str, int]]:
"""
Deduplicate predictions and measure how much of the benchmark they cover.

``evaluate()`` used to score whatever rows happened to be in the predictions
file, so a crashed run (or ``--limit``) produced a full-looking accuracy
with no hint that most questions were never answered. Duplicate ids were
also counted twice.

Args:
outputs_list: predictions as loaded from a JSONL file or passed by the caller.
questions: benchmark questions keyed by ``question_id``.

Returns:
A tuple ``(unique_outputs, coverage)`` where ``coverage`` holds
``expected`` (benchmark size), ``answered`` (unique matching ids),
``missing`` (benchmark questions with no prediction) and ``duplicates``.

Raises:
ValueError: if a prediction references an id that is not in the benchmark.
"""
expected = len(questions)
seen: set[int] = set()
unique: list[dict[str, Any]] = []
duplicates = 0

for item in outputs_list:
qid = normalize_question_id(item["question_id"])

if qid not in questions:
raise ValueError(
f"question_id {qid} from the predictions file is not part of the "
f"benchmark ({expected} questions loaded)."
)

if qid in seen:
duplicates += 1
continue

seen.add(qid)
unique.append(item)

return unique, {
"expected": expected,
"answered": len(seen),
"missing": expected - len(seen),
"duplicates": duplicates,
}


def evaluate_sample(
item: dict[str, int | str],
questions: dict[int, dict[str, str]],
Expand Down Expand Up @@ -115,11 +203,17 @@ def evaluate_sample(
"sql_error": int
}
"""
# Extract question metadata
qid = item["question_id"]
assert isinstance(
qid, int
), "question_id in the outputs file needs to be of type int."
# Extract question metadata.
# These used to be plain asserts: ``python -O`` strips asserts entirely, so
# malformed input silently slipped through instead of being reported.
qid = normalize_question_id(item["question_id"])

if qid not in questions:
raise ValueError(
f"question_id {qid} from the predictions file is not part of the "
f"benchmark ({len(questions)} questions loaded)."
)

q_info = questions[qid]
table_id, gold_sql, question_text = (
q_info["table_id"],
Expand All @@ -142,10 +236,13 @@ def evaluate_sample(
last_pred_res = None # store last prediction results for mismatch logging

# Loop over all SQL queries extracted from the model output
assert isinstance(
item["completion"], str
), f"Completion filed in outputs file must be of type string: {item['completion']}. Type: {type(item['completion'])}"
for pred_sql in find_sql(item["completion"]):
completion = item["completion"]
if not isinstance(completion, str):
raise TypeError(
f"completion must be of type str, got {type(completion).__name__}: "
f"{completion!r}"
)
for pred_sql in find_sql(completion):
# Replace placeholder table names with the actual one
pred_sql_fixed = fix_table_name(pred_sql, table_id)

Expand Down Expand Up @@ -179,7 +276,7 @@ def evaluate_sample(
"question_id": qid,
"question": question_text,
"gold_sql": gold_sql,
"model_output": item["completion"],
"model_output": completion,
"gold_results": gold_results,
"prediction_results": last_pred_res,
}
Expand Down
43 changes: 40 additions & 3 deletions llmsql/utils/rich_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,20 +37,57 @@ def print_summary(
gold_none: int,
sql_errors: int,
exact_string_matches: int,
coverage: dict[str, int] | None = None,
) -> None:
"""Pretty-print summary with Rich."""
"""
Pretty-print summary with Rich.

Args:
total, matches, pred_none, gold_none, sql_errors, exact_string_matches:
per-prediction counters.
coverage: optional ``{"expected", "answered", "missing", "duplicates"}``
mapping as returned by
:func:`~llmsql.utils.evaluation_utils.resolve_prediction_coverage`.
When given, answered/missing coverage and accuracy over the whole
benchmark are added to the table.
"""
table = Table(title="[green]Evaluation Summary[/green]", show_lines=True)
table.add_column("Metric", style="bold green")
table.add_column("Value", style="bold yellow")

table.add_row("Total Samples", str(total))
table.add_row("Correct Results", f"{matches} ({matches / total:.2%})")

if coverage:
expected = coverage["expected"]
answered = coverage["answered"]
coverage_text = (
f"{answered}/{expected} ({answered / expected:.2%})" if expected else "n/a"
)
table.add_row("Coverage", coverage_text)

if coverage["missing"]:
table.add_row("Missing Predictions", str(coverage["missing"]))
if coverage["duplicates"]:
table.add_row("Duplicate Predictions", str(coverage["duplicates"]))

table.add_row(
"Correct Results",
f"{matches} ({matches / total:.2%})" if total else "n/a",
)
table.add_row(
"Exact String Match",
f"{exact_string_matches} ({exact_string_matches / total:.2%})",
f"{exact_string_matches} ({exact_string_matches / total:.2%})"
if total
else "n/a",
)
table.add_row("Prediction None", f"{pred_none}/{total}")
table.add_row("Ground Truth None", f"{gold_none}/{total}")
table.add_row("SQL Errors", str(sql_errors))

if coverage and coverage["expected"]:
table.add_row(
"Accuracy over Benchmark",
f"{matches} ({matches / coverage['expected']:.2%})",
)

console.print(table)
Loading
Loading