| | """ |
| | MiniF2F Alpha-Renaming Pipeline |
| | |
| | This script creates an alpha-renamed version of the MiniF2F test dataset. |
| | Alpha-renaming replaces variable names with Greek letters (α, β, γ, etc.) |
| | using Lean 4 meta-programming to ensure syntactic correctness. |
| | |
| | Pipeline steps: |
| | 1. Download MiniF2F from HuggingFace |
| | 2. Preprocess: remove comments, extract propositions |
| | 3. Alpha-rename using Lean 4 meta-programming (AlphaRenaming.lean) |
| | 4. Verify with kimina-lean-server (check syntax validity) |
| | 5. Upload verified dataset to HuggingFace |
| | |
| | Usage: |
| | uv run python pipeline.py --repo-id ChristianZ97/minif2f_test-AlphaRenamed |
| | """ |
| |
|
| | import os |
| | import re |
| | import sys |
| | import json |
| | import tempfile |
| | import subprocess |
| | import argparse |
| | from typing import List, Dict, Optional |
| | from dataclasses import dataclass, field |
| | from datetime import datetime |
| |
|
| | from tqdm import tqdm |
| | from datasets import Dataset, load_dataset |
| | from huggingface_hub import login, DatasetCard |
| |
|
| | |
| | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| |
|
| | try: |
| | from kimina_client import KiminaClient |
| | except ImportError: |
| | KiminaClient = None |
| | print("Warning: kimina_client not found. Install or check path.") |
| |
|
| |
|
| | |
| | |
| | |
| |
|
| | PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) |
| |
|
| | |
| | DEFAULT_LEAN_HEADER = """import Mathlib |
| | import Aesop |
| | |
| | set_option maxHeartbeats 0 |
| | |
| | open BigOperators Real Nat Topology Rat |
| | """ |
| |
|
| |
|
| | @dataclass |
| | class LeanState: |
| | """Result of Lean verification.""" |
| | status: str |
| | is_syntax_correct: bool |
| | is_proven: bool |
| | has_sorry: bool |
| | error_messages: List[str] = field(default_factory=list) |
| |
|
| |
|
| | @dataclass |
| | class Problem: |
| | """A MiniF2F problem through the pipeline.""" |
| | unique_id: str |
| | original_statement: str |
| | cleaned_statement: str |
| | original_prop: str |
| | renamed_prop: Optional[str] |
| | verified: bool |
| | informal_statement: str |
| | error_message: Optional[str] = None |
| |
|
| |
|
| | |
| | |
| | |
| |
|
| | def download_minif2f() -> List[Dict]: |
| | """Download MiniF2F test dataset from HuggingFace (AI-MO/minif2f_test).""" |
| | print("=" * 60) |
| | print("Step 1: Downloading MiniF2F from HuggingFace") |
| | print("=" * 60) |
| | |
| | dataset = load_dataset("AI-MO/minif2f_test", split="train") |
| | problems = list(dataset) |
| | print(f" Downloaded {len(problems)} problems") |
| | return problems |
| |
|
| |
|
| | |
| | |
| | |
| |
|
| | def preprocess_statement(formal_statement: str) -> str: |
| | """Remove comments and clean up formal statement.""" |
| | |
| | cleaned = re.sub(r'/--[\s\S]*?-/', '', formal_statement) |
| | |
| | cleaned = re.sub(r'--.*', '', cleaned) |
| | |
| | cleaned = re.sub(r'\n\s*\n', '\n', cleaned) |
| | return cleaned.strip() |
| |
|
| |
|
| | def extract_proposition(cleaned_statement: str) -> Optional[str]: |
| | """ |
| | Extract proposition from theorem declaration. |
| | Example: "theorem foo (x : ℕ) : x = x := by sorry" -> "(∀ (x : ℕ), x = x)" |
| | """ |
| | |
| | pattern = r'theorem\s+\w+\s*(.*?)\s*:=\s*(?:by)?' |
| | match = re.search(pattern, cleaned_statement, re.DOTALL) |
| | |
| | if not match: |
| | return None |
| | |
| | signature = match.group(1).strip() |
| | |
| | |
| | depth = 0 |
| | colon_pos = -1 |
| | for i, c in enumerate(signature): |
| | if c in '([{': |
| | depth += 1 |
| | elif c in ')]}': |
| | depth -= 1 |
| | elif c == ':' and depth == 0: |
| | colon_pos = i |
| | |
| | if colon_pos == -1: |
| | return None |
| | |
| | params = signature[:colon_pos].strip() |
| | goal = signature[colon_pos + 1:].strip() |
| | |
| | if params: |
| | return f"(∀ {params}, {goal})" |
| | else: |
| | return f"({goal})" |
| |
|
| |
|
| | def preprocess_problems(raw_problems: List[Dict]) -> List[Problem]: |
| | """Preprocess all problems: clean and extract propositions.""" |
| | print("\n" + "=" * 60) |
| | print("Step 2: Preprocessing") |
| | print("=" * 60) |
| | |
| | problems = [] |
| | failed = 0 |
| | |
| | for sample in raw_problems: |
| | unique_id = sample.get("name", "unknown") |
| | formal_stmt = sample.get("formal_statement", "") |
| | informal = sample.get("informal_prefix", "") |
| | |
| | |
| | if informal.startswith("/- "): |
| | informal = informal[3:] |
| | if informal.endswith(" -/"): |
| | informal = informal[:-3] |
| | |
| | cleaned = preprocess_statement(formal_stmt) |
| | prop = extract_proposition(cleaned) |
| | |
| | if prop: |
| | problems.append(Problem( |
| | unique_id=unique_id, |
| | original_statement=formal_stmt, |
| | cleaned_statement=cleaned, |
| | original_prop=prop, |
| | renamed_prop=None, |
| | verified=False, |
| | informal_statement=informal.strip(), |
| | )) |
| | else: |
| | failed += 1 |
| | |
| | print(f" Extracted: {len(problems)} propositions") |
| | print(f" Failed: {failed}") |
| | return problems |
| |
|
| |
|
| | |
| | |
| | |
| |
|
| | def create_lean_file_for_batch(problems: List[Problem]) -> str: |
| | """Create Lean file using #alpha_rename_id command for batch processing.""" |
| | lines = [ |
| | "import AlphaRenaming", |
| | "open AlphaRenaming", |
| | "", |
| | ] |
| | |
| | for p in problems: |
| | safe_id = re.sub(r'[^a-zA-Z0-9_]', '_', p.unique_id) |
| | lines.append(f"#alpha_rename_id [{safe_id}] {p.original_prop}") |
| | lines.append("") |
| | |
| | return "\n".join(lines) |
| |
|
| |
|
| | def parse_lean_output(output: str, problems: List[Problem]) -> Dict[str, str]: |
| | """Parse Lean output to extract renamed propositions.""" |
| | renamed = {} |
| | |
| | |
| | id_map = {} |
| | for p in problems: |
| | safe_id = re.sub(r'[^a-zA-Z0-9_]', '_', p.unique_id) |
| | id_map[safe_id] = p.unique_id |
| | |
| | |
| | pattern = r'\[RENAMED:(\w+)\]\s*(.*?)\s*\[/RENAMED:\1\]' |
| | for match in re.finditer(pattern, output, re.DOTALL): |
| | safe_id = match.group(1) |
| | renamed_expr = match.group(2).strip() |
| | if safe_id in id_map: |
| | renamed[id_map[safe_id]] = renamed_expr |
| | |
| | return renamed |
| |
|
| |
|
| | def alpha_rename_batch(problems: List[Problem], batch_size: int = 30) -> None: |
| | """Alpha-rename using Lean meta-programming in batches.""" |
| | print("\n" + "=" * 60) |
| | print("Step 3: Alpha-Renaming (Lean Meta-programming)") |
| | print("=" * 60) |
| | |
| | total_renamed = 0 |
| | |
| | for i in tqdm(range(0, len(problems), batch_size), desc="Renaming"): |
| | batch = problems[i:i + batch_size] |
| | lean_code = create_lean_file_for_batch(batch) |
| | |
| | with tempfile.NamedTemporaryFile( |
| | mode='w', suffix='.lean', dir=PROJECT_DIR, delete=False |
| | ) as f: |
| | f.write(lean_code) |
| | temp_file = f.name |
| | |
| | try: |
| | result = subprocess.run( |
| | ['lake', 'env', 'lean', temp_file], |
| | cwd=PROJECT_DIR, |
| | capture_output=True, |
| | text=True, |
| | timeout=120 |
| | ) |
| | |
| | output = result.stdout + result.stderr |
| | renamed = parse_lean_output(output, batch) |
| | |
| | for p in batch: |
| | if p.unique_id in renamed: |
| | p.renamed_prop = renamed[p.unique_id] |
| | total_renamed += 1 |
| | |
| | except subprocess.TimeoutExpired: |
| | print(f" Warning: Batch {i//batch_size} timed out") |
| | except Exception as e: |
| | print(f" Warning: Batch {i//batch_size} error: {e}") |
| | finally: |
| | if os.path.exists(temp_file): |
| | os.remove(temp_file) |
| | |
| | print(f" Renamed: {total_renamed}/{len(problems)}") |
| |
|
| |
|
| | |
| | |
| | |
| |
|
| | def get_val(obj, key: str, default=None): |
| | """Safely get value from dict or object.""" |
| | if isinstance(obj, dict): |
| | return obj.get(key, default) |
| | return getattr(obj, key, default) |
| |
|
| |
|
| | def parse_lean_response(response) -> LeanState: |
| | """Parse KiminaClient response.""" |
| | has_error = False |
| | has_sorry = False |
| | error_msgs = [] |
| |
|
| | if not response or not hasattr(response, 'results') or not response.results: |
| | return LeanState("Error", False, False, False, ["No results"]) |
| |
|
| | result = response.results[0] |
| | lean_resp = getattr(result, "response", {}) |
| |
|
| | messages = get_val(lean_resp, "messages", []) or [] |
| | for msg in messages: |
| | severity = get_val(msg, "severity", "") |
| | data = get_val(msg, "data", "") |
| |
|
| | if severity == "error": |
| | has_error = True |
| | error_msgs.append(data) |
| |
|
| | if "declaration uses 'sorry'" in str(data): |
| | has_sorry = True |
| |
|
| | sorries = get_val(lean_resp, "sorries", []) or [] |
| | if sorries: |
| | has_sorry = True |
| |
|
| | if has_error: |
| | return LeanState("Error", False, False, has_sorry, error_msgs) |
| | elif has_sorry: |
| | return LeanState("Sorry", True, False, True) |
| | else: |
| | return LeanState("Success", True, True, False) |
| |
|
| |
|
| | def verify_single(client, problem: Problem) -> None: |
| | """Verify single problem using kimina-lean-server (append sorry).""" |
| | prop_to_verify = problem.renamed_prop or problem.original_prop |
| | |
| | if not prop_to_verify: |
| | return |
| | |
| | safe_name = re.sub(r'[^a-zA-Z0-9_]', '_', problem.unique_id) |
| | code = DEFAULT_LEAN_HEADER + f"\ntheorem {safe_name} : {prop_to_verify} := by\n sorry\n" |
| | |
| | try: |
| | response = client.check(code) |
| | state = parse_lean_response(response) |
| | problem.verified = state.status in ["Sorry", "Success"] |
| | |
| | if state.error_messages: |
| | problem.error_message = state.error_messages[0][:300] |
| | except Exception as e: |
| | problem.error_message = str(e)[:300] |
| |
|
| |
|
| | def verify_all(problems: List[Problem]) -> None: |
| | """Verify all problems with kimina-lean-server.""" |
| | print("\n" + "=" * 60) |
| | print("Step 4: Verifying with kimina-lean-server") |
| | print("=" * 60) |
| | |
| | if KiminaClient is None: |
| | print(" Error: kimina_client not available") |
| | return |
| | |
| | try: |
| | client = KiminaClient() |
| | except Exception as e: |
| | print(f" Error initializing client: {e}") |
| | return |
| | |
| | to_verify = [p for p in problems if p.renamed_prop or p.original_prop] |
| | |
| | for p in tqdm(to_verify, desc="Verifying"): |
| | verify_single(client, p) |
| | |
| | verified_count = sum(1 for p in problems if p.verified) |
| | error_count = sum(1 for p in to_verify if not p.verified) |
| | |
| | print(f" Verified OK: {verified_count}") |
| | print(f" Errors: {error_count}") |
| |
|
| |
|
| | |
| | |
| | |
| |
|
| | def create_hf_dataset(problems: List[Problem]) -> Dataset: |
| | """Create HuggingFace Dataset from ALL processed problems.""" |
| | data = { |
| | "unique_id": [], |
| | "informal_statement": [], |
| | "original_statement": [], |
| | "renamed_statement": [], |
| | "original_prop": [], |
| | "renamed_prop": [], |
| | "kimina_verified": [], |
| | "error_message": [], |
| | } |
| | |
| | for p in problems: |
| | |
| | if p.renamed_prop: |
| | full_theorem = DEFAULT_LEAN_HEADER + f"\ntheorem anonymous : {p.renamed_prop} := by\n sorry" |
| | else: |
| | full_theorem = "" |
| | |
| | data["unique_id"].append(p.unique_id) |
| | data["informal_statement"].append(p.informal_statement) |
| | data["original_statement"].append(p.original_statement) |
| | data["renamed_statement"].append(full_theorem) |
| | data["original_prop"].append(p.original_prop) |
| | data["renamed_prop"].append(p.renamed_prop or "") |
| | data["kimina_verified"].append(p.verified) |
| | data["error_message"].append(p.error_message or "") |
| | |
| | return Dataset.from_dict(data) |
| |
|
| |
|
| | def upload_to_hf(dataset: Dataset, repo_id: str, private: bool = False) -> None: |
| | """Upload dataset and README to HuggingFace Hub.""" |
| | print("\n" + "=" * 60) |
| | print("Step 5: Uploading to HuggingFace") |
| | print("=" * 60) |
| | |
| | print(f" Repo: {repo_id}") |
| | print(f" Samples: {len(dataset)}") |
| | |
| | |
| | verified_count = sum(1 for v in dataset["kimina_verified"] if v) |
| | renamed_count = sum(1 for r in dataset["renamed_prop"] if r) |
| | |
| | commit_msg = f"Upload alpha-renamed MiniF2F ({datetime.now().strftime('%Y-%m-%d %H:%M')})" |
| | |
| | |
| | dataset.push_to_hub( |
| | repo_id, |
| | private=private, |
| | commit_message=commit_msg, |
| | ) |
| | |
| | |
| | readme_path = os.path.join(PROJECT_DIR, "README.md") |
| | if os.path.exists(readme_path): |
| | with open(readme_path, 'r') as f: |
| | readme_content = f.read() |
| | |
| | |
| | yaml_header = """--- |
| | language: |
| | - en |
| | license: mit |
| | size_categories: |
| | - n<1K |
| | task_categories: |
| | - text-generation |
| | tags: |
| | - lean4 |
| | - mathlib |
| | - theorem-proving |
| | - alpha-renaming |
| | - minif2f |
| | --- |
| | |
| | """ |
| | full_readme = yaml_header + readme_content |
| | card = DatasetCard(full_readme) |
| | card.push_to_hub(repo_id) |
| | print(f" ✓ README uploaded") |
| | |
| | print(f" ✓ Uploaded to https://huggingface.co/datasets/{repo_id}") |
| | print(f" Stats: {renamed_count} renamed, {verified_count} verified, {len(dataset)} total") |
| |
|
| |
|
| | |
| | |
| | |
| |
|
| | def run_pipeline( |
| | repo_id: str, |
| | limit: Optional[int] = None, |
| | skip_verify: bool = False, |
| | skip_upload: bool = False, |
| | include_unverified: bool = False, |
| | private: bool = False, |
| | save_local: Optional[str] = None, |
| | hf_token: Optional[str] = None, |
| | ): |
| | """Run complete alpha-renaming pipeline.""" |
| | print("\n" + "=" * 60) |
| | print(" MiniF2F Alpha-Renaming Pipeline") |
| | print("=" * 60) |
| | |
| | |
| | token = hf_token or os.environ.get("HF_TOKEN") |
| | if token: |
| | login(token=token) |
| | |
| | |
| | raw_problems = download_minif2f() |
| | if limit: |
| | raw_problems = raw_problems[:limit] |
| | |
| | |
| | problems = preprocess_problems(raw_problems) |
| | |
| | |
| | alpha_rename_batch(problems) |
| | |
| | |
| | if not skip_verify: |
| | verify_all(problems) |
| | else: |
| | for p in problems: |
| | if p.renamed_prop: |
| | p.verified = True |
| | |
| | |
| | if save_local: |
| | local_data = [ |
| | { |
| | "unique_id": p.unique_id, |
| | "original_prop": p.original_prop, |
| | "renamed_prop": p.renamed_prop, |
| | "verified": p.verified, |
| | "error": p.error_message, |
| | } |
| | for p in problems |
| | ] |
| | with open(save_local, 'w') as f: |
| | json.dump(local_data, f, indent=2, ensure_ascii=False) |
| | print(f"\nSaved local copy to {save_local}") |
| | |
| | |
| | if not skip_upload: |
| | dataset = create_hf_dataset(problems) |
| | |
| | if len(dataset) == 0: |
| | print("\nError: No valid samples to upload") |
| | return |
| | |
| | upload_to_hf(dataset, repo_id, private=private) |
| | else: |
| | print("\n(Skipping HuggingFace upload)") |
| | |
| | |
| | print("\n" + "=" * 60) |
| | print(" Summary") |
| | print("=" * 60) |
| | total = len(problems) |
| | renamed = sum(1 for p in problems if p.renamed_prop) |
| | verified = sum(1 for p in problems if p.verified) |
| | print(f" Total: {total}") |
| | print(f" Renamed: {renamed} ({100*renamed/total:.1f}%)") |
| | print(f" Verified: {verified} ({100*verified/total:.1f}%)") |
| |
|
| |
|
| | |
| | |
| | |
| |
|
| | def main(): |
| | parser = argparse.ArgumentParser(description="MiniF2F Alpha-Renaming Pipeline") |
| | parser.add_argument("--repo-id", "-r", type=str, required=True, |
| | help="HuggingFace repo ID") |
| | parser.add_argument("--limit", "-n", type=int, default=None, |
| | help="Limit number of problems (for testing)") |
| | parser.add_argument("--skip-verify", action="store_true", |
| | help="Skip kimina-lean-server verification") |
| | parser.add_argument("--skip-upload", action="store_true", |
| | help="Skip HuggingFace upload") |
| | parser.add_argument("--include-unverified", action="store_true", |
| | help="Include unverified problems") |
| | parser.add_argument("--private", action="store_true", |
| | help="Make dataset private") |
| | parser.add_argument("--save-local", "-o", type=str, default=None, |
| | help="Save to local JSON file") |
| | parser.add_argument("--token", type=str, default=None, |
| | help="HuggingFace token") |
| | |
| | args = parser.parse_args() |
| | |
| | run_pipeline( |
| | repo_id=args.repo_id, |
| | limit=args.limit, |
| | skip_verify=args.skip_verify, |
| | skip_upload=args.skip_upload, |
| | include_unverified=args.include_unverified, |
| | private=args.private, |
| | save_local=args.save_local, |
| | hf_token=args.token, |
| | ) |
| |
|
| |
|
| | if __name__ == "__main__": |
| | main() |
| |
|