File size: 9,356 Bytes
3a3f073
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()