| """ |
| Compute Best-of-N metrics from a 3-stage pipeline rollout JSONL: |
| - greedy: EX of the first trajectory (K=1 baseline) |
| - pass@N: EX if ANY of the N trajectories is correct (oracle upper bound) |
| - majority: EX of the SQL whose execution result is the most common non-empty |
| result among executable trajectories (rule-based selector, |
| no extra trained selection agent needed). |
| |
| Usage: |
| python scripts/compute_bestofn_metrics.py <rollout.jsonl> <label> |
| """ |
| import json |
| import sys |
| import os |
| from collections import Counter |
| from concurrent.futures import ThreadPoolExecutor |
|
|
| ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| os.chdir(ROOT) |
| sys.path.insert(0, ROOT) |
| from validator_data.validator import _execute_sql |
| from data_processing.planner import is_execution_correct |
|
|
|
|
| def safe_execute(db_path, sql): |
| if not sql or sql.strip() == "": |
| return ("", True) |
| try: |
| return _execute_sql("./" + db_path, sql) |
| except Exception as e: |
| return (str(e), True) |
|
|
|
|
| def hash_result(result): |
| """Hash the execution result for majority voting (handles DataFrame, list, str, None).""" |
| if result is None: |
| return None |
| try: |
| |
| import pandas as pd |
| if isinstance(result, pd.DataFrame): |
| return str(tuple(map(tuple, result.values.tolist()))) |
| except Exception: |
| pass |
| return str(result) |
|
|
|
|
| def is_empty_result(result): |
| """Check if execution result is effectively empty.""" |
| if result is None: |
| return True |
| try: |
| import pandas as pd |
| if isinstance(result, pd.DataFrame): |
| return result.empty |
| except Exception: |
| pass |
| s = str(result).strip() |
| return s == "" or "(no rows)" in s or s == "[]" |
|
|
|
|
| def select_majority(traj_list, db_path): |
| """ |
| Rule-based selector: among executable trajectories with NON-empty result, |
| pick the SQL whose result hash is most common. Return (selected_sql, selected_idx). |
| Tie-breaking: first by frequency, then by trajectory order. |
| """ |
| candidates = [] |
| for i, t in enumerate(traj_list): |
| sql = t.get("fixed_sql") or t.get("planner_sql") |
| if not sql or sql.strip() == "": |
| continue |
| exec_result, has_err = safe_execute(db_path, sql) |
| if has_err: |
| continue |
| empty = is_empty_result(exec_result) |
| candidates.append((i, sql, hash_result(exec_result), empty)) |
|
|
| if not candidates: |
| |
| return traj_list[0].get("fixed_sql") or traj_list[0].get("planner_sql"), 0 |
|
|
| |
| non_empty = [c for c in candidates if not c[3]] |
| pool = non_empty if non_empty else candidates |
|
|
| |
| counter = Counter(c[2] for c in pool) |
| best_hash, _ = counter.most_common(1)[0] |
| |
| for i, sql, h, _ in pool: |
| if h == best_hash: |
| return sql, i |
| return pool[0][1], pool[0][0] |
|
|
|
|
| def main(): |
| if len(sys.argv) != 3: |
| print("Usage: compute_bestofn_metrics.py <rollout.jsonl> <label>") |
| sys.exit(1) |
|
|
| rollout_path, label = sys.argv[1], sys.argv[2] |
|
|
| n_q = 0 |
| n_greedy_correct = 0 |
| n_pass_at_N = 0 |
| n_majority_correct = 0 |
| K_used = None |
|
|
| with open(rollout_path) as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| sample = json.loads(line) |
| traj = sample.get("trajectories", []) |
| if not traj: |
| continue |
| n_q += 1 |
| if K_used is None: |
| K_used = len(traj) |
|
|
| |
| if traj[0].get("is_fixed_correct"): |
| n_greedy_correct += 1 |
|
|
| |
| if any(t.get("is_fixed_correct") for t in traj): |
| n_pass_at_N += 1 |
|
|
| |
| db_path = sample["db_path"] |
| gold_sql = sample["sql"] |
| gold_exec = safe_execute(db_path, gold_sql) |
| if gold_exec[1]: |
| continue |
|
|
| selected_sql, _idx = select_majority(traj, db_path) |
| sel_exec = safe_execute(db_path, selected_sql) |
| if not sel_exec[1] and is_execution_correct(gold_exec[0], sel_exec[0]): |
| n_majority_correct += 1 |
|
|
| if n_q == 0: |
| print(f"{label}: no questions evaluated") |
| return |
|
|
| print() |
| print(f"=== {label} ===") |
| print(f" questions evaluated: {n_q}") |
| print(f" K used per question: {K_used}") |
| print(f" greedy (1st traj): {n_greedy_correct}/{n_q} = {100*n_greedy_correct/n_q:.2f}%") |
| print(f" selector-majority: {n_majority_correct}/{n_q} = {100*n_majority_correct/n_q:.2f}%") |
| print(f" pass@{K_used} (oracle): {n_pass_at_N}/{n_q} = {100*n_pass_at_N/n_q:.2f}%") |
| print() |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|