koth-miner-ev4 / source.py
BlueShark1214's picture
Upload source.py with huggingface_hub
ac619f0 verified
Raw History Blame Contribute Delete
11.6 kB
"""General-purpose solve, execute, and verify agent for SN99."""
import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
import time
MODELS = (
"qwen/qwen3.7-flash",
"deepseek/deepseek-v4-flash",
"deepseek/deepseek-v4-pro",
"z-ai/glm-5.2",
"openai/gpt-5.6-luna",
"google/gemini-3.6-flash",
"moonshotai/kimi-k3",
)
FAST = MODELS[4]
REVIEWER = MODELS[5]
SOLVER = MODELS[4]
FORMAT = "blueshark-verify-v2"
RUN_SECONDS = 780.0
RESERVE_SECONDS = 165.0
EXPECTED_TASKS = 6
EXPECTED_CODE_TASKS = 2
SAMPLE_SECONDS = 5.0
STRESS_SECONDS = 24.0
STRESS_CASE_SECONDS = 4.0
STRESS_ROUNDS = 48
SIZES = (1, 2, 3, 5, 8, 13, 21, 34)
SAMPLE_PATTERN = re.compile(
r"Sample (Input|Output) \d+\s*\n+(.*?)(?=\n\s*\n|\Z)", re.S
)
FENCE_PATTERN = re.compile(r"```(?:python)?\s*\n(.*?)```", re.S)
NAMED_PATTERN = re.compile(r"```(reference|generator)\s*\n(.*?)```", re.S)
def _is_code(text):
return (
"Write a complete Python 3 program" in text
and "standard input" in text
and "standard output" in text
)
def _is_choice(text):
body = "\n" + text
return all("\n" + letter + ")" in body for letter in "ABCD")
def _tag(text, marker):
if _is_code(text) or _is_choice(text):
return text
raw = hashlib.blake2b((marker + text).encode(), digest_size=16).digest()
number = int.from_bytes(raw, "big")
return text + ("\n\nRequest marker: %040d. Ignore this marker and do not repeat it." % number)
def _samples(text):
blocks = SAMPLE_PATTERN.findall(text)
inputs = [value.strip() for kind, value in blocks if kind == "Input"]
outputs = [value.strip() for kind, value in blocks if kind == "Output"]
return list(zip(inputs, outputs))
def _program(response):
match = FENCE_PATTERN.search(str(response))
return (match.group(1) if match else str(response)).strip()
def _run(code, input_text, timeout, args=()):
path = None
try:
fd, path = tempfile.mkstemp(suffix=".py")
with os.fdopen(fd, "w") as handle:
handle.write(code)
proc = subprocess.run(
[sys.executable, path, *[str(x) for x in args]],
input=input_text,
capture_output=True,
text=True,
timeout=timeout,
)
if proc.returncode != 0:
note = (proc.stderr or "no stderr").strip().splitlines()[-1][:200]
return None, "exit %d: %s" % (proc.returncode, note)
return proc.stdout, ""
except subprocess.TimeoutExpired:
return None, "timeout"
except Exception as exc:
return None, type(exc).__name__
finally:
if path:
try:
os.unlink(path)
except OSError:
pass
def _sample_failure(code, samples, until):
for input_text, expected in samples:
if time.monotonic() >= until:
return None
actual, note = _run(code, input_text, SAMPLE_SECONDS)
if actual is None:
return input_text, expected, "<no output: %s>" % note
if actual.split() != expected.split():
return input_text, expected, actual.strip() or "<empty output>"
return None
def _same_output(left, right):
a, b = left.split(), right.split()
if len(a) != len(b):
return False
for x, y in zip(a, b):
if x == y:
continue
try:
fx, fy = float(x), float(y)
except ValueError:
return False
if abs(fx - fy) > 1e-7 * max(1.0, abs(fx), abs(fy)):
return False
return True
def _blocks(response):
return {name: code.strip() for name, code in NAMED_PATTERN.findall(str(response))}
def _counterexample(solution, reference, generator, until, seed_start):
for index in range(STRESS_ROUNDS):
if time.monotonic() >= until:
return None
size = SIZES[(index // 6) % len(SIZES)]
case, _ = _run(generator, "", STRESS_CASE_SECONDS, (seed_start + index, size))
if not case or not case.strip():
continue
expected, _ = _run(reference, case, STRESS_CASE_SECONDS)
if expected is None:
continue
actual, note = _run(solution, case, STRESS_CASE_SECONDS)
if actual is None:
return case, "<no output: %s>" % note, expected.strip()
if not _same_output(actual, expected):
return case, actual.strip(), expected.strip()
return None
def _load(weights):
try:
data = json.loads(bytes(weights).decode())
except Exception as exc:
raise ValueError("weights must be JSON") from exc
if data.get("format") != FORMAT or not isinstance(data.get("marker"), str):
raise ValueError("invalid weights")
return data["marker"]
def build_agent(weights):
marker = _load(weights)
clock = {"start": None, "done": 0, "code_done": 0, "latency": {}}
def agent(prompt, call_model):
text = str(prompt)
is_code = _is_code(text)
if clock["start"] is None:
clock["start"] = time.monotonic()
hard_stop = clock["start"] + RUN_SECONDS - RESERVE_SECONDS
def ask(model, messages, tokens=12288, effort="low"):
started = time.monotonic()
response = call_model(
model,
messages,
{"max_tokens": tokens, "reasoning": {"effort": effort}},
)
elapsed = time.monotonic() - started
clock["latency"][model] = max(clock["latency"].get(model, 8.0), elapsed)
return response
def enough_room(model, extra=20.0):
now = time.monotonic()
served = clock["done"] + 1
average = (now - clock["start"]) / served
future = max(0, EXPECTED_TASKS - served) * average
estimate = clock["latency"].get(model, 20.0)
return now + estimate + extra + future < hard_stop
try:
if not is_code:
return ask(
FAST,
[{"role": "user", "content": _tag(text, marker)}],
tokens=8192,
)
instruction = "".join((
"\n\nSolve independently from the statement and constraints. Prove the algorithm "
"before coding. Check minimum and maximum sizes, equality, duplicates, mandatory "
"operations, overwrite effects, integer bounds, complexity, exact formatting, and "
"every worked example. This execution judge compares output tokens exactly even ",
"when a statement mentions numeric tolerance, so infer decimal precision from the "
"worked outputs and reproduce it. If every operation is mandatory, test equality, "
"harmless placements, and later overwrites before accepting a damaging choice. "
"Return only complete raw Python 3 source with buffered I/O.",
))
answer = ask(SOLVER, [{"role": "user", "content": text + instruction}])
samples = _samples(text)
if not samples:
return answer
code_share = max(1, EXPECTED_CODE_TASKS - clock["code_done"])
local_stop = time.monotonic() + max(0.0, hard_stop - time.monotonic()) / code_share
check_until = min(local_stop, hard_stop)
failure = _sample_failure(_program(answer), samples, check_until)
if failure is not None and enough_room(FAST, 15.0):
case, expected, actual = failure
repair = (
text + "\n\nYour proposed program failed a worked example. Input:\n" + case
+ "\n\nIt printed:\n" + actual + "\n\nExpected:\n" + expected
+ "\n\nFind the underlying mistake and return only the corrected complete "
"Python 3 source. Recheck all examples and the maximum constraints."
)
revised = ask(FAST, [{"role": "user", "content": repair}], effort="medium")
if _sample_failure(_program(revised), samples, check_until) is None:
answer = revised
if not enough_room(FAST, STRESS_SECONDS + 20.0):
return answer
tool_request = text + "".join((
"\n\nFor independent testing, write two small Python programs. The first must be "
"an obviously correct exhaustive or direct-simulation reference for small legal "
"inputs and must not reuse an optimized approach. The second must generate legal ",
"small inputs from command-line seed and size arguments, emphasizing minimum sizes, "
"equality, duplicates, extremes, and mandatory no-op cases. Verify the reference on "
"every worked example. Reply only with fenced blocks named reference and generator.",
))
reference = generator = found = None
for attempt in range(3):
if not enough_room(FAST, STRESS_SECONDS + 15.0):
break
request = tool_request + (
"\n\nAttempt marker %d. Build the checker independently from any prior attempt."
% (attempt + 1)
)
tools = _blocks(ask(FAST, [{"role": "user", "content": request}], tokens=12288))
candidate_reference = tools.get("reference")
candidate_generator = tools.get("generator")
if not candidate_reference or not candidate_generator:
continue
if _sample_failure(candidate_reference, samples, check_until) is not None:
continue
reference, generator = candidate_reference, candidate_generator
found = _counterexample(
_program(answer), reference, generator,
min(time.monotonic() + STRESS_SECONDS, check_until),
1709 + 997 * attempt + 97 * clock["code_done"],
)
if found is not None:
break
if found is None or not enough_room(FAST, 15.0):
return answer
case, actual, expected = found
review = (
text + "\n\nAn independent executable reference found a counterexample to the "
"candidate. Input:\n" + case + "\n\nCandidate output:\n" + actual
+ "\n\nReference output:\n" + expected + "\n\nDerive the algorithm yourself, "
"identify the root cause, and return only a corrected complete Python 3 program. "
"It must satisfy the worked examples and maximum constraints.\n\nCandidate:\n"
+ _program(answer)
)
revised = ask(FAST, [{"role": "user", "content": review}], tokens=12288, effort="medium")
if _sample_failure(_program(revised), samples, check_until) is not None:
return answer
second = _counterexample(
_program(revised), reference, generator,
min(time.monotonic() + STRESS_SECONDS, check_until),
9011 + 97 * clock["code_done"],
)
return revised if second is None else answer
except Exception:
if "answer" in locals() and str(answer).strip():
return answer
raise
finally:
clock["done"] += 1
if is_code:
clock["code_done"] += 1
return agent