File size: 14,049 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
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
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, LLMTestCaseParams


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_quality_scores.json"
MD_OUT = OUTPUTS_DIR / "deepeval_quality_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_conjecture_quality_metric():
    return GEval(
        model=make_rcd_model(),
        name="Conjecture Quality",
        evaluation_steps=[
            (
                "Evaluate the actual output as a generated mathematical conjecture. "
                "The goal is to assign a score based on the quality, relevance, and "
                "mathematical usefulness of the conjecture."
            ),
            (
                "Use the input as the context that was provided to the conjecture-generating "
                "model. Use the expected output as a theorem from a mathematics paper whose "
                "preceding text was used to generate the conjecture. Use the actual output "
                "as the generated conjecture being evaluated."
            ),
            (
                "First, compare the actual output to the expected output. Determine whether "
                "the actual output is essentially the same as the expected theorem, a close "
                "variant, a related generalization or specialization, loosely related, or "
                "unrelated."
            ),
            (
                "Second, remove fluff. Ignore generic motivational language, vague claims "
                "of importance, broad exposition, future-work language, and text that does "
                "not assert a mathematical claim. Determine whether a clear mathematical "
                "statement remains."
            ),
            (
                "Assess whether anything mathematically meaningful remains after removing "
                "fluff. If the remaining content does not contain a clear mathematical "
                "statement, assign a low score. If it appears to contain a potentially new "
                "mathematical statement, continue evaluating it using the knownness, "
                "simple-case plausibility, and relevance criteria below."
            ),
            (
                "Assess simple-case plausibility. Penalize statements that are internally "
                "inconsistent, obviously false, missing necessary hypotheses, overgeneralized "
                "in a way that would likely fail immediately, or likely to fail on the first "
                "interesting example. Do not perform extensive computation; use basic "
                "mathematical reasoning only."
            ),
            (
                "Assess knownness and novelty. A known result is less valuable as a new "
                "conjecture than a plausible new statement. However, do not overly penalize "
                "close recovery of the expected theorem: similarity to the expected theorem "
                "is evidence that the output is mathematically meaningful, interesting, and "
                "contextually relevant."
            ),
            (
                "Assess relevance to the expected theorem. Outputs close to the expected "
                "theorem should generally receive higher scores. Outputs very different from "
                "the expected theorem should often receive C-level scores if they contain "
                "substantive mathematical content but are difficult to evaluate confidently."
            ),
            (
                "Assign a continuous score from 0 to 1 using this scale: "
                "1.0 means A-level: clear, substantive, plausible, highly relevant, and "
                "mathematically interesting; it closely recovers, usefully refines, or "
                "interestingly extends the expected theorem. "
                "0.75 means B-level: good mathematical conjecture; mostly clear, plausible, "
                "and relevant, but less precise, less novel, or less strong than A. "
                "0.5 means C-level: contains potentially interesting mathematical content, "
                "but its relevance, novelty, precision, or plausibility is uncertain; this "
                "includes many outputs that are quite different from the expected theorem "
                "but not clearly bad. "
                "0.25 means D-level: weak conjecture; little substance remains after removing "
                "fluff, or the statement is vague, trivial, mostly known, poorly connected, "
                "or mathematically imprecise. "
                "0.0 means E-level: no usable conjecture; incoherent, unrelated, essentially "
                "only fluff, or obviously false in simple cases."
            ),
            (
                "Use intermediate values when appropriate. For example, a score of 0.6 may "
                "indicate an output between C and B, while a score of 0.9 may indicate a "
                "very strong output that is slightly below ideal."
            ),
        ],
        evaluation_params=[
            LLMTestCaseParams.INPUT,
            LLMTestCaseParams.ACTUAL_OUTPUT,
            LLMTestCaseParams.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)

            conjecture_quality = make_conjecture_quality_metric()
            conjecture_quality.measure(test_case)
            return conjecture_quality

        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,
        )

        conjecture_quality = 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,
                "conjecture_quality_score": conjecture_quality.score,
                "conjecture_quality_reason": conjecture_quality.reason,
                "passed": conjecture_quality.is_successful(),
            }
        )

    JSON_OUT.write_text(json.dumps(results, indent=2), encoding="utf-8")

    lines = [
        "# DeepEval Conjecture Quality Scores",
        "",
        "| Result ID | Conjecture Quality Score | Passed? |",
        "|---|---:|---|",
    ]

    for row in results:
        lines.append(
            f"| {row['result_id']} | {row['conjecture_quality_score']:.3f} | {row['passed']} |"
        )

    lines.extend(["", "## Details", ""])

    for row in results:
        lines.extend(
            [
                f"### {row['result_id']}",
                "",
                f"**Score:** {row['conjecture_quality_score']:.3f}",
                "",
                f"**Passed:** {row['passed']}",
                "",
                row["conjecture_quality_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()