File size: 7,932 Bytes
ea8c728 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | """Evaluator for LLM-SQL column reordering (aligned with CORAL examples/ADRS/llm_sql/eval).
Requires ``solver.py``, ``utils.py``, and ``datasets/*.csv`` in this directory.
Use ``fetch_datasets.sh`` or copy from ``CORAL/.../llm_sql/eval/datasets/``.
"""
from __future__ import annotations
import importlib.util
import os
import sys
import time
import traceback
import pandas as pd
_REQUIRED_CSV = (
"movies.csv",
"beer.csv",
"BIRD.csv",
"PDMX.csv",
"products.csv",
)
def _datasets_dir(current_dir: str, program_path: str) -> str:
"""Prefer ``<evaluator>/datasets``; else ``<initial.py>/datasets`` (Shinka task copy)."""
primary = os.path.join(current_dir, "datasets")
if _has_all_csv(primary):
return primary
alt = os.path.join(os.path.dirname(os.path.abspath(program_path)), "datasets")
if _has_all_csv(alt):
return alt
return primary
def _has_all_csv(d: str) -> bool:
return os.path.isdir(d) and all(
os.path.isfile(os.path.join(d, name)) for name in _REQUIRED_CSV
)
def evaluate(program_path: str) -> dict:
"""Same protocol as CORAL ``eval/evaluator.py`` (fixed CSVs + ``col_merge`` per file)."""
try:
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
sys.path.insert(0, current_dir)
prog_dir = os.path.dirname(os.path.abspath(program_path))
if prog_dir not in sys.path:
sys.path.insert(0, prog_dir)
# Import after sys.path: Shinka loads evaluator via importlib without task dir on path.
from utils import evaluate_df_prefix_hit_cnt
spec = importlib.util.spec_from_file_location("program", program_path)
program = importlib.util.module_from_spec(spec)
spec.loader.exec_module(program)
if not hasattr(program, "Evolved"):
return {
"combined_score": 0.0,
"runs_successfully": 0.0,
"error": "Missing algorithm function",
}
datasets_dir = _datasets_dir(current_dir, program_path)
test_files = [os.path.join(datasets_dir, name) for name in _REQUIRED_CSV]
col_merges = [
[["movieinfo", "movietitle", "rottentomatoeslink"]],
[["beer/beerId", "beer/name"]],
[["PostId", "Body"]],
[
["path", "metadata"],
[
"hasmetadata",
"isofficial",
"isuserpublisher",
"isdraft",
"hasannotations",
"subsetall",
],
],
[["product_title", "parent_asin"]],
]
if not _has_all_csv(datasets_dir):
return {
"combined_score": 0.0,
"runs_successfully": 0.0,
"error": (
"Missing llm_sql datasets (need all of: "
+ ", ".join(_REQUIRED_CSV)
+ "). Run ./fetch_datasets.sh under this example, or copy datasets/ "
"next to evaluator.py or next to initial.py (Shinka task_dir)."
),
}
failed_files = 0
hit_rates: list[float] = []
total_runtime = 0.0
successful_files = 0
for filename, col_merge in zip(test_files, col_merges):
try:
if not os.path.exists(filename):
print(f"Dataset not found: {filename}, skipping...")
failed_files += 1
continue
print(f"Processing dataset: {filename}")
master_df = pd.read_csv(filename)
total_chars_before = (
master_df.astype(str).apply(lambda x: x.str.len().sum(), axis=1).sum()
)
original_row_count = len(master_df)
st = time.time()
reordered, _ = program.Evolved().reorder(
master_df,
early_stop=100000,
distinct_value_threshold=0.7,
row_stop=4,
col_stop=2,
col_merge=col_merge,
)
runtime = time.time() - st
reordered_row_count = len(reordered)
if reordered_row_count != original_row_count:
diff = reordered_row_count - original_row_count
if diff < 0:
error_msg = (
f"Evaluation failed: row count decreases by {abs(diff)} rows. "
"Data were lost - you might have dropped some rows or failed to "
"preserve all data during reordering."
)
else:
error_msg = (
f"Evaluation failed: row count increases by {diff} rows. "
"Data were duplicated - you might have duplicated some rows "
"during reordering."
)
return {
"combined_score": 0.0,
"runs_successfully": 0.0,
"error": error_msg,
}
total_chars_after = (
reordered.astype(str).apply(lambda x: x.str.len().sum(), axis=1).sum()
)
if total_chars_after < total_chars_before:
char_diff = total_chars_before - total_chars_after
char_diff_pct = (
(char_diff / total_chars_before * 100)
if total_chars_before > 0
else 0
)
message = (
f"Evaluation failed: character decreases by {char_diff_pct:.2f}%. "
"Data were lost - you might have dropped some data or failed to "
"preserve all data during reordering."
)
return {
"combined_score": 0.0,
"runs_successfully": 0.0,
"error": message,
}
results = evaluate_df_prefix_hit_cnt(reordered)
print(f"Results: {results}, Runtime: {runtime}")
hit_rate = results[1] / 100
hit_rates.append(hit_rate)
total_runtime += runtime
successful_files += 1
except Exception as e:
print(f"Failed to process {os.path.basename(filename)}: {str(e)}")
print(traceback.format_exc())
failed_files += 1
break
if successful_files == 0:
return {
"combined_score": 0.0,
"runs_successfully": 0.0,
"error": "No files processed successfully",
}
if failed_files > 0:
return {
"combined_score": 0.0,
"runs_successfully": 0.0,
"error": "1 or more files failed to run",
}
average_hit_rate = sum(hit_rates) / successful_files
average_runtime = total_runtime / successful_files
score = 0.95 * average_hit_rate + 0.05 * (12 - min(12, average_runtime)) / 12
return {
"combined_score": float(score),
"runs_successfully": 1.0,
"hit_rates": hit_rates,
"total_runtime": float(total_runtime),
"avg_hit_rate": float(average_hit_rate),
"avg_runtime": float(average_runtime),
}
except Exception as e:
print(f"Evaluation failed: {str(e)}")
print(traceback.format_exc())
return {"combined_score": 0.0, "runs_successfully": 0.0, "error": str(e)}
|