File size: 12,862 Bytes
706935f 77a0a50 706935f 77a0a50 706935f 77a0a50 706935f 77a0a50 706935f 77a0a50 706935f 77a0a50 706935f 77a0a50 706935f 77a0a50 706935f 77a0a50 706935f 77a0a50 706935f 77a0a50 706935f 77a0a50 706935f | 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 | """Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge.
The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points)
are adapted from CMU-AIRe/QED-Nano (Apache License 2.0, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718):
https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench
See LICENSE and NOTICE for details.
"""
import email.utils
import json
import os
import re
import stat
import sys
import time
import urllib.error
import urllib.request
LIMIT = 200_000
MIN_NON_WS_CHARS = 20
DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro"
DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1"
DEFAULT_TIMEOUT_SEC = 240.0
DEFAULT_MAX_ATTEMPTS = 5
MAX_RETRY_AFTER_SEC = 120.0
MAX_TOKENS_SCHEDULE = (16384, 32768, 65536)
RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504})
def read_own(path):
"""Reject links, special files, multiple hard links, and oversized files."""
parts = os.path.abspath(path).split("/")[1:]
folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
try:
for part in parts[:-1]:
inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)
os.close(folder)
folder = inner
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)
finally:
os.close(folder)
with os.fdopen(fd, "rb") as stream:
info = os.fstat(stream.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
raise ValueError("not a regular file with one link")
data = stream.read(LIMIT + 1)
if len(data) > LIMIT:
raise ValueError(f"file exceeds {LIMIT} bytes")
return data
def write_new(path, data):
try:
os.unlink(path)
except FileNotFoundError:
pass
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
with os.fdopen(fd, "wb") as handle:
handle.write(data)
def write_json(path, payload):
write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))
def remove_self_evaluation(text):
"""Apply QED-Nano's evaluation-heading cleanup to a candidate solution."""
pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$"
return re.sub(pattern, "", text).strip()
def parse_proof_points(text):
"""Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}."""
match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL)
points = (
re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE)
if match
else None
)
if points is None:
raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7")
return int(points.group(1))
def parse_retry_after(headers):
if not headers:
return None
raw = headers.get("Retry-After")
if raw is None:
return None
text = str(raw).strip()
if not text:
return None
try:
seconds = float(text)
except ValueError:
try:
dt = email.utils.parsedate_to_datetime(text)
except (TypeError, ValueError):
return None
seconds = dt.timestamp() - time.time()
if seconds <= 0:
return 0.0
return min(seconds, MAX_RETRY_AFTER_SEC)
class NonRetryableJudgeError(RuntimeError):
"""Raised on permanent client/configuration errors such as HTTP 400/401/403/404."""
def call_judge_once(prompt, model, base_url, api_key, max_tokens, timeout_sec):
url = base_url.rstrip("/") + "/chat/completions"
body = json.dumps(
{
"model": model,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": max_tokens,
}
).encode("utf-8")
request = urllib.request.Request(
url,
data=body,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"User-Agent": "harbor-imo-proofbench-verifier/1.0",
},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=timeout_sec) as response:
raw_body = response.read()
except urllib.error.HTTPError as exc:
err_snippet = ""
try:
err_snippet = exc.read().decode("utf-8", "replace")[:300]
except Exception:
pass
retry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else None
msg = f"HTTP {exc.code}: {err_snippet}".strip()
if exc.code not in RETRYABLE_HTTP_CODES and not (500 <= exc.code <= 599):
raise NonRetryableJudgeError(msg) from exc
err = RuntimeError(msg)
err.retry_after = retry_after
raise err from exc
if not raw_body.strip():
raise ValueError("Judge returned an empty HTTP body")
data = json.loads(raw_body.decode("utf-8"))
choices = data.get("choices") or []
content = (choices[0].get("message") or {}).get("content") if choices else None
if not isinstance(content, str) or not content.strip():
raise ValueError("Judge returned empty message content")
usage = data.get("usage") or {}
return content, usage.get("completion_tokens")
def judge_proof(prompt, model, base_url, api_key):
max_attempts = max(1, int(os.environ.get("JUDGE_MAX_ATTEMPTS", str(DEFAULT_MAX_ATTEMPTS))))
timeout_sec = float(os.environ.get("JUDGE_TIMEOUT_SEC", str(DEFAULT_TIMEOUT_SEC)))
base_delay = float(os.environ.get("JUDGE_RETRY_BASE_DELAY", "2.0"))
last_error = None
last_raw = ""
for attempt in range(1, max_attempts + 1):
max_tokens = MAX_TOKENS_SCHEDULE[min(attempt - 1, len(MAX_TOKENS_SCHEDULE) - 1)]
try:
raw, completion_tokens = call_judge_once(
prompt, model, base_url, api_key, max_tokens, timeout_sec
)
last_raw = raw
points = parse_proof_points(raw)
return points, raw, completion_tokens, attempt, None
except NonRetryableJudgeError as exc:
last_error = f"{type(exc).__name__}: {exc}"
return None, last_raw, None, attempt, last_error
except (urllib.error.URLError, TimeoutError, OSError, ValueError, RuntimeError) as exc:
last_error = f"{type(exc).__name__}: {exc}"
retry_after = getattr(exc, "retry_after", None)
print(
f"[imo-proofbench-verifier] attempt {attempt}/{max_attempts} failed: {last_error}",
file=sys.stderr,
flush=True,
)
if attempt < max_attempts:
delay = min(60.0, base_delay * (2 ** (attempt - 1)))
if retry_after is not None:
delay = max(delay, retry_after)
if delay > 0:
time.sleep(delay)
return None, last_raw, None, max_attempts, last_error
def main():
out = os.environ["VERIFIER_DIR"]
tests_dir = os.environ["TESTS_DIR"]
os.makedirs(out, exist_ok=True)
for stale in ("reward.txt", "reward.json"):
try:
os.unlink(os.path.join(out, stale))
except FileNotFoundError:
pass
proof_out_path = os.path.join(out, "proof.md")
try:
os.unlink(proof_out_path)
except FileNotFoundError:
pass
reference_bytes = open(os.path.join(tests_dir, "reference.json"), "rb").read()
ref = json.loads(reference_bytes.decode("utf-8"))
if ref.get("max_score") != 7:
raise ValueError("Expected ProofBench reference with max_score=7")
for field in ("problem", "solution", "grading_guidelines"):
if not isinstance(ref.get(field), str):
raise TypeError(f"Missing reference {field}")
write_new(os.path.join(out, "reference.json"), reference_bytes)
judge_model = (os.environ.get("JUDGE_MODEL") or DEFAULT_JUDGE_MODEL).strip() or DEFAULT_JUDGE_MODEL
judge_base_url = (
(os.environ.get("JUDGE_BASE_URL") or DEFAULT_JUDGE_BASE_URL).strip()
or DEFAULT_JUDGE_BASE_URL
)
api_key = (
(os.environ.get("JUDGE_API_KEY") or "").strip()
or (os.environ.get("HF_INFERENCE_TOKEN") or "").strip()
)
structural_status = "missing"
structural_reason = "proof unavailable or invalid"
char_count = 0
non_ws_count = 0
proof = ""
try:
raw = read_own(os.environ["PROOF"])
proof = raw.decode("utf-8", "strict")
char_count = len(proof)
non_ws_count = sum(not ch.isspace() for ch in proof)
write_new(proof_out_path, raw)
if non_ws_count < MIN_NON_WS_CHARS:
structural_status = "empty"
structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters"
else:
structural_status = "ok"
structural_reason = "structurally valid submission"
except (OSError, ValueError, UnicodeError) as exc:
structural_reason = "proof unavailable or invalid: " + str(exc)[:200]
structural = {
"status": structural_status,
"char_count": char_count,
"non_whitespace_count": non_ws_count,
"reason": structural_reason,
}
if structural_status != "ok":
judgment = {
"status": structural_status,
"structural": structural,
"judged_by_api": False,
"judge_model": judge_model,
"judge_base_url": judge_base_url,
"points": 0,
"max_score": 7,
"reward": 0.0,
"passed_6": False,
"attempts": 0,
"judge_output_tokens": 0,
"raw_response": "",
"reason": structural_reason,
"error": None,
}
write_json(os.path.join(out, "judgment.json"), judgment)
write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0})
print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})")
return
if not api_key:
error_msg = "Missing judge API key: set JUDGE_API_KEY or HF_INFERENCE_TOKEN"
judgment = {
"status": "judge_error",
"structural": structural,
"judged_by_api": False,
"judge_model": judge_model,
"judge_base_url": judge_base_url,
"points": None,
"max_score": 7,
"reward": None,
"passed_6": None,
"attempts": 0,
"judge_output_tokens": None,
"raw_response": "",
"reason": error_msg,
"error": error_msg,
}
write_json(os.path.join(out, "judgment.json"), judgment)
print(f"ERROR: {error_msg}", file=sys.stderr)
sys.exit(1)
template = open(os.path.join(tests_dir, "proofbench_prompt.txt"), encoding="utf-8").read()
prompt = template.format(
problem_statement=ref["problem"],
solution=ref["solution"],
guidelines=ref["grading_guidelines"],
student_answer=remove_self_evaluation(proof),
)
points, raw_response, completion_tokens, attempts, error_msg = judge_proof(
prompt, judge_model, judge_base_url, api_key
)
if error_msg is not None:
judgment = {
"status": "judge_error",
"structural": structural,
"judged_by_api": True,
"judge_model": judge_model,
"judge_base_url": judge_base_url,
"points": None,
"max_score": 7,
"reward": None,
"passed_6": None,
"attempts": attempts,
"judge_output_tokens": None,
"raw_response": raw_response,
"reason": error_msg,
"error": error_msg,
}
write_json(os.path.join(out, "judgment.json"), judgment)
print(f"ERROR: judge failed after {attempts} attempt(s): {error_msg}", file=sys.stderr)
sys.exit(1)
reward = round(points / 7.0, 6)
judgment = {
"status": "judged",
"structural": structural,
"judged_by_api": True,
"judge_model": judge_model,
"judge_base_url": judge_base_url,
"points": points,
"max_score": 7,
"reward": reward,
"passed_6": points >= 6,
"attempts": attempts,
"judge_output_tokens": completion_tokens,
"raw_response": raw_response,
"reason": f"Judge awarded {points} out of 7",
"error": None,
}
write_json(os.path.join(out, "judgment.json"), judgment)
write_json(os.path.join(out, "reward.json"), {"reward": reward, "points": points})
print(f"judged: points={points}/7 reward={reward} attempts={attempts} model={judge_model}")
if __name__ == "__main__":
main()
|