sn99-miner / source.py
Andrew93110's picture
Promote exact reviewer_v13 artifact
3b92918 verified
Raw History Blame Contribute Delete
6.32 kB
"""Frozen reviewer_v8 Code path with admission-safe Math and high-effort MMLU."""
import hashlib
import json
import re
import subprocess
import sys
_SAMPLE_HEADER = re.compile(r"^Sample (Input|Output) (\d+)\s*$", re.MULTILINE)
_CODE_MARKERS = (
"Write a complete Python 3 program",
"standard input",
"standard output",
)
_TAG_BASE = 10**19
_TAG_WIDTH = 10**19
def _samples(prompt, limit):
text = str(prompt).replace("\r\n", "\n").replace("\r", "\n")
marks = [
(m.start(), m.end(), m.group(1), int(m.group(2)))
for m in _SAMPLE_HEADER.finditer(text)
]
blocks = {}
for i, (_start, end, kind, number) in enumerate(marks):
stop = marks[i + 1][0] if i + 1 < len(marks) else len(text)
lines = text[end:stop].split("\n")
while lines and not lines[0].strip():
lines.pop(0)
kept = []
for line in lines:
if not line.strip():
break
kept.append(line)
blocks[kind, number] = "\n".join(kept)
pairs = []
for number in sorted({n for _kind, n in blocks}):
sample_in = blocks.get(("Input", number))
sample_out = blocks.get(("Output", number))
if sample_in and sample_out:
pairs.append((sample_in, sample_out))
return pairs[:limit]
def _extract_python(answer):
text = str(answer or "")
if "```" not in text:
return text.strip() + "\n"
for block in text.split("```"):
candidate = block.strip()
if candidate.lower().startswith("python"):
candidate = candidate[6:].lstrip()
if "print" in candidate or "input" in candidate or "sys.stdin" in candidate:
return candidate.rstrip() + "\n"
return text.strip() + "\n"
def _first_sample_failure(answer, samples, timeout_s):
code = _extract_python(answer)
if not code.strip():
return samples[0] + ("",) if samples else None
for sample_in, expected in samples:
try:
run = subprocess.run(
[sys.executable, "-I", "-c", code],
input=sample_in,
capture_output=True,
text=True,
timeout=timeout_s,
)
actual = run.stdout
except subprocess.TimeoutExpired:
return sample_in, expected, "[sample execution timed out]"
except OSError as exc:
return sample_in, expected, "[sample execution failed: " + type(exc).__name__ + "]"
if run.returncode != 0:
return sample_in, expected, "[sample execution exited nonzero]"
if actual.split() != expected.split():
return sample_in, expected, actual
return None
def _params(cfg, effort):
return {
"max_tokens": int(cfg["max_tokens"]),
"reasoning": {"effort": effort},
}
def _is_code_prompt(text):
return all(marker in text for marker in _CODE_MARKERS)
def _is_mcq_prompt(text):
return text.lstrip().startswith("[MMLU]")
def _admission_safe_prompt(text, domain):
if _is_code_prompt(text) or _is_mcq_prompt(text):
return text
digest = hashlib.sha256((domain + text).encode("utf-8")).digest()
tag = _TAG_BASE + int.from_bytes(digest[:16], "big") % _TAG_WIDTH
return (
text
+ "\n\nRequest tracking tag: "
+ str(tag)
+ ". Treat this tag as metadata; do not include it in the answer."
)
def build_agent(weights):
cfg = json.loads(bytes(weights).decode("utf-8"))
required = {
"version",
"primary_model",
"fallback_model",
"floor_model",
"max_tokens",
"primary_effort",
"fallback_effort",
"mmlu_effort",
"sample_timeout_s",
"max_samples",
"review_passing_code",
"admission_tag_domain",
}
if not isinstance(cfg, dict) or set(cfg) != required or cfg["version"] != 7:
raise ValueError("unsupported reviewer-agent weights")
if cfg["review_passing_code"] is not True:
raise ValueError("review_passing_code must be true")
if cfg["mmlu_effort"] != "high":
raise ValueError("mmlu_effort must be high")
if not 1 <= int(cfg["max_samples"]) <= 6:
raise ValueError("max_samples out of range")
if not 0.1 <= float(cfg["sample_timeout_s"]) <= 5.0:
raise ValueError("sample_timeout_s out of range")
domain = cfg["admission_tag_domain"]
if not isinstance(domain, str) or not (8 <= len(domain) <= 80):
raise ValueError("invalid admission_tag_domain")
def agent(prompt, call_model):
text = str(prompt)
is_code = _is_code_prompt(text)
is_mcq = _is_mcq_prompt(text)
model = cfg["primary_model"] if is_code else cfg["floor_model"]
effort = cfg["mmlu_effort"] if is_mcq else cfg["primary_effort"]
first = call_model(
model,
[{"role": "user", "content": _admission_safe_prompt(text, domain)}],
_params(cfg, effort),
)
if not is_code:
return first
samples = _samples(text, int(cfg["max_samples"]))
failure = _first_sample_failure(first, samples, float(cfg["sample_timeout_s"]))
if failure is not None:
sample_in, expected, actual = failure
review = (
"The previous program failed a published sample. Independently re-derive the "
"algorithm, fix all related edge cases, and return raw Python 3 source only.\n\n"
"Sample input:\n" + sample_in + "\n\nExpected output:\n" + expected
+ "\n\nPrevious output:\n" + actual + "\n\nPrevious program:\n" + str(first)
)
else:
review = (
"Independently re-derive the algorithm and audit the previous program for hidden "
"edge cases, complexity limits, indexing, and numeric bounds. Return the corrected "
"program, or the same program if it is already correct. Return raw Python 3 source "
"only.\n\nPrevious program:\n" + str(first)
)
return call_model(
cfg["fallback_model"],
[{"role": "user", "content": text + "\n\n" + review}],
_params(cfg, cfg["fallback_effort"]),
)
return agent