zzqsb's picture
Release the REE tasks and dataset card.
7f50cd1
Raw History Blame Contribute Delete
7.01 kB
"""Deadline adapter for unmodified Crystal v1.1; see ../PORT.md."""
import time
STARTED = time.monotonic()
import asyncio
import json
import math
import os
from pathlib import Path
import sys
import chess
import chess.engine
sys.path.insert(0, str(Path(os.environ["CORE_DIR"]) / "interface"))
from positions import read_positions
WORKERS = 4
NULL_FALLBACK = 8 # Frozen in the supplied audit, from practice residuals only.
SHUTDOWN_RESERVE_SEC = 2.0
ENGINE_GRACE_SEC = 0.5
async def close_engine(engine, transport):
"""Reap the engine even if its normal UCI shutdown fails."""
try:
await asyncio.wait_for(engine.quit(), ENGINE_GRACE_SEC)
except (asyncio.TimeoutError, chess.engine.EngineError):
pass
finally:
# asyncio kills a subprocess that has not exited. Reap it before return,
# including when the global deadline cancels normal UCI shutdown.
transport.close()
await asyncio.wait_for(
asyncio.shield(engine.returncode), ENGINE_GRACE_SEC
)
async def analyse_many(worker, rows, records, search_deadline):
if not rows:
return
transport, engine = await chess.engine.popen_uci(
str(Path(__file__).with_name("engine"))
)
try:
# No configure() call. Search defaults and python-chess's managed
# analysis-mode settings are the same as in the previous adapter.
for offset, (index, fen) in enumerate(rows):
remaining = search_deadline - time.monotonic()
if remaining <= 0:
break
record = records[index]
record["worker"] = worker
# Equal time for remaining positions in this original strided chunk.
# Recompute after each search so early completion releases its time.
allocation = remaining / (len(rows) - offset)
record["allocated_seconds"] = allocation
board = chess.Board(fen)
position_started = time.monotonic()
record["status"] = "searching"
analysis = None
stop_timer = None
try:
analysis = await engine.analysis(
board, chess.engine.Limit(time=allocation), game=board
)
stop_timer = asyncio.get_running_loop().call_later(
max(0.0, search_deadline - time.monotonic()), analysis.stop
)
async for info in analysis:
if "nodes" in info:
record["nodes"] = info["nodes"]
if "time" in info:
record["engine_seconds"] = info["time"]
if "depth" in info:
record["depth"] = info["depth"]
if "score" in info and info.get("multipv", 1) == 1:
# Match previous/main.py: every new primary score clears
# the old claim, including centipawn and bounded scores.
record["claim"] = None
record["final_score_bounded"] = (
"upperbound" in info or "lowerbound" in info
)
if not record["final_score_bounded"]:
record["claim"] = info["score"].pov(board.turn).mate()
await analysis.wait()
record["status"] = "complete"
except asyncio.CancelledError:
# A killed/unresponsive search has no final score to report.
record["claim"] = None
record["status"] = "deadline"
raise
finally:
if stop_timer is not None:
stop_timer.cancel()
if analysis is not None:
analysis.stop()
record["wall_seconds"] = time.monotonic() - position_started
finally:
await close_engine(engine, transport)
async def solve(fens, records, search_deadline):
rows = list(enumerate(fens))
tasks = [
asyncio.create_task(
analyse_many(worker, rows[worker::WORKERS], records, search_deadline)
)
for worker in range(WORKERS)
]
deadline_reached = False
try:
# The UCI stop timers fire first; allow final scores and bestmove to arrive.
await asyncio.wait_for(
asyncio.gather(*tasks),
max(0.001, search_deadline + ENGINE_GRACE_SEC - time.monotonic()),
)
except asyncio.TimeoutError:
deadline_reached = True
finally:
for task in tasks:
if not task.done():
task.cancel()
outcomes = await asyncio.gather(*tasks, return_exceptions=True)
# Do not disguise a broken or unavailable engine as fallback predictions.
for outcome in outcomes:
if isinstance(outcome, Exception):
raise outcome
return deadline_reached
def main():
if len(sys.argv) != 3:
raise SystemExit("usage: run.sh <data dir> <output dir>")
budget = float(os.environ.get("TASK_BUDGET_SEC", "55"))
if not math.isfinite(budget) or budget <= 0:
raise ValueError("TASK_BUDGET_SEC must be finite and positive")
budget = min(55.0, budget)
reserve = min(SHUTDOWN_RESERVE_SEC, budget / 4)
search_deadline = STARTED + budget - reserve
fens = read_positions(sys.argv[1])
records = [
{
"index": index,
"worker": index % WORKERS,
"status": "not_started",
"allocated_seconds": 0.0,
"wall_seconds": 0.0,
"engine_seconds": 0.0,
"nodes": 0,
"depth": None,
"final_score_bounded": None,
"claim": None,
}
for index in range(len(fens))
]
deadline_reached = asyncio.run(solve(fens, records, search_deadline))
claims = [record["claim"] for record in records]
predictions = [NULL_FALLBACK if mate is None else mate for mate in claims]
output = Path(sys.argv[2])
output.mkdir(parents=True, exist_ok=True)
(output / "mates.json").write_text(json.dumps(predictions) + "\n")
(output / "claims.json").write_text(json.dumps(claims) + "\n")
stats = {
"engine": "Crystal v1.1",
"source_commit": "70f1112e6d442d8dc3e9441aaa7996231b951482",
"protocol": "deadline allocation; final-score claims; null-only +8 fallback",
"budget_seconds": budget,
"shutdown_reserve_seconds": reserve,
"wall_seconds": time.monotonic() - STARTED,
"worker_count": WORKERS,
"threads_per_engine": 1,
"forced_deadline_cleanup": deadline_reached,
"total_reported_nodes": sum(record["nodes"] for record in records),
"fallback_count": sum(mate is None for mate in claims),
"positions": records,
}
(output / "run-stats.json").write_text(json.dumps(stats, indent=2) + "\n")
if __name__ == "__main__":
main()