File size: 18,714 Bytes
4231b73 d28389c 4231b73 d28389c 4231b73 | 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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | """
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
# Add parent directory to path for kimina_client
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.")
# ============================================================================
# Configuration
# ============================================================================
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
# Standard Lean 4 header for Mathlib
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 # "Success", "Error", "Sorry"
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 # Raw formal_statement from HF
cleaned_statement: str # After removing comments
original_prop: str # Extracted proposition (∀ form)
renamed_prop: Optional[str] # After alpha-renaming
verified: bool # Passed kimina verification
informal_statement: str # Natural language description
error_message: Optional[str] = None
# ============================================================================
# Step 1: Download MiniF2F
# ============================================================================
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
# ============================================================================
# Step 2: Preprocess
# ============================================================================
def preprocess_statement(formal_statement: str) -> str:
"""Remove comments and clean up formal statement."""
# Remove block comments /-- ... -/
cleaned = re.sub(r'/--[\s\S]*?-/', '', formal_statement)
# Remove line comments -- ...
cleaned = re.sub(r'--.*', '', cleaned)
# Clean up whitespace
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)"
"""
# Match: theorem name params : goal := ...
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()
# Find outermost : separating params from goal
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", "")
# Clean informal statement
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
# ============================================================================
# Step 3: Alpha-Renaming (Lean Meta-programming)
# ============================================================================
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 = {}
# Build safe_id -> unique_id map
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
# Parse [RENAMED:id]...[/RENAMED:id] markers
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)}")
# ============================================================================
# Step 4: Verify with kimina-lean-server
# ============================================================================
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}")
# ============================================================================
# Step 5: Upload to HuggingFace
# ============================================================================
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:
# Build renamed_statement if renamed_prop exists (use anonymous name)
if p.renamed_prop:
full_theorem = DEFAULT_LEAN_HEADER + f"\ntheorem anonymous : {p.renamed_prop} := by\n sorry"
else:
full_theorem = "" # Empty if renaming failed
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)}")
# Count stats
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')})"
# Push dataset
dataset.push_to_hub(
repo_id,
private=private,
commit_message=commit_msg,
)
# Upload README
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()
# Create dataset card with YAML front matter
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")
# ============================================================================
# Main Pipeline
# ============================================================================
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)
# HuggingFace login
token = hf_token or os.environ.get("HF_TOKEN")
if token:
login(token=token)
# Step 1: Download
raw_problems = download_minif2f()
if limit:
raw_problems = raw_problems[:limit]
# Step 2: Preprocess
problems = preprocess_problems(raw_problems)
# Step 3: Alpha-rename
alpha_rename_batch(problems)
# Step 4: Verify
if not skip_verify:
verify_all(problems)
else:
for p in problems:
if p.renamed_prop:
p.verified = True
# Save local copy
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}")
# Step 5: Upload
if not skip_upload:
dataset = create_hf_dataset(problems) # Include ALL 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)")
# Summary
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}%)")
# ============================================================================
# CLI
# ============================================================================
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()
|