Datasets:
Download code/eval_deepeval_alignment.py from ai4he/conjecture-context-ablation: direct link, hf CLI and curl.
- Browser
- Download file 9.36 kB
-
https://huggingface.co/datasets/ai4he/conjecture-context-ablation/resolve/main/code/eval_deepeval_alignment.py
- Command line
-
hf download hf://datasets/ai4he/conjecture-context-ablation/code/eval_deepeval_alignment.py
-
curl -L -o eval_deepeval_alignment.py https://huggingface.co/datasets/ai4he/conjecture-context-ablation/resolve/main/code/eval_deepeval_alignment.py
9.36 kB
| import json | |
| import os | |
| import re | |
| import time | |
| from pathlib import Path | |
| from deepeval.metrics import GEval | |
| from deepeval.models import GPTModel | |
| from deepeval.test_case import LLMTestCase, SingleTurnParams | |
| BASE_DIR = Path(__file__).resolve().parent | |
| INPUTS_DIR = BASE_DIR / "inputs" | |
| OUTPUTS_DIR = BASE_DIR / "outputs" | |
| THEOREM_MAP = INPUTS_DIR / "theorem_map.md" | |
| CONJECTURES_DIR = INPUTS_DIR / "generated_conjectures" | |
| JSON_OUT = OUTPUTS_DIR / "deepeval_correctness_scores.json" | |
| MD_OUT = OUTPUTS_DIR / "deepeval_correctness_scores.md" | |
| DEEPEVAL_RETRY_SLEEP_SECONDS = 5 | |
| def read_text(path: Path) -> str: | |
| if not path.exists(): | |
| raise FileNotFoundError(f"Missing file: {path}") | |
| return path.read_text(encoding="utf-8") | |
| def extract_result_ids_from_conjectures() -> list[str]: | |
| result_ids = [] | |
| for path in sorted(CONJECTURES_DIR.glob("result_*_conjecture.md")): | |
| match = re.search(r"(result_\d+)_conjecture\.md$", path.name) | |
| if match: | |
| result_ids.append(match.group(1)) | |
| return result_ids | |
| def extract_formal_statement(conjecture_text: str, path: Path | None = None) -> str: | |
| """ | |
| Extract only the Formal Statement section from a generated conjecture file. | |
| The current conjecture-generation prompt requires a '## Formal Statement' | |
| section. If the model fails to follow the format, fall back to the full | |
| file and print a warning so the evaluation can still run. | |
| """ | |
| match = re.search( | |
| r"## Formal Statement\s*(.*?)(?=\n## |\Z)", | |
| conjecture_text, | |
| flags=re.DOTALL, | |
| ) | |
| if match: | |
| return match.group(1).strip() | |
| label = f" in {path}" if path else "" | |
| print( | |
| f"WARNING: Could not find '## Formal Statement'{label}; using full file.", | |
| flush=True, | |
| ) | |
| return conjecture_text.strip() | |
| def extract_source_theorem_from_map(theorem_map_text: str, result_id: str) -> str: | |
| """ | |
| Extract the source theorem statement for a result ID from theorem_map.md. | |
| Robust to headings like: | |
| ### result_001 | |
| ### `result_001` | |
| ### result_001: Theorem \\ref{central} | |
| Robust to labels like: | |
| - **Exact statement:** ... | |
| - Exact statement: ... | |
| - **Formal Statement:** ... | |
| - Formal Statement: ... | |
| """ | |
| lines = theorem_map_text.splitlines() | |
| # 1. Find the result section heading. | |
| start = None | |
| heading_re = re.compile( | |
| rf"^###\s+`?{re.escape(result_id)}`?(?:\s*:.*)?\s*$", | |
| flags=re.IGNORECASE, | |
| ) | |
| for i, line in enumerate(lines): | |
| if heading_re.match(line.strip()): | |
| start = i + 1 | |
| break | |
| if start is None: | |
| raise ValueError(f"Could not find section for {result_id} in theorem_map.md") | |
| # 2. Find the end of this result section. | |
| end = len(lines) | |
| next_result_re = re.compile( | |
| r"^###\s+`?result_\d+`?(?:\s*:.*)?\s*$", | |
| flags=re.IGNORECASE, | |
| ) | |
| for i in range(start, len(lines)): | |
| stripped = lines[i].strip() | |
| if next_result_re.match(stripped) or stripped.startswith("## Summary") or stripped.startswith("## Final Summary"): | |
| end = i | |
| break | |
| section_lines = lines[start:end] | |
| # 3. Find a statement field. | |
| statement_labels = { | |
| "statement", | |
| "statement (exact from paper)", | |
| "exact statement", | |
| "exact theorem statement", | |
| "theorem statement", | |
| "formal statement", | |
| } | |
| for i, line in enumerate(section_lines): | |
| stripped = line.strip() | |
| # Only consider Markdown bullet fields. | |
| if not stripped.startswith("-"): | |
| continue | |
| field = stripped[1:].strip() | |
| # Remove bold wrapping around the label, but not the value. | |
| # Examples: | |
| # **Exact statement:** Let ... | |
| # Exact statement: Let ... | |
| field = field.replace("**", "") | |
| if ":" not in field: | |
| continue | |
| label, value = field.split(":", 1) | |
| label = label.strip().lower() | |
| value = value.strip() | |
| if label not in statement_labels: | |
| continue | |
| statement_parts = [] | |
| if value: | |
| statement_parts.append(value) | |
| # Capture continuation lines until the next bullet or heading. | |
| for continuation in section_lines[i + 1:]: | |
| continuation_stripped = continuation.strip() | |
| if continuation_stripped.startswith("- ") or continuation_stripped.startswith("### ") or continuation_stripped.startswith("## "): | |
| break | |
| if continuation_stripped: | |
| statement_parts.append(continuation_stripped) | |
| statement = "\n".join(statement_parts).strip() | |
| # Remove markdown blockquote markers. | |
| statement = re.sub(r"^\s*>\s?", "", statement, flags=re.MULTILINE).strip() | |
| if statement: | |
| return statement | |
| raise ValueError(f"Could not find theorem statement for {result_id} in theorem_map.md") | |
| def make_rcd_model(): | |
| api_key = os.environ.get("RCD_LLM_API_KEY") | |
| if not api_key: | |
| raise RuntimeError( | |
| "RCD_LLM_API_KEY is not set. Run: " | |
| 'export RCD_LLM_API_KEY="$(cat ~/.secrets/rcd_llm_key)"' | |
| ) | |
| return GPTModel( | |
| model="gemma-4-31b", | |
| api_key=api_key, | |
| base_url="https://llm.rcd.clemson.edu/v1", | |
| temperature=0, | |
| ) | |
| def make_correctness_metric(): | |
| return GEval( | |
| model=make_rcd_model(), | |
| name="Correctness", | |
| criteria="Determine whether the actual output is factually correct based on the expected output.", | |
| evaluation_params=[ | |
| SingleTurnParams.ACTUAL_OUTPUT, | |
| SingleTurnParams.EXPECTED_OUTPUT, | |
| ], | |
| threshold=0.5, | |
| ) | |
| def measure_with_retries(test_case: LLMTestCase, result_id: str) -> GEval: | |
| """ | |
| Run the DeepEval metric for one example, retrying the same example until it succeeds. | |
| This is intentionally unbounded so transient DeepEval/model/API failures do not | |
| cause the script to skip an example or move on prematurely. | |
| """ | |
| attempt = 1 | |
| while True: | |
| try: | |
| if attempt > 1: | |
| print(f"Retrying {result_id} DeepEval call, attempt {attempt}...", flush=True) | |
| correctness = make_correctness_metric() | |
| correctness.measure(test_case) | |
| return correctness | |
| except Exception as exc: | |
| print( | |
| f"WARNING: DeepEval failed for {result_id} on attempt {attempt}: " | |
| f"{type(exc).__name__}: {exc}", | |
| flush=True, | |
| ) | |
| attempt += 1 | |
| time.sleep(DEEPEVAL_RETRY_SLEEP_SECONDS) | |
| def main(): | |
| OUTPUTS_DIR.mkdir(parents=True, exist_ok=True) | |
| theorem_map_text = read_text(THEOREM_MAP) | |
| result_ids = extract_result_ids_from_conjectures() | |
| if not result_ids: | |
| raise RuntimeError(f"No conjecture files found in {CONJECTURES_DIR}") | |
| results = [] | |
| for result_id in result_ids: | |
| conjecture_path = CONJECTURES_DIR / f"{result_id}_conjecture.md" | |
| actual_full_text = read_text(conjecture_path) | |
| actual_output = extract_formal_statement(actual_full_text, conjecture_path) | |
| expected_output = extract_source_theorem_from_map(theorem_map_text, result_id) | |
| judge_actual_output = actual_output[:12000] | |
| judge_expected_output = expected_output[:8000] | |
| print(f"Evaluating {result_id}...", flush=True) | |
| print(f" actual chars: {len(actual_output)} -> judging {len(judge_actual_output)}", flush=True) | |
| print(f" expected chars: {len(expected_output)} -> judging {len(judge_expected_output)}", flush=True) | |
| test_case = LLMTestCase( | |
| input=( | |
| "" | |
| ), | |
| actual_output=judge_actual_output, | |
| expected_output=judge_expected_output, | |
| ) | |
| correctness = measure_with_retries(test_case, result_id) | |
| results.append( | |
| { | |
| "result_id": result_id, | |
| "conjecture_file": str(conjecture_path.relative_to(BASE_DIR)), | |
| "expected_output": expected_output, | |
| "actual_output": actual_output, | |
| "correctness_score": correctness.score, | |
| "correctness_reason": correctness.reason, | |
| "passed": correctness.is_successful(), | |
| } | |
| ) | |
| JSON_OUT.write_text(json.dumps(results, indent=2), encoding="utf-8") | |
| lines = [ | |
| "# DeepEval Correctness Scores", | |
| "", | |
| "| Result ID | Correctness Score | Passed? |", | |
| "|---|---:|---|", | |
| ] | |
| for row in results: | |
| lines.append( | |
| f"| {row['result_id']} | {row['correctness_score']:.3f} | {row['passed']} |" | |
| ) | |
| lines.extend(["", "## Details", ""]) | |
| for row in results: | |
| lines.extend( | |
| [ | |
| f"### {row['result_id']}", | |
| "", | |
| f"**Score:** {row['correctness_score']:.3f}", | |
| "", | |
| f"**Passed:** {row['passed']}", | |
| "", | |
| row["correctness_reason"] or "No reason provided.", | |
| "", | |
| ] | |
| ) | |
| MD_OUT.write_text("\n".join(lines), encoding="utf-8") | |
| print(f"Wrote {JSON_OUT}") | |
| print(f"Wrote {MD_OUT}") | |
| if __name__ == "__main__": | |
| main() | |