Download experiments/learnability/exp_pattern_prover/eval_pattern_prover.py from MilaAI4Math/OpenExpDatasets: direct link, hf CLI and curl.
- Browser
- Download file 9.49 kB
-
https://huggingface.co/datasets/MilaAI4Math/OpenExpDatasets/resolve/9ebb8c742abb4f651ff8dec02d985ecd22c9d044/experiments/learnability/exp_pattern_prover/eval_pattern_prover.py
- Command line
-
hf download hf://datasets/MilaAI4Math/OpenExpDatasets@9ebb8c742abb4f651ff8dec02d985ecd22c9d044/experiments/learnability/exp_pattern_prover/eval_pattern_prover.py
-
curl -L -o eval_pattern_prover.py https://huggingface.co/datasets/MilaAI4Math/OpenExpDatasets/resolve/9ebb8c742abb4f651ff8dec02d985ecd22c9d044/experiments/learnability/exp_pattern_prover/eval_pattern_prover.py
9.49 kB
| #!/usr/bin/env python3 | |
| """ | |
| Evaluation script for pattern-based baseline prover. | |
| Evaluates on extrinsic propositional logic problemset. | |
| """ | |
| import os | |
| import json | |
| import sys | |
| from typing import Optional | |
| from concurrent.futures import ProcessPoolExecutor, as_completed | |
| from functools import partial | |
| import problems | |
| from learning.exp_pattern_prover.pattern_prover import PatternProver, PatternProverConfig | |
| from proofsearch import format_blocks_with_indent | |
| try: | |
| from tqdm import tqdm | |
| except ImportError: | |
| # Fallback if tqdm not available | |
| def tqdm(iterable, **kwargs): | |
| return iterable | |
| def _evaluate_single_problem(args): | |
| """Worker function to evaluate a single problem (for multiprocessing).""" | |
| problem, problemset_id, max_depth, max_iterations, verbose, log_dir = args | |
| try: | |
| # Load problemset (each worker needs its own copy) | |
| problemset = problems.load_problemset(problemset_id) | |
| # Create log file path if logging is enabled | |
| log_file = None | |
| if log_dir: | |
| os.makedirs(log_dir, exist_ok=True) | |
| log_file = os.path.join(log_dir, f"{problem}_log.jsonl") | |
| # Create pattern prover | |
| config = PatternProverConfig( | |
| max_depth=max_depth, | |
| max_iterations=max_iterations, | |
| verbose=verbose, | |
| log_file=log_file | |
| ) | |
| prover = PatternProver(config) | |
| # Initialize and solve | |
| state = problemset.initialize_problem(problem) | |
| result = prover.proof_search(problem, state) | |
| # Extract proof if successful | |
| proof_text = None | |
| if result.success: | |
| try: | |
| # Get solution actions first to verify structure | |
| solution_actions = result.root.get_solution_actions() | |
| if solution_actions is None or (isinstance(solution_actions, list) and len(solution_actions) == 0): | |
| proof_text = "<proof reconstruction failed: No solution actions found>" | |
| else: | |
| # Make a copy since reconstruct_proof modifies the list | |
| actions_copy = [a for a in solution_actions] if isinstance(solution_actions, list) else solution_actions | |
| proof_text = format_blocks_with_indent(result.root.reconstruct_proof()) | |
| except Exception as e: | |
| import traceback | |
| proof_text = f"<proof reconstruction failed: {e}>\n{traceback.format_exc()}" | |
| return { | |
| 'problem': problem, | |
| 'success': result.success, | |
| 'iterations': result.iterations, | |
| 'proof': proof_text, | |
| 'error': None | |
| } | |
| except Exception as e: | |
| import traceback | |
| return { | |
| 'problem': problem, | |
| 'success': False, | |
| 'iterations': 0, | |
| 'proof': None, | |
| 'error': f"{str(e)}\n{traceback.format_exc()}" | |
| } | |
| def evaluate_pattern_prover( | |
| problemset_id: str = 'extrinsic-propositional-logic', | |
| max_problems: Optional[int] = None, | |
| max_depth: int = 30, | |
| max_iterations: int = 5000, | |
| verbose: bool = False, | |
| output_dir: str = '.', | |
| num_workers: Optional[int] = None, | |
| log_dir: Optional[str] = None, | |
| ): | |
| """ | |
| Evaluate pattern prover on a problemset. | |
| Args: | |
| problemset_id: ID of problemset to evaluate on | |
| max_problems: Maximum number of problems to evaluate (None = all) | |
| max_depth: Maximum search depth | |
| max_iterations: Maximum iterations | |
| verbose: Print verbose output | |
| output_dir: Directory to save results | |
| num_workers: Number of parallel workers (None = use all CPU cores) | |
| """ | |
| # Load problemset to get problem list | |
| print(f"Loading problemset: {problemset_id}") | |
| problemset = problems.load_problemset(problemset_id) | |
| print(f"Loaded {len(problemset)} problems") | |
| # Get problems to evaluate | |
| problem_names = problemset.problem_names() | |
| if max_problems is not None: | |
| problem_names = problem_names[:max_problems] | |
| # Determine number of workers | |
| if num_workers is None: | |
| import multiprocessing | |
| num_workers = multiprocessing.cpu_count() | |
| print(f"Evaluating {len(problem_names)} problems using {num_workers} workers...") | |
| print() | |
| # Set up log directory | |
| if log_dir is None: | |
| log_dir = os.path.join(output_dir, "logs") | |
| # Prepare arguments for workers | |
| worker_args = [ | |
| (problem, problemset_id, max_depth, max_iterations, verbose, log_dir) | |
| for problem in problem_names | |
| ] | |
| # Evaluate in parallel | |
| results = { | |
| "results": [], | |
| "num_proved": 0, | |
| "num_total": len(problem_names), | |
| "solved_problems": [] | |
| } | |
| if num_workers == 1: | |
| # Sequential execution (useful for debugging) | |
| for args in worker_args: | |
| result = _evaluate_single_problem(args) | |
| results["results"].append(result) | |
| if result['success']: | |
| results["num_proved"] += 1 | |
| results["solved_problems"].append(result['problem']) | |
| if verbose: | |
| status = "✓" if result['success'] else "✗" | |
| print(f"{status} {result['problem']}: {result['iterations']} iterations") | |
| else: | |
| # Parallel execution | |
| with ProcessPoolExecutor(max_workers=num_workers) as executor: | |
| futures = { | |
| executor.submit(_evaluate_single_problem, args): args[0] | |
| for args in worker_args | |
| } | |
| for future in tqdm(as_completed(futures), total=len(futures), desc="Evaluating"): | |
| problem_name = futures[future] | |
| try: | |
| result = future.result() | |
| results["results"].append(result) | |
| if result['success']: | |
| results["num_proved"] += 1 | |
| results["solved_problems"].append(result['problem']) | |
| if verbose: | |
| status = "✓" if result['success'] else "✗" | |
| print(f"{status} {result['problem']}: {result['iterations']} iterations") | |
| except Exception as e: | |
| print(f"Error evaluating {problem_name}: {e}") | |
| results["results"].append({ | |
| 'problem': problem_name, | |
| 'success': False, | |
| 'iterations': 0, | |
| 'proof': None, | |
| 'error': str(e) | |
| }) | |
| # Sort results by problem name for consistency | |
| results["results"].sort(key=lambda x: x['problem']) | |
| # Print summary | |
| print() | |
| print("=" * 60) | |
| print("SUMMARY") | |
| print("=" * 60) | |
| print(f"Solved: {results['num_proved']}/{results['num_total']}") | |
| if results['num_total'] > 0: | |
| print(f"Pass rate: {results['num_proved']/results['num_total']*100:.1f}%") | |
| print() | |
| if results['solved_problems']: | |
| print("Solved problems:") | |
| for p in sorted(results['solved_problems']): | |
| print(f" - {p}") | |
| print() | |
| # Save results | |
| os.makedirs(output_dir, exist_ok=True) | |
| output_file = os.path.join(output_dir, "pattern_prover_results.json") | |
| with open(output_file, 'w') as f: | |
| json.dump(results, f, indent=2) | |
| print(f"Results saved to: {output_file}") | |
| return results | |
| def main(): | |
| """Main entry point.""" | |
| import argparse | |
| parser = argparse.ArgumentParser(description="Evaluate pattern-based prover") | |
| parser.add_argument( | |
| '--problemset', | |
| type=str, | |
| default='extrinsic-propositional-logic', | |
| help='Problemset ID (default: extrinsic-propositional-logic)' | |
| ) | |
| parser.add_argument( | |
| '--max-problems', | |
| type=int, | |
| default=None, | |
| help='Maximum number of problems to evaluate (default: all)' | |
| ) | |
| parser.add_argument( | |
| '--max-depth', | |
| type=int, | |
| default=30, | |
| help='Maximum search depth (default: 30)' | |
| ) | |
| parser.add_argument( | |
| '--max-iterations', | |
| type=int, | |
| default=5000, | |
| help='Maximum iterations (default: 5000)' | |
| ) | |
| parser.add_argument( | |
| '--verbose', | |
| action='store_true', | |
| help='Print verbose output' | |
| ) | |
| parser.add_argument( | |
| '--output-dir', | |
| type=str, | |
| default='.', | |
| help='Output directory for results (default: current directory)' | |
| ) | |
| parser.add_argument( | |
| '--num-workers', | |
| type=int, | |
| default=None, | |
| help='Number of parallel workers (default: use all CPU cores)' | |
| ) | |
| parser.add_argument( | |
| '--log-dir', | |
| type=str, | |
| default=None, | |
| help='Directory for detailed logs (default: output_dir/logs)' | |
| ) | |
| args = parser.parse_args() | |
| evaluate_pattern_prover( | |
| problemset_id=args.problemset, | |
| max_problems=args.max_problems, | |
| max_depth=args.max_depth, | |
| max_iterations=args.max_iterations, | |
| verbose=args.verbose, | |
| output_dir=args.output_dir, | |
| num_workers=args.num_workers, | |
| log_dir=args.log_dir | |
| ) | |
| if __name__ == '__main__': | |
| main() | |
| #command to run: | |
| # python eval_pattern_prover.py --problemset extrinsic-95--output-dir results/pattern_prover --num-workers 4 --log-dir results/pattern_prover_95 |