Upload folder using huggingface_hub
Browse files
.gitattributes
CHANGED
|
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
step_payload_20260214.dat filter=lfs diff=lfs merge=lfs -text
|
scaffolding_only/scaffolding/notebook_step.py
ADDED
|
@@ -0,0 +1,1634 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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4 |
+
This runner is intentionally non-Harmony. It uses OpenAI Chat Completions with
|
| 5 |
+
vLLM auto tool-choice + Step tool-call parser, and executes Python tool calls
|
| 6 |
+
in a stateful, killable sandbox process.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import io
|
| 12 |
+
import json
|
| 13 |
+
import logging
|
| 14 |
+
import math
|
| 15 |
+
import multiprocessing as mp
|
| 16 |
+
import os
|
| 17 |
+
import queue
|
| 18 |
+
import re
|
| 19 |
+
import signal
|
| 20 |
+
import subprocess
|
| 21 |
+
import sys
|
| 22 |
+
import threading
|
| 23 |
+
import time
|
| 24 |
+
from collections import Counter, defaultdict
|
| 25 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 26 |
+
from contextlib import redirect_stderr, redirect_stdout
|
| 27 |
+
from dataclasses import dataclass
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any, Optional
|
| 30 |
+
|
| 31 |
+
import pandas as pd
|
| 32 |
+
import polars as pl
|
| 33 |
+
from openai import OpenAI
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# -------------------------------
|
| 37 |
+
# Environment / defaults
|
| 38 |
+
# -------------------------------
|
| 39 |
+
MODEL_PATH = os.getenv("MODEL_PATH", "stepfun-ai/Step-3.5-Flash-GGUF-Q4_K_S")
|
| 40 |
+
VLLM_TOKENIZER = os.getenv("VLLM_TOKENIZER", "stepfun-ai/Step-3.5-Flash")
|
| 41 |
+
VLLM_HF_CONFIG_PATH = os.getenv("VLLM_HF_CONFIG_PATH", VLLM_TOKENIZER)
|
| 42 |
+
REFERENCE_CSV = os.getenv("REFERENCE_CSV", "data/rollout_datasets/imo_answerbench_random100.csv")
|
| 43 |
+
OUTPUT_CSV = os.getenv("OUTPUT_CSV", "step/predictions_step.csv")
|
| 44 |
+
OUTPUT_GENERATIONS_JSON = os.getenv("OUTPUT_GENERATIONS_JSON", "step/generations_step.json")
|
| 45 |
+
OUTPUT_METRICS_JSON = os.getenv("OUTPUT_METRICS_JSON", "")
|
| 46 |
+
VLLM_SERVER_LOG = os.getenv("VLLM_SERVER_LOG", "step/vllm_server_step.log")
|
| 47 |
+
NOTEBOOK_LOG = os.getenv("NOTEBOOK_LOG", "step/notebook_step.log")
|
| 48 |
+
LOCAL_RUN = os.getenv("LOCAL_RUN", "1")
|
| 49 |
+
ID_COLUMN = os.getenv("ID_COLUMN", "id")
|
| 50 |
+
QUESTION_COLUMN = os.getenv("QUESTION_COLUMN", "")
|
| 51 |
+
VLLM_CHAT_TEMPLATE = os.getenv("VLLM_CHAT_TEMPLATE", "")
|
| 52 |
+
VLLM_TOOL_CALL_PARSER = os.getenv("VLLM_TOOL_CALL_PARSER", "step3")
|
| 53 |
+
VLLM_REASONING_PARSER = os.getenv("VLLM_REASONING_PARSER", "step3")
|
| 54 |
+
VLLM_ENABLE_AUTO_TOOL_CHOICE = os.getenv("VLLM_ENABLE_AUTO_TOOL_CHOICE", "1")
|
| 55 |
+
VLLM_ASYNC_SCHEDULING = os.getenv("VLLM_ASYNC_SCHEDULING", "1")
|
| 56 |
+
VLLM_KV_CACHE_DTYPE = os.getenv("VLLM_KV_CACHE_DTYPE", "")
|
| 57 |
+
VLLM_LOAD_FORMAT = os.getenv("VLLM_LOAD_FORMAT", "")
|
| 58 |
+
VLLM_EXTERNAL_BASE_URL = os.getenv("VLLM_EXTERNAL_BASE_URL", "")
|
| 59 |
+
|
| 60 |
+
VLLM_SERVER_PORT = int(os.getenv("VLLM_SERVER_PORT", "8340"))
|
| 61 |
+
VLLM_TENSOR_PARALLEL_SIZE = int(os.getenv("VLLM_TENSOR_PARALLEL_SIZE", "2"))
|
| 62 |
+
VLLM_MAX_NUM_SEQS = int(os.getenv("VLLM_MAX_NUM_SEQS", "16"))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _env_int(name: str, default: int) -> int:
|
| 66 |
+
raw = os.getenv(name)
|
| 67 |
+
if raw is None:
|
| 68 |
+
return default
|
| 69 |
+
try:
|
| 70 |
+
return int(raw)
|
| 71 |
+
except ValueError:
|
| 72 |
+
return default
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _env_float(name: str, default: float) -> float:
|
| 76 |
+
raw = os.getenv(name)
|
| 77 |
+
if raw is None:
|
| 78 |
+
return default
|
| 79 |
+
try:
|
| 80 |
+
return float(raw)
|
| 81 |
+
except ValueError:
|
| 82 |
+
return default
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _env_bool(name: str, default: bool) -> bool:
|
| 86 |
+
raw = os.getenv(name)
|
| 87 |
+
if raw is None:
|
| 88 |
+
return default
|
| 89 |
+
return raw.strip().lower() in {"1", "true", "yes", "y", "on"}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _env_optional_int(name: str, default: int | None) -> int | None:
|
| 93 |
+
raw = os.getenv(name)
|
| 94 |
+
if raw is None or raw.strip() == "":
|
| 95 |
+
return default
|
| 96 |
+
try:
|
| 97 |
+
return int(raw)
|
| 98 |
+
except ValueError:
|
| 99 |
+
return default
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@dataclass(frozen=True)
|
| 103 |
+
class Config:
|
| 104 |
+
model_path: str = MODEL_PATH
|
| 105 |
+
served_model_name: str = os.getenv("SERVED_MODEL_NAME", "step-3.5-flash")
|
| 106 |
+
|
| 107 |
+
# Math/tool instructions
|
| 108 |
+
system_prompt: str = (
|
| 109 |
+
"You are a careful competition math solver. "
|
| 110 |
+
"You may use the python tool to compute or verify results. "
|
| 111 |
+
"Return only the final answer in \\boxed{} at the end."
|
| 112 |
+
)
|
| 113 |
+
preference_prompt: str = (
|
| 114 |
+
"Solve this problem. If useful, call the python tool with valid Python code. "
|
| 115 |
+
"Final answer must be in \\boxed{} ."
|
| 116 |
+
)
|
| 117 |
+
tool_prompt: str = (
|
| 118 |
+
"Execute Python code in a persistent session. "
|
| 119 |
+
"Use print(...) to show outputs. Available modules include math, numpy, sympy, "
|
| 120 |
+
"itertools, and collections."
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# Runtime controls
|
| 124 |
+
high_problem_timeout: int = _env_int("CFG_HIGH_PROBLEM_TIMEOUT", 900)
|
| 125 |
+
base_problem_timeout: int = _env_int("CFG_BASE_PROBLEM_TIMEOUT", 300)
|
| 126 |
+
session_limit: int = _env_int("CFG_SESSION_LIMIT", 17520)
|
| 127 |
+
server_timeout: int = _env_int("CFG_SERVER_TIMEOUT", 900)
|
| 128 |
+
session_timeout: int = _env_int("CFG_SESSION_TIMEOUT", 1800)
|
| 129 |
+
execution_timeout: int = _env_int("CFG_EXECUTION_TIMEOUT", 10)
|
| 130 |
+
sandbox_timeout: int = _env_int("CFG_SANDBOX_TIMEOUT", 5)
|
| 131 |
+
chat_timeout: int = _env_int("CFG_CHAT_TIMEOUT", 180)
|
| 132 |
+
max_chat_retries: int = _env_int("CFG_MAX_CHAT_RETRIES", 8)
|
| 133 |
+
|
| 134 |
+
context_tokens: int = _env_int("CFG_CONTEXT_TOKENS", 65536)
|
| 135 |
+
max_tokens: int = _env_int("CFG_MAX_TOKENS", context_tokens)
|
| 136 |
+
# Backward-compatible alias: if CFG_MAX_TOKENS is unset, allow CFG_MAX_NEW_TOKENS.
|
| 137 |
+
max_new_tokens: int = _env_int("CFG_MAX_NEW_TOKENS", max_tokens)
|
| 138 |
+
turn_max_tokens: int = _env_int("CFG_TURN_MAX_TOKENS", 0)
|
| 139 |
+
continue_after_length: bool = _env_bool("CFG_CONTINUE_AFTER_LENGTH", True)
|
| 140 |
+
append_preference_prompt: bool = _env_bool("CFG_APPEND_PREFERENCE_PROMPT", False)
|
| 141 |
+
use_system_prompt: bool = _env_bool("CFG_USE_SYSTEM_PROMPT", True)
|
| 142 |
+
allow_fallback_tool_code: bool = _env_bool("CFG_ALLOW_FALLBACK_TOOL_CODE", True)
|
| 143 |
+
disable_majority_vote: bool = _env_bool("CFG_DISABLE_MAJORITY_VOTE", False)
|
| 144 |
+
|
| 145 |
+
early_stop: int = _env_int("CFG_EARLY_STOP", 4)
|
| 146 |
+
disable_majority_early_stop: bool = _env_bool("CFG_DISABLE_MAJORITY_EARLY_STOP", False)
|
| 147 |
+
attempts: int = _env_int("CFG_ATTEMPTS", 8)
|
| 148 |
+
workers: int = _env_int("CFG_WORKERS", 8)
|
| 149 |
+
question_parallel: int = _env_int("CFG_QUESTION_PARALLEL", 1)
|
| 150 |
+
sandbox_pool_size: int = _env_int("CFG_SANDBOX_POOL_SIZE", 0)
|
| 151 |
+
turns: int = _env_int("CFG_TURNS", 64)
|
| 152 |
+
seed: int = _env_int("CFG_SEED", 42)
|
| 153 |
+
|
| 154 |
+
gpu_memory_utilization: float = _env_float("CFG_GPU_MEMORY_UTILIZATION", 0.96)
|
| 155 |
+
temperature: float = _env_float("CFG_TEMPERATURE", 1.0)
|
| 156 |
+
min_p: float = _env_float("CFG_MIN_P", 0.02)
|
| 157 |
+
|
| 158 |
+
dtype: str = os.getenv("VLLM_DTYPE", "auto")
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
CFG = Config()
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# -------------------------------
|
| 165 |
+
# Logging
|
| 166 |
+
# -------------------------------
|
| 167 |
+
Path(NOTEBOOK_LOG).parent.mkdir(parents=True, exist_ok=True)
|
| 168 |
+
|
| 169 |
+
log = logging.getLogger("notebook_step")
|
| 170 |
+
log.setLevel(logging.INFO)
|
| 171 |
+
log.handlers.clear()
|
| 172 |
+
|
| 173 |
+
_fmt = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
|
| 174 |
+
_file_handler = logging.FileHandler(NOTEBOOK_LOG)
|
| 175 |
+
_file_handler.setFormatter(_fmt)
|
| 176 |
+
log.addHandler(_file_handler)
|
| 177 |
+
|
| 178 |
+
_stdout_handler = logging.StreamHandler(sys.stdout)
|
| 179 |
+
_stdout_handler.setFormatter(_fmt)
|
| 180 |
+
log.addHandler(_stdout_handler)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _normalize_answer(value: Any) -> Any:
|
| 184 |
+
if value is None:
|
| 185 |
+
return None
|
| 186 |
+
try:
|
| 187 |
+
if pd.isna(value):
|
| 188 |
+
return None
|
| 189 |
+
except Exception:
|
| 190 |
+
pass
|
| 191 |
+
|
| 192 |
+
if isinstance(value, bool):
|
| 193 |
+
return int(value)
|
| 194 |
+
if isinstance(value, int):
|
| 195 |
+
return value
|
| 196 |
+
if isinstance(value, float):
|
| 197 |
+
if value.is_integer():
|
| 198 |
+
return int(value)
|
| 199 |
+
return str(value).strip()
|
| 200 |
+
|
| 201 |
+
text = str(value).strip()
|
| 202 |
+
if not text:
|
| 203 |
+
return ""
|
| 204 |
+
if text.startswith(r"\(") and text.endswith(r"\)"):
|
| 205 |
+
text = text[2:-2].strip()
|
| 206 |
+
if text.startswith("$") and text.endswith("$"):
|
| 207 |
+
text = text[1:-1].strip()
|
| 208 |
+
boxed_match = re.fullmatch(r"\\boxed\{(.+)\}", text)
|
| 209 |
+
if boxed_match:
|
| 210 |
+
text = boxed_match.group(1).strip()
|
| 211 |
+
if re.fullmatch(r"[+-]?\d+", text):
|
| 212 |
+
try:
|
| 213 |
+
return int(text)
|
| 214 |
+
except ValueError:
|
| 215 |
+
pass
|
| 216 |
+
if re.fullmatch(r"[+-]?\d+\.0+", text):
|
| 217 |
+
try:
|
| 218 |
+
return int(float(text))
|
| 219 |
+
except ValueError:
|
| 220 |
+
pass
|
| 221 |
+
return text
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _extract_boxed_candidates(text: str) -> list[str]:
|
| 225 |
+
if not text:
|
| 226 |
+
return []
|
| 227 |
+
return [m.strip() for m in re.findall(r"\\boxed\s*\{\s*([^{}]+?)\s*\}", text)]
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _answers_match(pred: Any, gt: Any) -> bool:
|
| 231 |
+
pred_norm = _normalize_answer(pred)
|
| 232 |
+
gt_norm = _normalize_answer(gt)
|
| 233 |
+
if pred_norm == gt_norm:
|
| 234 |
+
return True
|
| 235 |
+
|
| 236 |
+
pred_text = str(pred_norm).strip() if pred_norm is not None else ""
|
| 237 |
+
gt_text = str(gt_norm).strip() if gt_norm is not None else ""
|
| 238 |
+
if not pred_text or not gt_text:
|
| 239 |
+
return False
|
| 240 |
+
|
| 241 |
+
pred_boxed = _extract_boxed_candidates(pred_text)
|
| 242 |
+
if pred_boxed and any(gt_text in candidate for candidate in pred_boxed):
|
| 243 |
+
return True
|
| 244 |
+
if gt_text in pred_text:
|
| 245 |
+
return True
|
| 246 |
+
return False
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# -------------------------------
|
| 250 |
+
# Stateful, killable sandbox
|
| 251 |
+
# -------------------------------
|
| 252 |
+
class AIMO3Sandbox:
|
| 253 |
+
"""Persistent Python worker process. Kills/restarts on timeout."""
|
| 254 |
+
|
| 255 |
+
_init_code = (
|
| 256 |
+
"import math\n"
|
| 257 |
+
"import sympy\n"
|
| 258 |
+
"import itertools\n"
|
| 259 |
+
"import collections\n"
|
| 260 |
+
"import numpy as np\n"
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
@staticmethod
|
| 264 |
+
def _worker_main(conn, init_code: str) -> None:
|
| 265 |
+
namespace: dict[str, Any] = {}
|
| 266 |
+
|
| 267 |
+
def _format_traceback(tb_str: str) -> str:
|
| 268 |
+
return re.sub(r"\x1b\[[0-9;]*m", "", tb_str)
|
| 269 |
+
|
| 270 |
+
def _init_namespace() -> None:
|
| 271 |
+
namespace.clear()
|
| 272 |
+
out = io.StringIO()
|
| 273 |
+
err = io.StringIO()
|
| 274 |
+
with redirect_stdout(out), redirect_stderr(err):
|
| 275 |
+
exec(init_code, namespace)
|
| 276 |
+
|
| 277 |
+
try:
|
| 278 |
+
_init_namespace()
|
| 279 |
+
except BaseException as exc:
|
| 280 |
+
conn.send({"ok": False, "output": f"[ERROR] Sandbox init failed: {exc}"})
|
| 281 |
+
conn.close()
|
| 282 |
+
return
|
| 283 |
+
|
| 284 |
+
while True:
|
| 285 |
+
try:
|
| 286 |
+
msg = conn.recv()
|
| 287 |
+
except EOFError:
|
| 288 |
+
break
|
| 289 |
+
|
| 290 |
+
cmd = msg.get("cmd")
|
| 291 |
+
if cmd == "close":
|
| 292 |
+
conn.send({"ok": True, "output": ""})
|
| 293 |
+
break
|
| 294 |
+
|
| 295 |
+
if cmd == "reset":
|
| 296 |
+
try:
|
| 297 |
+
_init_namespace()
|
| 298 |
+
conn.send({"ok": True, "output": ""})
|
| 299 |
+
except BaseException as exc:
|
| 300 |
+
conn.send({"ok": False, "output": f"[ERROR] Sandbox reset failed: {exc}"})
|
| 301 |
+
continue
|
| 302 |
+
|
| 303 |
+
if cmd != "exec":
|
| 304 |
+
conn.send({"ok": False, "output": f"[ERROR] Unknown command: {cmd}"})
|
| 305 |
+
continue
|
| 306 |
+
|
| 307 |
+
code = msg.get("code", "")
|
| 308 |
+
out_io = io.StringIO()
|
| 309 |
+
err_io = io.StringIO()
|
| 310 |
+
try:
|
| 311 |
+
with redirect_stdout(out_io), redirect_stderr(err_io):
|
| 312 |
+
exec(code, namespace)
|
| 313 |
+
except Exception:
|
| 314 |
+
import traceback
|
| 315 |
+
|
| 316 |
+
err_io.write(_format_traceback(traceback.format_exc()))
|
| 317 |
+
|
| 318 |
+
stdout = out_io.getvalue()
|
| 319 |
+
stderr = err_io.getvalue()
|
| 320 |
+
if stderr:
|
| 321 |
+
output = f"{stdout.rstrip()}\n{stderr}" if stdout else stderr
|
| 322 |
+
else:
|
| 323 |
+
output = stdout if stdout.strip() else "[WARN] No output. Use print() to see results."
|
| 324 |
+
conn.send({"ok": True, "output": output})
|
| 325 |
+
|
| 326 |
+
conn.close()
|
| 327 |
+
|
| 328 |
+
def __init__(self, timeout: float):
|
| 329 |
+
self._default_timeout = timeout
|
| 330 |
+
self._mp_ctx = mp.get_context("fork")
|
| 331 |
+
self._lock = threading.Lock()
|
| 332 |
+
self._worker = None
|
| 333 |
+
self._parent_conn = None
|
| 334 |
+
self._start_worker()
|
| 335 |
+
|
| 336 |
+
def _start_worker(self) -> None:
|
| 337 |
+
if self._worker is not None and self._worker.is_alive():
|
| 338 |
+
return
|
| 339 |
+
parent_conn, child_conn = self._mp_ctx.Pipe(duplex=True)
|
| 340 |
+
worker = self._mp_ctx.Process(
|
| 341 |
+
target=AIMO3Sandbox._worker_main,
|
| 342 |
+
args=(child_conn, self._init_code),
|
| 343 |
+
daemon=True,
|
| 344 |
+
)
|
| 345 |
+
worker.start()
|
| 346 |
+
child_conn.close()
|
| 347 |
+
self._worker = worker
|
| 348 |
+
self._parent_conn = parent_conn
|
| 349 |
+
|
| 350 |
+
def _stop_worker(self, graceful: bool) -> None:
|
| 351 |
+
worker = self._worker
|
| 352 |
+
parent_conn = self._parent_conn
|
| 353 |
+
|
| 354 |
+
if parent_conn is not None and worker is not None and worker.is_alive() and graceful:
|
| 355 |
+
try:
|
| 356 |
+
parent_conn.send({"cmd": "close"})
|
| 357 |
+
if parent_conn.poll(0.5):
|
| 358 |
+
parent_conn.recv()
|
| 359 |
+
except (BrokenPipeError, EOFError, OSError):
|
| 360 |
+
pass
|
| 361 |
+
|
| 362 |
+
if worker is not None and worker.is_alive():
|
| 363 |
+
worker.terminate()
|
| 364 |
+
worker.join(timeout=1.0)
|
| 365 |
+
if worker.is_alive():
|
| 366 |
+
worker.kill()
|
| 367 |
+
worker.join(timeout=1.0)
|
| 368 |
+
|
| 369 |
+
if parent_conn is not None:
|
| 370 |
+
try:
|
| 371 |
+
parent_conn.close()
|
| 372 |
+
except Exception:
|
| 373 |
+
pass
|
| 374 |
+
|
| 375 |
+
self._worker = None
|
| 376 |
+
self._parent_conn = None
|
| 377 |
+
|
| 378 |
+
def _restart_worker(self) -> None:
|
| 379 |
+
self._stop_worker(graceful=False)
|
| 380 |
+
self._start_worker()
|
| 381 |
+
|
| 382 |
+
def execute(self, code: str, timeout: float | None = None) -> str:
|
| 383 |
+
effective_timeout = self._default_timeout if timeout is None else timeout
|
| 384 |
+
with self._lock:
|
| 385 |
+
if self._worker is None or not self._worker.is_alive():
|
| 386 |
+
self._restart_worker()
|
| 387 |
+
|
| 388 |
+
try:
|
| 389 |
+
assert self._parent_conn is not None
|
| 390 |
+
self._parent_conn.send({"cmd": "exec", "code": code})
|
| 391 |
+
if effective_timeout is not None and effective_timeout > 0:
|
| 392 |
+
if not self._parent_conn.poll(effective_timeout):
|
| 393 |
+
self._restart_worker()
|
| 394 |
+
return f"[ERROR] Execution timed out after {effective_timeout} seconds"
|
| 395 |
+
response = self._parent_conn.recv()
|
| 396 |
+
output = str(response.get("output", ""))
|
| 397 |
+
return output if output else "[WARN] No output. Use print() to see results."
|
| 398 |
+
except (BrokenPipeError, EOFError, OSError):
|
| 399 |
+
self._restart_worker()
|
| 400 |
+
return "[ERROR] Sandbox worker crashed and was restarted"
|
| 401 |
+
|
| 402 |
+
def reset(self) -> None:
|
| 403 |
+
with self._lock:
|
| 404 |
+
if self._worker is None or not self._worker.is_alive():
|
| 405 |
+
self._restart_worker()
|
| 406 |
+
return
|
| 407 |
+
|
| 408 |
+
try:
|
| 409 |
+
assert self._parent_conn is not None
|
| 410 |
+
self._parent_conn.send({"cmd": "reset"})
|
| 411 |
+
if self._default_timeout is not None and self._default_timeout > 0:
|
| 412 |
+
if not self._parent_conn.poll(self._default_timeout):
|
| 413 |
+
self._restart_worker()
|
| 414 |
+
return
|
| 415 |
+
self._parent_conn.recv()
|
| 416 |
+
except (BrokenPipeError, EOFError, OSError):
|
| 417 |
+
self._restart_worker()
|
| 418 |
+
|
| 419 |
+
def close(self) -> None:
|
| 420 |
+
with self._lock:
|
| 421 |
+
self._stop_worker(graceful=True)
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
# -------------------------------
|
| 425 |
+
# Solver
|
| 426 |
+
# -------------------------------
|
| 427 |
+
class StepToolSolver:
|
| 428 |
+
def __init__(self, cfg: Config, port: int = 8340):
|
| 429 |
+
self.cfg = cfg
|
| 430 |
+
self.port = port
|
| 431 |
+
self.base_url = (
|
| 432 |
+
VLLM_EXTERNAL_BASE_URL.rstrip("/")
|
| 433 |
+
if VLLM_EXTERNAL_BASE_URL
|
| 434 |
+
else f"http://127.0.0.1:{port}/v1"
|
| 435 |
+
)
|
| 436 |
+
self.api_key = "sk-local"
|
| 437 |
+
self.started_server = not bool(VLLM_EXTERNAL_BASE_URL)
|
| 438 |
+
self.server_process: subprocess.Popen | None = None
|
| 439 |
+
if self.started_server:
|
| 440 |
+
self.server_process = self._start_server()
|
| 441 |
+
|
| 442 |
+
client_timeout: float | None = None
|
| 443 |
+
if self.cfg.session_timeout > 0:
|
| 444 |
+
client_timeout = float(self.cfg.session_timeout)
|
| 445 |
+
self.client = OpenAI(
|
| 446 |
+
base_url=self.base_url,
|
| 447 |
+
api_key=self.api_key,
|
| 448 |
+
timeout=client_timeout,
|
| 449 |
+
)
|
| 450 |
+
self._wait_for_server()
|
| 451 |
+
self._maybe_autodetect_served_model()
|
| 452 |
+
self._initialize_kernels()
|
| 453 |
+
|
| 454 |
+
self.python_tool = {
|
| 455 |
+
"type": "function",
|
| 456 |
+
"function": {
|
| 457 |
+
"name": "python",
|
| 458 |
+
"description": self.cfg.tool_prompt,
|
| 459 |
+
"parameters": {
|
| 460 |
+
"type": "object",
|
| 461 |
+
"properties": {
|
| 462 |
+
"code": {
|
| 463 |
+
"type": "string",
|
| 464 |
+
"description": "Python code to execute",
|
| 465 |
+
}
|
| 466 |
+
},
|
| 467 |
+
"required": ["code"],
|
| 468 |
+
"additionalProperties": False,
|
| 469 |
+
},
|
| 470 |
+
},
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
def _start_server(self) -> subprocess.Popen:
|
| 474 |
+
env = os.environ.copy()
|
| 475 |
+
env["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
| 476 |
+
env.setdefault("PYTHONPATH", "/home/ubuntu/aimo/vllm")
|
| 477 |
+
env.setdefault("TRANSFORMERS_NO_TF", "1")
|
| 478 |
+
env.setdefault("TRANSFORMERS_NO_FLAX", "1")
|
| 479 |
+
env.setdefault("USE_TF", "0")
|
| 480 |
+
env.setdefault("USE_FLAX", "0")
|
| 481 |
+
|
| 482 |
+
cmd = [
|
| 483 |
+
sys.executable,
|
| 484 |
+
"-m",
|
| 485 |
+
"vllm.entrypoints.openai.api_server",
|
| 486 |
+
"--seed",
|
| 487 |
+
str(self.cfg.seed),
|
| 488 |
+
"--model",
|
| 489 |
+
self.cfg.model_path,
|
| 490 |
+
"--served-model-name",
|
| 491 |
+
self.cfg.served_model_name,
|
| 492 |
+
"--tensor-parallel-size",
|
| 493 |
+
str(VLLM_TENSOR_PARALLEL_SIZE),
|
| 494 |
+
"--disable-custom-all-reduce",
|
| 495 |
+
"--max-num-seqs",
|
| 496 |
+
str(VLLM_MAX_NUM_SEQS),
|
| 497 |
+
"--gpu-memory-utilization",
|
| 498 |
+
str(self.cfg.gpu_memory_utilization),
|
| 499 |
+
"--host",
|
| 500 |
+
"0.0.0.0",
|
| 501 |
+
"--port",
|
| 502 |
+
str(self.port),
|
| 503 |
+
"--dtype",
|
| 504 |
+
self.cfg.dtype,
|
| 505 |
+
"--max-model-len",
|
| 506 |
+
str(self.cfg.context_tokens),
|
| 507 |
+
"--enable-prefix-caching",
|
| 508 |
+
"--trust-remote-code",
|
| 509 |
+
]
|
| 510 |
+
if VLLM_ASYNC_SCHEDULING == "1":
|
| 511 |
+
cmd.append("--async-scheduling")
|
| 512 |
+
if VLLM_KV_CACHE_DTYPE:
|
| 513 |
+
cmd.extend(["--kv-cache-dtype", VLLM_KV_CACHE_DTYPE])
|
| 514 |
+
if VLLM_LOAD_FORMAT:
|
| 515 |
+
cmd.extend(["--load-format", VLLM_LOAD_FORMAT])
|
| 516 |
+
if VLLM_ENABLE_AUTO_TOOL_CHOICE == "1":
|
| 517 |
+
cmd.append("--enable-auto-tool-choice")
|
| 518 |
+
if VLLM_TOOL_CALL_PARSER:
|
| 519 |
+
cmd.extend(["--tool-call-parser", VLLM_TOOL_CALL_PARSER])
|
| 520 |
+
if VLLM_REASONING_PARSER:
|
| 521 |
+
cmd.extend(["--reasoning-parser", VLLM_REASONING_PARSER])
|
| 522 |
+
if VLLM_CHAT_TEMPLATE:
|
| 523 |
+
cmd.extend(["--chat-template", VLLM_CHAT_TEMPLATE])
|
| 524 |
+
|
| 525 |
+
if VLLM_TOKENIZER:
|
| 526 |
+
cmd.extend(["--tokenizer", VLLM_TOKENIZER])
|
| 527 |
+
if VLLM_HF_CONFIG_PATH:
|
| 528 |
+
cmd.extend(["--hf-config-path", VLLM_HF_CONFIG_PATH])
|
| 529 |
+
|
| 530 |
+
Path(VLLM_SERVER_LOG).parent.mkdir(parents=True, exist_ok=True)
|
| 531 |
+
self.log_file = open(VLLM_SERVER_LOG, "w", encoding="utf-8")
|
| 532 |
+
|
| 533 |
+
log.info("Launching vLLM server:")
|
| 534 |
+
log.info(" ".join(cmd))
|
| 535 |
+
|
| 536 |
+
return subprocess.Popen(
|
| 537 |
+
cmd,
|
| 538 |
+
env=env,
|
| 539 |
+
stdout=self.log_file,
|
| 540 |
+
stderr=subprocess.STDOUT,
|
| 541 |
+
start_new_session=True,
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
def _wait_for_server(self) -> None:
|
| 545 |
+
log.info("Waiting for vLLM server...")
|
| 546 |
+
start = time.time()
|
| 547 |
+
|
| 548 |
+
for _ in range(self.cfg.server_timeout):
|
| 549 |
+
if self.started_server and self.server_process is not None:
|
| 550 |
+
rc = self.server_process.poll()
|
| 551 |
+
if rc is not None:
|
| 552 |
+
self.log_file.flush()
|
| 553 |
+
with open(VLLM_SERVER_LOG, "r", encoding="utf-8") as f:
|
| 554 |
+
logs = f.read()
|
| 555 |
+
raise RuntimeError(f"Server died with code {rc}. Full logs:\n{logs}\n")
|
| 556 |
+
|
| 557 |
+
try:
|
| 558 |
+
self.client.models.list()
|
| 559 |
+
elapsed = time.time() - start
|
| 560 |
+
log.info(f"Server is ready (took {elapsed:.2f}s)")
|
| 561 |
+
return
|
| 562 |
+
except Exception:
|
| 563 |
+
time.sleep(1)
|
| 564 |
+
|
| 565 |
+
raise RuntimeError("Server failed to start (timeout).")
|
| 566 |
+
|
| 567 |
+
def _maybe_autodetect_served_model(self) -> None:
|
| 568 |
+
"""Avoid 404s when external server model-id differs from local default."""
|
| 569 |
+
try:
|
| 570 |
+
listed = self.client.models.list()
|
| 571 |
+
ids = [m.id for m in getattr(listed, "data", []) if getattr(m, "id", None)]
|
| 572 |
+
if not ids:
|
| 573 |
+
return
|
| 574 |
+
if self.cfg.served_model_name in ids:
|
| 575 |
+
return
|
| 576 |
+
picked = ids[0]
|
| 577 |
+
log.warning(
|
| 578 |
+
"Configured model id '%s' is not served by endpoint; switching to '%s' (available=%s)",
|
| 579 |
+
self.cfg.served_model_name,
|
| 580 |
+
picked,
|
| 581 |
+
ids,
|
| 582 |
+
)
|
| 583 |
+
object.__setattr__(self.cfg, "served_model_name", picked)
|
| 584 |
+
except Exception as exc:
|
| 585 |
+
log.warning("Unable to auto-detect served model id: %s", exc)
|
| 586 |
+
|
| 587 |
+
def _initialize_kernels(self) -> None:
|
| 588 |
+
pool_size = self.cfg.sandbox_pool_size
|
| 589 |
+
if pool_size <= 0:
|
| 590 |
+
pool_size = max(self.cfg.workers, self.cfg.attempts * self.cfg.question_parallel)
|
| 591 |
+
log.info(f"Initializing {pool_size} sandboxes...")
|
| 592 |
+
self.sandbox_pool: queue.Queue[AIMO3Sandbox] = queue.Queue()
|
| 593 |
+
for _ in range(pool_size):
|
| 594 |
+
self.sandbox_pool.put(AIMO3Sandbox(timeout=self.cfg.execution_timeout))
|
| 595 |
+
log.info("Sandboxes initialized")
|
| 596 |
+
|
| 597 |
+
@staticmethod
|
| 598 |
+
def _scan_for_answer(text: str) -> Any | None:
|
| 599 |
+
# Extract the last simple boxed expression and normalize downstream.
|
| 600 |
+
pattern = r"\\boxed\s*\{\s*([^{}]+?)\s*\}"
|
| 601 |
+
matches = re.findall(pattern, text)
|
| 602 |
+
if not matches:
|
| 603 |
+
return None
|
| 604 |
+
candidate = matches[-1].strip()
|
| 605 |
+
if re.fullmatch(r"[+-]?\d[\d,]*", candidate):
|
| 606 |
+
try:
|
| 607 |
+
return int(candidate.replace(",", ""))
|
| 608 |
+
except ValueError:
|
| 609 |
+
pass
|
| 610 |
+
return candidate
|
| 611 |
+
|
| 612 |
+
@staticmethod
|
| 613 |
+
def _ensure_last_print(code: str) -> str:
|
| 614 |
+
lines = code.strip().split("\n")
|
| 615 |
+
if not lines:
|
| 616 |
+
return code
|
| 617 |
+
last_line = lines[-1].strip()
|
| 618 |
+
if not last_line:
|
| 619 |
+
return code
|
| 620 |
+
if last_line.startswith("#"):
|
| 621 |
+
return code
|
| 622 |
+
if "print(" in last_line or last_line.startswith("import ") or last_line.startswith("from "):
|
| 623 |
+
return code
|
| 624 |
+
lines[-1] = f"print({last_line})"
|
| 625 |
+
return "\n".join(lines)
|
| 626 |
+
|
| 627 |
+
@staticmethod
|
| 628 |
+
def _extract_text_parts(raw: Any) -> str:
|
| 629 |
+
if raw is None:
|
| 630 |
+
return ""
|
| 631 |
+
if isinstance(raw, str):
|
| 632 |
+
return raw
|
| 633 |
+
if isinstance(raw, list):
|
| 634 |
+
parts: list[str] = []
|
| 635 |
+
for item in raw:
|
| 636 |
+
if isinstance(item, str):
|
| 637 |
+
if item:
|
| 638 |
+
parts.append(item)
|
| 639 |
+
continue
|
| 640 |
+
if isinstance(item, dict):
|
| 641 |
+
text = item.get("text") or item.get("content") or ""
|
| 642 |
+
if isinstance(text, str) and text:
|
| 643 |
+
parts.append(text)
|
| 644 |
+
continue
|
| 645 |
+
text = getattr(item, "text", None) or getattr(item, "content", None)
|
| 646 |
+
if isinstance(text, str) and text:
|
| 647 |
+
parts.append(text)
|
| 648 |
+
return "\n".join(parts).strip()
|
| 649 |
+
if isinstance(raw, dict):
|
| 650 |
+
text = raw.get("text") or raw.get("content") or ""
|
| 651 |
+
return text if isinstance(text, str) else ""
|
| 652 |
+
return str(raw)
|
| 653 |
+
|
| 654 |
+
def _extract_message_text(self, msg: Any) -> tuple[str, str]:
|
| 655 |
+
content = self._extract_text_parts(getattr(msg, "content", None))
|
| 656 |
+
reasoning = self._extract_text_parts(getattr(msg, "reasoning_content", None))
|
| 657 |
+
if not reasoning:
|
| 658 |
+
for attr in ("reasoning", "thinking", "analysis"):
|
| 659 |
+
val = getattr(msg, attr, None)
|
| 660 |
+
reasoning = self._extract_text_parts(val)
|
| 661 |
+
if reasoning:
|
| 662 |
+
break
|
| 663 |
+
return content, reasoning
|
| 664 |
+
|
| 665 |
+
@staticmethod
|
| 666 |
+
def _message_debug_summary(obj: Any) -> str:
|
| 667 |
+
finish = getattr(obj, "finish_reason", None)
|
| 668 |
+
message = getattr(obj, "message", obj)
|
| 669 |
+
tool_calls = getattr(message, "tool_calls", None)
|
| 670 |
+
try:
|
| 671 |
+
payload = obj.model_dump(exclude_none=False)
|
| 672 |
+
except Exception:
|
| 673 |
+
payload = {}
|
| 674 |
+
payload_json = json.dumps(payload, ensure_ascii=False, default=str)
|
| 675 |
+
if len(payload_json) > 1600:
|
| 676 |
+
payload_json = payload_json[:1600] + "...(truncated)"
|
| 677 |
+
return (
|
| 678 |
+
f"finish_reason={finish} "
|
| 679 |
+
f"tool_calls_type={type(tool_calls).__name__} "
|
| 680 |
+
f"payload={payload_json}"
|
| 681 |
+
)
|
| 682 |
+
|
| 683 |
+
@staticmethod
|
| 684 |
+
def _safe_json_loads(raw: Any) -> dict[str, Any]:
|
| 685 |
+
if raw is None:
|
| 686 |
+
return {}
|
| 687 |
+
if isinstance(raw, dict):
|
| 688 |
+
return raw
|
| 689 |
+
if isinstance(raw, list):
|
| 690 |
+
return {}
|
| 691 |
+
if not isinstance(raw, str):
|
| 692 |
+
raw = str(raw)
|
| 693 |
+
raw = raw.strip()
|
| 694 |
+
if not raw:
|
| 695 |
+
return {}
|
| 696 |
+
try:
|
| 697 |
+
obj = json.loads(raw)
|
| 698 |
+
if isinstance(obj, dict):
|
| 699 |
+
return obj
|
| 700 |
+
return {}
|
| 701 |
+
except json.JSONDecodeError:
|
| 702 |
+
pass
|
| 703 |
+
|
| 704 |
+
# Loose fallback for malformed arguments.
|
| 705 |
+
code_match = re.search(r'"code"\s*:\s*"(.*)"', raw, flags=re.DOTALL)
|
| 706 |
+
if code_match:
|
| 707 |
+
code_raw = code_match.group(1)
|
| 708 |
+
code = code_raw.encode("utf-8").decode("unicode_escape")
|
| 709 |
+
return {"code": code}
|
| 710 |
+
return {"code": raw}
|
| 711 |
+
|
| 712 |
+
@staticmethod
|
| 713 |
+
def _extract_code(args_obj: dict[str, Any]) -> str:
|
| 714 |
+
for key in ("code", "python", "script", "input"):
|
| 715 |
+
val = args_obj.get(key)
|
| 716 |
+
if isinstance(val, str) and val.strip():
|
| 717 |
+
return val
|
| 718 |
+
return ""
|
| 719 |
+
|
| 720 |
+
def _extract_tool_calls_from_content_blocks(self, raw_content: Any) -> list[dict[str, Any]]:
|
| 721 |
+
if not isinstance(raw_content, list):
|
| 722 |
+
return []
|
| 723 |
+
calls: list[dict[str, Any]] = []
|
| 724 |
+
for idx, block in enumerate(raw_content):
|
| 725 |
+
if isinstance(block, dict):
|
| 726 |
+
payload = block
|
| 727 |
+
else:
|
| 728 |
+
payload = {}
|
| 729 |
+
for attr in ("type", "id", "name", "arguments", "input", "function"):
|
| 730 |
+
val = getattr(block, attr, None)
|
| 731 |
+
if val is not None:
|
| 732 |
+
payload[attr] = val
|
| 733 |
+
block_type = str(payload.get("type", "")).lower()
|
| 734 |
+
fn_name = ""
|
| 735 |
+
fn_args: Any = None
|
| 736 |
+
if block_type in {"tool_call", "function_call"}:
|
| 737 |
+
fn_name = str(payload.get("name") or "")
|
| 738 |
+
fn_args = payload.get("arguments", None)
|
| 739 |
+
fn_obj = payload.get("function")
|
| 740 |
+
if isinstance(fn_obj, dict):
|
| 741 |
+
fn_name = str(fn_obj.get("name") or fn_name)
|
| 742 |
+
if fn_args is None:
|
| 743 |
+
fn_args = fn_obj.get("arguments", None)
|
| 744 |
+
if not fn_name and isinstance(payload.get("function"), dict):
|
| 745 |
+
fn_name = str((payload["function"] or {}).get("name") or "")
|
| 746 |
+
fn_args = (payload["function"] or {}).get("arguments", fn_args)
|
| 747 |
+
if not fn_name:
|
| 748 |
+
continue
|
| 749 |
+
if fn_args is None:
|
| 750 |
+
fn_args = {}
|
| 751 |
+
if isinstance(fn_args, str):
|
| 752 |
+
args_text = fn_args
|
| 753 |
+
else:
|
| 754 |
+
try:
|
| 755 |
+
args_text = json.dumps(fn_args, ensure_ascii=False)
|
| 756 |
+
except Exception:
|
| 757 |
+
args_text = str(fn_args)
|
| 758 |
+
call_id = str(payload.get("id") or f"manual_content_tc_{idx}")
|
| 759 |
+
calls.append(
|
| 760 |
+
{
|
| 761 |
+
"id": call_id,
|
| 762 |
+
"function": {
|
| 763 |
+
"name": fn_name,
|
| 764 |
+
"arguments": args_text,
|
| 765 |
+
},
|
| 766 |
+
}
|
| 767 |
+
)
|
| 768 |
+
return calls
|
| 769 |
+
|
| 770 |
+
@staticmethod
|
| 771 |
+
def _extract_fallback_tool_code(text: str) -> str | None:
|
| 772 |
+
if not text:
|
| 773 |
+
return None
|
| 774 |
+
code_fence = re.search(r"```python\s*(.*?)```", text, flags=re.DOTALL | re.IGNORECASE)
|
| 775 |
+
if code_fence:
|
| 776 |
+
candidate = code_fence.group(1).strip()
|
| 777 |
+
if candidate:
|
| 778 |
+
return candidate
|
| 779 |
+
generic_fence = re.search(r"```\s*(.*?)```", text, flags=re.DOTALL)
|
| 780 |
+
if generic_fence:
|
| 781 |
+
candidate = generic_fence.group(1).strip()
|
| 782 |
+
if candidate:
|
| 783 |
+
return candidate
|
| 784 |
+
xml_param = re.search(
|
| 785 |
+
r"<parameter=[^>]*>(.*?)</parameter>",
|
| 786 |
+
text,
|
| 787 |
+
flags=re.DOTALL | re.IGNORECASE,
|
| 788 |
+
)
|
| 789 |
+
if xml_param:
|
| 790 |
+
candidate = xml_param.group(1).replace("<![CDATA[", "").replace("]]>", "").strip()
|
| 791 |
+
if candidate:
|
| 792 |
+
return candidate
|
| 793 |
+
function_block = re.search(
|
| 794 |
+
r"<function\s*=\s*python[^>]*>(.*?)</function>",
|
| 795 |
+
text,
|
| 796 |
+
flags=re.DOTALL | re.IGNORECASE,
|
| 797 |
+
)
|
| 798 |
+
if function_block:
|
| 799 |
+
candidate = function_block.group(1).strip()
|
| 800 |
+
if candidate:
|
| 801 |
+
return candidate
|
| 802 |
+
return None
|
| 803 |
+
|
| 804 |
+
@staticmethod
|
| 805 |
+
def _parse_tool_calls_from_text(content: str) -> list[dict[str, Any]]:
|
| 806 |
+
if not content:
|
| 807 |
+
return []
|
| 808 |
+
calls: list[dict[str, Any]] = []
|
| 809 |
+
call_pattern = re.compile(
|
| 810 |
+
r"<tool_call>\s*<function=([^\n>]+)>\s*(.*?)</function>\s*</tool_call>",
|
| 811 |
+
flags=re.DOTALL,
|
| 812 |
+
)
|
| 813 |
+
param_pattern = re.compile(
|
| 814 |
+
r"<parameter=([^>\n]+)>\s*(.*?)\s*</parameter>",
|
| 815 |
+
flags=re.DOTALL,
|
| 816 |
+
)
|
| 817 |
+
for idx, match in enumerate(call_pattern.finditer(content)):
|
| 818 |
+
fn_name = match.group(1).strip()
|
| 819 |
+
fn_body = match.group(2)
|
| 820 |
+
args: dict[str, Any] = {}
|
| 821 |
+
for p_name, p_val in param_pattern.findall(fn_body):
|
| 822 |
+
key = p_name.strip()
|
| 823 |
+
val = p_val.strip()
|
| 824 |
+
if not key:
|
| 825 |
+
continue
|
| 826 |
+
args[key] = val
|
| 827 |
+
calls.append(
|
| 828 |
+
{
|
| 829 |
+
"id": f"manual_tc_{idx}",
|
| 830 |
+
"function": {
|
| 831 |
+
"name": fn_name,
|
| 832 |
+
"arguments": json.dumps(args, ensure_ascii=False),
|
| 833 |
+
},
|
| 834 |
+
}
|
| 835 |
+
)
|
| 836 |
+
return calls
|
| 837 |
+
|
| 838 |
+
def _chat_once(
|
| 839 |
+
self,
|
| 840 |
+
messages: list[dict[str, Any]],
|
| 841 |
+
deadline: float | None,
|
| 842 |
+
seed: int,
|
| 843 |
+
):
|
| 844 |
+
remaining = float("inf")
|
| 845 |
+
if deadline is not None:
|
| 846 |
+
remaining = deadline - time.time()
|
| 847 |
+
if remaining <= 0:
|
| 848 |
+
raise TimeoutError("Attempt deadline reached before chat request")
|
| 849 |
+
|
| 850 |
+
req_timeout: float | None = None
|
| 851 |
+
if self.cfg.chat_timeout > 0:
|
| 852 |
+
req_timeout = max(1.0, min(float(self.cfg.chat_timeout), remaining))
|
| 853 |
+
|
| 854 |
+
requested_max_tokens = max(1, int(self.cfg.max_tokens))
|
| 855 |
+
if os.getenv("CFG_MAX_TOKENS") is None and os.getenv("CFG_MAX_NEW_TOKENS") is not None:
|
| 856 |
+
requested_max_tokens = max(1, int(self.cfg.max_new_tokens))
|
| 857 |
+
if self.cfg.turn_max_tokens > 0:
|
| 858 |
+
requested_max_tokens = min(requested_max_tokens, int(self.cfg.turn_max_tokens))
|
| 859 |
+
last_error: Exception | None = None
|
| 860 |
+
|
| 861 |
+
for _ in range(max(1, self.cfg.max_chat_retries)):
|
| 862 |
+
kwargs: dict[str, Any] = {
|
| 863 |
+
"model": self.cfg.served_model_name,
|
| 864 |
+
"messages": messages,
|
| 865 |
+
"temperature": self.cfg.temperature,
|
| 866 |
+
"max_tokens": requested_max_tokens,
|
| 867 |
+
"seed": seed,
|
| 868 |
+
"extra_body": {"min_p": self.cfg.min_p},
|
| 869 |
+
"tools": [self.python_tool],
|
| 870 |
+
}
|
| 871 |
+
if req_timeout is not None:
|
| 872 |
+
kwargs["timeout"] = req_timeout
|
| 873 |
+
if VLLM_ENABLE_AUTO_TOOL_CHOICE == "1":
|
| 874 |
+
kwargs["tool_choice"] = "auto"
|
| 875 |
+
else:
|
| 876 |
+
kwargs["tool_choice"] = "none"
|
| 877 |
+
|
| 878 |
+
try:
|
| 879 |
+
return self.client.chat.completions.create(**kwargs)
|
| 880 |
+
except Exception as exc:
|
| 881 |
+
last_error = exc
|
| 882 |
+
msg = str(exc)
|
| 883 |
+
msg_l = msg.lower()
|
| 884 |
+
maybe_context_400 = (
|
| 885 |
+
("400" in msg or "badrequest" in type(exc).__name__.lower())
|
| 886 |
+
and any(
|
| 887 |
+
token in msg_l
|
| 888 |
+
for token in ("max_tokens", "max token", "context", "sequence length", "too many tokens")
|
| 889 |
+
)
|
| 890 |
+
)
|
| 891 |
+
if maybe_context_400 and requested_max_tokens > 1:
|
| 892 |
+
input_tokens = None
|
| 893 |
+
match = re.search(r"request has\\s+(\\d+)\\s+input tokens", msg, flags=re.IGNORECASE)
|
| 894 |
+
if match:
|
| 895 |
+
try:
|
| 896 |
+
input_tokens = int(match.group(1))
|
| 897 |
+
except Exception:
|
| 898 |
+
input_tokens = None
|
| 899 |
+
if input_tokens is not None:
|
| 900 |
+
reduced = max(1, min(int(self.cfg.max_tokens), int(self.cfg.context_tokens) - input_tokens))
|
| 901 |
+
else:
|
| 902 |
+
reduced = max(1, int(requested_max_tokens * 0.7))
|
| 903 |
+
if reduced >= requested_max_tokens:
|
| 904 |
+
reduced = requested_max_tokens - 1
|
| 905 |
+
log.warning(
|
| 906 |
+
"Reducing max_tokens from %s to %s after request error: %s",
|
| 907 |
+
requested_max_tokens,
|
| 908 |
+
reduced,
|
| 909 |
+
msg[:220],
|
| 910 |
+
)
|
| 911 |
+
requested_max_tokens = reduced
|
| 912 |
+
continue
|
| 913 |
+
raise
|
| 914 |
+
|
| 915 |
+
assert last_error is not None
|
| 916 |
+
raise last_error
|
| 917 |
+
|
| 918 |
+
def _process_attempt(
|
| 919 |
+
self,
|
| 920 |
+
problem: str,
|
| 921 |
+
system_prompt: str,
|
| 922 |
+
attempt_index: int,
|
| 923 |
+
stop_event: threading.Event,
|
| 924 |
+
deadline: float | None,
|
| 925 |
+
) -> dict[str, Any]:
|
| 926 |
+
if stop_event.is_set() or (deadline is not None and time.time() > deadline):
|
| 927 |
+
return {
|
| 928 |
+
"Attempt": attempt_index + 1,
|
| 929 |
+
"Answer": None,
|
| 930 |
+
"Python Calls": 0,
|
| 931 |
+
"Python Errors": 0,
|
| 932 |
+
"Response Length": 0,
|
| 933 |
+
"Generation": "",
|
| 934 |
+
}
|
| 935 |
+
|
| 936 |
+
sandbox = None
|
| 937 |
+
python_calls = 0
|
| 938 |
+
python_errors = 0
|
| 939 |
+
total_chars = 0
|
| 940 |
+
final_answer = None
|
| 941 |
+
generation_chunks: list[str] = []
|
| 942 |
+
empty_turns = 0
|
| 943 |
+
|
| 944 |
+
attempt_seed = int(math.pow(self.cfg.seed + attempt_index, 2))
|
| 945 |
+
|
| 946 |
+
messages: list[dict[str, Any]] = []
|
| 947 |
+
if self.cfg.use_system_prompt and system_prompt:
|
| 948 |
+
messages.append({"role": "system", "content": system_prompt})
|
| 949 |
+
messages.append({"role": "user", "content": problem})
|
| 950 |
+
|
| 951 |
+
try:
|
| 952 |
+
if self.cfg.sandbox_timeout > 0:
|
| 953 |
+
sandbox = self.sandbox_pool.get(timeout=self.cfg.sandbox_timeout)
|
| 954 |
+
else:
|
| 955 |
+
sandbox = self.sandbox_pool.get()
|
| 956 |
+
|
| 957 |
+
for turn in range(self.cfg.turns):
|
| 958 |
+
if stop_event.is_set() or (deadline is not None and time.time() > deadline):
|
| 959 |
+
break
|
| 960 |
+
|
| 961 |
+
resp = self._chat_once(
|
| 962 |
+
messages=messages,
|
| 963 |
+
deadline=deadline,
|
| 964 |
+
seed=attempt_seed + turn,
|
| 965 |
+
)
|
| 966 |
+
choice = resp.choices[0]
|
| 967 |
+
msg = choice.message
|
| 968 |
+
|
| 969 |
+
content, reasoning_content = self._extract_message_text(msg)
|
| 970 |
+
if content:
|
| 971 |
+
generation_chunks.append(content)
|
| 972 |
+
total_chars += len(content)
|
| 973 |
+
if reasoning_content:
|
| 974 |
+
generation_chunks.append(f"\n[reasoning]\n{reasoning_content}")
|
| 975 |
+
|
| 976 |
+
structured_tool_calls = list(msg.tool_calls or [])
|
| 977 |
+
tool_calls: list[Any] = structured_tool_calls
|
| 978 |
+
manual_tool_calls = []
|
| 979 |
+
if not tool_calls:
|
| 980 |
+
parsed_blocks = self._extract_tool_calls_from_content_blocks(getattr(msg, "content", None))
|
| 981 |
+
if parsed_blocks:
|
| 982 |
+
manual_tool_calls = parsed_blocks
|
| 983 |
+
tool_calls = manual_tool_calls
|
| 984 |
+
if not tool_calls:
|
| 985 |
+
parse_sources = []
|
| 986 |
+
if content:
|
| 987 |
+
parse_sources.append(content)
|
| 988 |
+
if reasoning_content:
|
| 989 |
+
parse_sources.append(reasoning_content)
|
| 990 |
+
for src in parse_sources:
|
| 991 |
+
parsed = self._parse_tool_calls_from_text(src)
|
| 992 |
+
if parsed:
|
| 993 |
+
manual_tool_calls = parsed
|
| 994 |
+
tool_calls = manual_tool_calls
|
| 995 |
+
break
|
| 996 |
+
|
| 997 |
+
if tool_calls:
|
| 998 |
+
empty_turns = 0
|
| 999 |
+
if structured_tool_calls:
|
| 1000 |
+
assistant_tool_calls = []
|
| 1001 |
+
for tc in structured_tool_calls:
|
| 1002 |
+
assistant_tool_calls.append(
|
| 1003 |
+
{
|
| 1004 |
+
"id": tc.id,
|
| 1005 |
+
"type": "function",
|
| 1006 |
+
"function": {
|
| 1007 |
+
"name": tc.function.name,
|
| 1008 |
+
"arguments": tc.function.arguments or "{}",
|
| 1009 |
+
},
|
| 1010 |
+
}
|
| 1011 |
+
)
|
| 1012 |
+
messages.append(
|
| 1013 |
+
{
|
| 1014 |
+
"role": "assistant",
|
| 1015 |
+
"content": content or "",
|
| 1016 |
+
"tool_calls": assistant_tool_calls,
|
| 1017 |
+
}
|
| 1018 |
+
)
|
| 1019 |
+
else:
|
| 1020 |
+
# For manual XML tool calls, keep whichever text contained the call.
|
| 1021 |
+
messages.append({"role": "assistant", "content": content or reasoning_content or ""})
|
| 1022 |
+
|
| 1023 |
+
for tc in tool_calls:
|
| 1024 |
+
if structured_tool_calls:
|
| 1025 |
+
fn_name = tc.function.name
|
| 1026 |
+
raw_args = tc.function.arguments or "{}"
|
| 1027 |
+
tool_call_id = tc.id
|
| 1028 |
+
else:
|
| 1029 |
+
fn_name = tc["function"]["name"]
|
| 1030 |
+
raw_args = tc["function"]["arguments"] or "{}"
|
| 1031 |
+
tool_call_id = tc["id"]
|
| 1032 |
+
args_obj = self._safe_json_loads(raw_args)
|
| 1033 |
+
|
| 1034 |
+
if fn_name != "python":
|
| 1035 |
+
python_errors += 1
|
| 1036 |
+
tool_output = f"[ERROR] Unsupported tool '{fn_name}'. Use only 'python'."
|
| 1037 |
+
else:
|
| 1038 |
+
code = self._extract_code(args_obj)
|
| 1039 |
+
code = self._ensure_last_print(code)
|
| 1040 |
+
python_calls += 1
|
| 1041 |
+
exec_timeout: float | None = self.cfg.execution_timeout
|
| 1042 |
+
if exec_timeout <= 0:
|
| 1043 |
+
exec_timeout = None
|
| 1044 |
+
tool_output = sandbox.execute(code, timeout=exec_timeout)
|
| 1045 |
+
if (
|
| 1046 |
+
tool_output.startswith("[ERROR]")
|
| 1047 |
+
or "Traceback" in tool_output
|
| 1048 |
+
or "Error:" in tool_output
|
| 1049 |
+
):
|
| 1050 |
+
python_errors += 1
|
| 1051 |
+
|
| 1052 |
+
messages.append(
|
| 1053 |
+
{
|
| 1054 |
+
"role": "tool",
|
| 1055 |
+
"tool_call_id": tool_call_id,
|
| 1056 |
+
"name": "python",
|
| 1057 |
+
"content": str(tool_output),
|
| 1058 |
+
}
|
| 1059 |
+
)
|
| 1060 |
+
continue
|
| 1061 |
+
|
| 1062 |
+
ran_fallback_tool = False
|
| 1063 |
+
if self.cfg.allow_fallback_tool_code:
|
| 1064 |
+
fallback_code = self._extract_fallback_tool_code(content or reasoning_content or "")
|
| 1065 |
+
if fallback_code:
|
| 1066 |
+
if content or reasoning_content:
|
| 1067 |
+
messages.append({"role": "assistant", "content": content or reasoning_content or ""})
|
| 1068 |
+
python_calls += 1
|
| 1069 |
+
exec_timeout: float | None = self.cfg.execution_timeout
|
| 1070 |
+
if exec_timeout <= 0:
|
| 1071 |
+
exec_timeout = None
|
| 1072 |
+
tool_output = sandbox.execute(self._ensure_last_print(fallback_code), timeout=exec_timeout)
|
| 1073 |
+
if (
|
| 1074 |
+
tool_output.startswith("[ERROR]")
|
| 1075 |
+
or "Traceback" in tool_output
|
| 1076 |
+
or "Error:" in tool_output
|
| 1077 |
+
):
|
| 1078 |
+
python_errors += 1
|
| 1079 |
+
messages.append({"role": "user", "content": f"Python output:\n{tool_output}"})
|
| 1080 |
+
generation_chunks.append("\n[fallback-python]")
|
| 1081 |
+
ran_fallback_tool = True
|
| 1082 |
+
if ran_fallback_tool:
|
| 1083 |
+
continue
|
| 1084 |
+
|
| 1085 |
+
# If assistant returned no tool calls and fallback did not fire, stop this attempt.
|
| 1086 |
+
if content or reasoning_content:
|
| 1087 |
+
messages.append({"role": "assistant", "content": content or reasoning_content or ""})
|
| 1088 |
+
else:
|
| 1089 |
+
debug_summary = self._message_debug_summary(choice)
|
| 1090 |
+
generation_chunks.append(f"\n[empty-response] {debug_summary}")
|
| 1091 |
+
|
| 1092 |
+
final_answer = self._scan_for_answer(content)
|
| 1093 |
+
if final_answer is None and reasoning_content:
|
| 1094 |
+
final_answer = self._scan_for_answer(reasoning_content)
|
| 1095 |
+
if final_answer is not None:
|
| 1096 |
+
break
|
| 1097 |
+
|
| 1098 |
+
finish_reason = getattr(choice, "finish_reason", None)
|
| 1099 |
+
if self.cfg.continue_after_length and finish_reason == "length":
|
| 1100 |
+
messages.append(
|
| 1101 |
+
{
|
| 1102 |
+
"role": "user",
|
| 1103 |
+
"content": "Continue from where you stopped. End with only the final answer in \\boxed{}.",
|
| 1104 |
+
}
|
| 1105 |
+
)
|
| 1106 |
+
generation_chunks.append("\n[continue-after-length]")
|
| 1107 |
+
continue
|
| 1108 |
+
|
| 1109 |
+
generation_chunks.append("\n[no-tool-turn-stop]")
|
| 1110 |
+
break
|
| 1111 |
+
|
| 1112 |
+
if final_answer is None:
|
| 1113 |
+
final_answer = self._scan_for_answer("\n".join(generation_chunks))
|
| 1114 |
+
|
| 1115 |
+
except Exception as exc:
|
| 1116 |
+
import traceback
|
| 1117 |
+
python_errors += 1
|
| 1118 |
+
tb = traceback.format_exc(limit=8)
|
| 1119 |
+
generation_chunks.append(f"\n[attempt-error] {type(exc).__name__}: {exc}\n{tb}")
|
| 1120 |
+
finally:
|
| 1121 |
+
if sandbox is not None:
|
| 1122 |
+
sandbox.reset()
|
| 1123 |
+
self.sandbox_pool.put(sandbox)
|
| 1124 |
+
|
| 1125 |
+
return {
|
| 1126 |
+
"Attempt": attempt_index + 1,
|
| 1127 |
+
"Response Length": total_chars,
|
| 1128 |
+
"Python Calls": python_calls,
|
| 1129 |
+
"Python Errors": python_errors,
|
| 1130 |
+
"Answer": final_answer,
|
| 1131 |
+
"Generation": "".join(generation_chunks),
|
| 1132 |
+
}
|
| 1133 |
+
|
| 1134 |
+
@staticmethod
|
| 1135 |
+
def _select_answer(detailed_results: list[dict[str, Any]]) -> Any:
|
| 1136 |
+
stats = defaultdict(lambda: {"votes": 0, "calls": 0})
|
| 1137 |
+
|
| 1138 |
+
for result in detailed_results:
|
| 1139 |
+
ans = result.get("Answer")
|
| 1140 |
+
if ans is not None:
|
| 1141 |
+
stats[ans]["votes"] += 1
|
| 1142 |
+
stats[ans]["calls"] += result.get("Python Calls", 0)
|
| 1143 |
+
|
| 1144 |
+
sorted_stats = sorted(
|
| 1145 |
+
stats.items(),
|
| 1146 |
+
key=lambda item: (item[1]["votes"], item[1]["calls"]),
|
| 1147 |
+
reverse=True,
|
| 1148 |
+
)
|
| 1149 |
+
|
| 1150 |
+
rows = [(a, d["votes"], d["calls"]) for a, d in sorted_stats]
|
| 1151 |
+
if rows:
|
| 1152 |
+
vote_df = pd.DataFrame(rows, columns=["Answer", "Votes", "Calls"])
|
| 1153 |
+
log.info("\n" + vote_df.to_string())
|
| 1154 |
+
|
| 1155 |
+
final_answer = sorted_stats[0][0]
|
| 1156 |
+
final_votes = sorted_stats[0][1]["votes"]
|
| 1157 |
+
final_calls = sorted_stats[0][1]["calls"]
|
| 1158 |
+
log.info(f"Final Result: {final_answer} | Votes: {final_votes} | Calls: {final_calls}")
|
| 1159 |
+
return final_answer
|
| 1160 |
+
|
| 1161 |
+
@staticmethod
|
| 1162 |
+
def _select_answer_no_majority(detailed_results: list[dict[str, Any]]) -> Any:
|
| 1163 |
+
ordered_results = sorted(
|
| 1164 |
+
detailed_results,
|
| 1165 |
+
key=lambda row: int(row.get("Attempt", 10**9)),
|
| 1166 |
+
)
|
| 1167 |
+
for row in ordered_results:
|
| 1168 |
+
answer = row.get("Answer")
|
| 1169 |
+
if answer is not None:
|
| 1170 |
+
calls = row.get("Python Calls", 0)
|
| 1171 |
+
log.info(f"Final Result: {answer} | Votes: 1 | Calls: {calls} | Strategy: first-valid-attempt")
|
| 1172 |
+
return answer
|
| 1173 |
+
raise ValueError("No valid answer found for non-majority selection.")
|
| 1174 |
+
|
| 1175 |
+
def solve_problem(self, problem: str) -> tuple[Any, str, list[dict[str, Any]]]:
|
| 1176 |
+
problem_start = time.time()
|
| 1177 |
+
log.info(f"Problem: {problem[:200]}...")
|
| 1178 |
+
|
| 1179 |
+
user_input = str(problem).strip()
|
| 1180 |
+
if self.cfg.append_preference_prompt:
|
| 1181 |
+
user_input = f"{user_input} {self.cfg.preference_prompt}".strip()
|
| 1182 |
+
budget: float | None = None
|
| 1183 |
+
if self.cfg.high_problem_timeout > 0:
|
| 1184 |
+
budget = float(self.cfg.high_problem_timeout)
|
| 1185 |
+
elif self.cfg.base_problem_timeout > 0:
|
| 1186 |
+
budget = float(self.cfg.base_problem_timeout)
|
| 1187 |
+
deadline = (time.time() + budget) if budget is not None else None
|
| 1188 |
+
if deadline is not None:
|
| 1189 |
+
log.info(f"Budget: {budget:.2f}s | Deadline: {deadline:.2f}")
|
| 1190 |
+
else:
|
| 1191 |
+
log.info("Budget: unlimited (timeouts disabled)")
|
| 1192 |
+
|
| 1193 |
+
tasks = [(self.cfg.system_prompt, idx) for idx in range(self.cfg.attempts)]
|
| 1194 |
+
|
| 1195 |
+
detailed_results: list[dict[str, Any]] = []
|
| 1196 |
+
valid_answers: list[int] = []
|
| 1197 |
+
early_stop_enabled = (
|
| 1198 |
+
(not self.cfg.disable_majority_early_stop)
|
| 1199 |
+
and (1 <= self.cfg.early_stop <= self.cfg.attempts)
|
| 1200 |
+
)
|
| 1201 |
+
stop_event = threading.Event()
|
| 1202 |
+
|
| 1203 |
+
executor = ThreadPoolExecutor(max_workers=max(1, min(self.cfg.workers, self.cfg.attempts)))
|
| 1204 |
+
try:
|
| 1205 |
+
futures = []
|
| 1206 |
+
for system_prompt, attempt_index in tasks:
|
| 1207 |
+
futures.append(
|
| 1208 |
+
executor.submit(
|
| 1209 |
+
self._process_attempt,
|
| 1210 |
+
user_input,
|
| 1211 |
+
system_prompt,
|
| 1212 |
+
attempt_index,
|
| 1213 |
+
stop_event,
|
| 1214 |
+
deadline,
|
| 1215 |
+
)
|
| 1216 |
+
)
|
| 1217 |
+
|
| 1218 |
+
for future in as_completed(futures):
|
| 1219 |
+
try:
|
| 1220 |
+
result = future.result()
|
| 1221 |
+
detailed_results.append(result)
|
| 1222 |
+
|
| 1223 |
+
ans = result.get("Answer")
|
| 1224 |
+
if ans is not None:
|
| 1225 |
+
valid_answers.append(ans)
|
| 1226 |
+
|
| 1227 |
+
counts = Counter(valid_answers).most_common(1)
|
| 1228 |
+
if early_stop_enabled and counts and counts[0][1] >= self.cfg.early_stop:
|
| 1229 |
+
stop_event.set()
|
| 1230 |
+
for f in futures:
|
| 1231 |
+
f.cancel()
|
| 1232 |
+
break
|
| 1233 |
+
except Exception as exc:
|
| 1234 |
+
log.warning(f"Future failed: {exc}")
|
| 1235 |
+
finally:
|
| 1236 |
+
executor.shutdown(wait=False, cancel_futures=True)
|
| 1237 |
+
|
| 1238 |
+
detailed_results.sort(key=lambda x: int(x.get("Attempt", 0)))
|
| 1239 |
+
|
| 1240 |
+
used = time.time() - problem_start
|
| 1241 |
+
if budget is not None:
|
| 1242 |
+
saved = max(0.0, budget - used)
|
| 1243 |
+
log.info(f"[Budget]: {budget:.2f}s")
|
| 1244 |
+
log.info(f"[Saved time]: {saved:.2f}s")
|
| 1245 |
+
else:
|
| 1246 |
+
log.info("[Budget]: unlimited")
|
| 1247 |
+
log.info(f"[Inference] Took {used:.2f}s")
|
| 1248 |
+
|
| 1249 |
+
if detailed_results:
|
| 1250 |
+
res_df = pd.DataFrame(detailed_results)
|
| 1251 |
+
if "Answer" in res_df.columns:
|
| 1252 |
+
res_df["Answer"] = res_df["Answer"].astype("Int64")
|
| 1253 |
+
log.info("\n" + res_df.to_string())
|
| 1254 |
+
|
| 1255 |
+
if not valid_answers:
|
| 1256 |
+
log.info("Result: 0")
|
| 1257 |
+
fallback = detailed_results[0].get("Generation", "") if detailed_results else ""
|
| 1258 |
+
return 0, str(fallback), detailed_results
|
| 1259 |
+
|
| 1260 |
+
if self.cfg.disable_majority_vote:
|
| 1261 |
+
final_answer = self._select_answer_no_majority(detailed_results)
|
| 1262 |
+
else:
|
| 1263 |
+
final_answer = self._select_answer(detailed_results)
|
| 1264 |
+
generation_candidates = [
|
| 1265 |
+
str(r.get("Generation", ""))
|
| 1266 |
+
for r in detailed_results
|
| 1267 |
+
if r.get("Answer") == final_answer
|
| 1268 |
+
]
|
| 1269 |
+
final_generation = max(generation_candidates, key=len) if generation_candidates else ""
|
| 1270 |
+
return final_answer, final_generation, detailed_results
|
| 1271 |
+
|
| 1272 |
+
def close(self) -> None:
|
| 1273 |
+
if self.started_server and hasattr(self, "server_process") and self.server_process is not None:
|
| 1274 |
+
try:
|
| 1275 |
+
pgid = os.getpgid(self.server_process.pid)
|
| 1276 |
+
os.killpg(pgid, signal.SIGTERM)
|
| 1277 |
+
except Exception:
|
| 1278 |
+
try:
|
| 1279 |
+
self.server_process.terminate()
|
| 1280 |
+
except Exception:
|
| 1281 |
+
pass
|
| 1282 |
+
try:
|
| 1283 |
+
self.server_process.wait(timeout=30)
|
| 1284 |
+
except Exception:
|
| 1285 |
+
pass
|
| 1286 |
+
|
| 1287 |
+
if self.started_server and hasattr(self, "log_file") and self.log_file is not None:
|
| 1288 |
+
try:
|
| 1289 |
+
self.log_file.close()
|
| 1290 |
+
except Exception:
|
| 1291 |
+
pass
|
| 1292 |
+
|
| 1293 |
+
if hasattr(self, "sandbox_pool"):
|
| 1294 |
+
while not self.sandbox_pool.empty():
|
| 1295 |
+
try:
|
| 1296 |
+
sb = self.sandbox_pool.get_nowait()
|
| 1297 |
+
sb.close()
|
| 1298 |
+
except Exception:
|
| 1299 |
+
pass
|
| 1300 |
+
|
| 1301 |
+
|
| 1302 |
+
# -------------------------------
|
| 1303 |
+
# Prediction loop
|
| 1304 |
+
# -------------------------------
|
| 1305 |
+
solver = StepToolSolver(CFG, port=VLLM_SERVER_PORT)
|
| 1306 |
+
_predict_lock = threading.Lock()
|
| 1307 |
+
|
| 1308 |
+
predictions: dict[Any, Any] = {}
|
| 1309 |
+
generation_records: dict[Any, dict[str, Any]] = {}
|
| 1310 |
+
correct_count = 0
|
| 1311 |
+
total_count = 0
|
| 1312 |
+
|
| 1313 |
+
|
| 1314 |
+
def predict(id_: pl.DataFrame, question: pl.DataFrame, answer: Optional[pl.DataFrame] = None) -> pl.DataFrame:
|
| 1315 |
+
global correct_count, total_count, predictions, generation_records
|
| 1316 |
+
|
| 1317 |
+
question_id = id_.item(0, 0)
|
| 1318 |
+
question_text = question.item(0, 0)
|
| 1319 |
+
|
| 1320 |
+
log.info("------")
|
| 1321 |
+
log.info(f"ID: {question_id}")
|
| 1322 |
+
log.info(f"Question: {question_text[:200]}...")
|
| 1323 |
+
|
| 1324 |
+
final_answer, generation_text, attempt_results = solver.solve_problem(question_text)
|
| 1325 |
+
|
| 1326 |
+
with _predict_lock:
|
| 1327 |
+
predictions[question_id] = final_answer
|
| 1328 |
+
total_count += 1
|
| 1329 |
+
|
| 1330 |
+
if question_id in ground_truth:
|
| 1331 |
+
gt = ground_truth[question_id]
|
| 1332 |
+
is_correct = _answers_match(final_answer, gt)
|
| 1333 |
+
if is_correct:
|
| 1334 |
+
correct_count += 1
|
| 1335 |
+
status = "RIGHT" if is_correct else "WRONG"
|
| 1336 |
+
log.info(f"Answer: {final_answer} | Ground Truth: {gt} | {status}")
|
| 1337 |
+
log.info(f"Running Accuracy: {correct_count}/{total_count} ({100.0 * correct_count / total_count:.1f}%)")
|
| 1338 |
+
else:
|
| 1339 |
+
log.info(f"Answer: {final_answer}")
|
| 1340 |
+
|
| 1341 |
+
generation_records[question_id] = {
|
| 1342 |
+
"id": question_id,
|
| 1343 |
+
"question": question_text,
|
| 1344 |
+
"answer": final_answer,
|
| 1345 |
+
"generation": generation_text,
|
| 1346 |
+
"attempts": attempt_results,
|
| 1347 |
+
}
|
| 1348 |
+
|
| 1349 |
+
log.info("------")
|
| 1350 |
+
return pl.DataFrame({"id": question_id, "answer": final_answer})
|
| 1351 |
+
|
| 1352 |
+
|
| 1353 |
+
def _load_reference_csv(path: str) -> pd.DataFrame:
|
| 1354 |
+
frame = pd.read_csv(path)
|
| 1355 |
+
default_question_cols = ("question", "problem", "prompt", "text", "content")
|
| 1356 |
+
has_id_col = (ID_COLUMN in frame.columns) or ("id" in frame.columns)
|
| 1357 |
+
has_question_col = any(col in frame.columns for col in ((QUESTION_COLUMN,) if QUESTION_COLUMN else default_question_cols))
|
| 1358 |
+
if has_id_col and has_question_col:
|
| 1359 |
+
return frame
|
| 1360 |
+
|
| 1361 |
+
fallback = pd.read_csv(path, header=None)
|
| 1362 |
+
if fallback.shape[1] < 2:
|
| 1363 |
+
raise RuntimeError(f"CSV must have at least 2 columns (id, question). Found shape={fallback.shape}.")
|
| 1364 |
+
rename_map = {0: "id", 1: "question"}
|
| 1365 |
+
if fallback.shape[1] >= 3:
|
| 1366 |
+
rename_map[2] = "answer"
|
| 1367 |
+
return fallback.rename(columns=rename_map)
|
| 1368 |
+
|
| 1369 |
+
|
| 1370 |
+
def _ensure_output_parent(path: str) -> None:
|
| 1371 |
+
parent = Path(path).parent
|
| 1372 |
+
if parent and str(parent) not in ("", "."):
|
| 1373 |
+
parent.mkdir(parents=True, exist_ok=True)
|
| 1374 |
+
|
| 1375 |
+
|
| 1376 |
+
def _write_outputs() -> None:
|
| 1377 |
+
with _predict_lock:
|
| 1378 |
+
pred_ids = list(predictions.keys())
|
| 1379 |
+
pred_vals = list(predictions.values())
|
| 1380 |
+
gen_vals = list(generation_records.values())
|
| 1381 |
+
|
| 1382 |
+
_ensure_output_parent(OUTPUT_CSV)
|
| 1383 |
+
out = pl.DataFrame({"id": pred_ids, "answer": pred_vals})
|
| 1384 |
+
out.write_csv(OUTPUT_CSV)
|
| 1385 |
+
log.info(f"Wrote {OUTPUT_CSV}")
|
| 1386 |
+
|
| 1387 |
+
if OUTPUT_GENERATIONS_JSON:
|
| 1388 |
+
_ensure_output_parent(OUTPUT_GENERATIONS_JSON)
|
| 1389 |
+
with open(OUTPUT_GENERATIONS_JSON, "w", encoding="utf-8") as f:
|
| 1390 |
+
json.dump(gen_vals, f, ensure_ascii=False, indent=2)
|
| 1391 |
+
log.info(f"Wrote {OUTPUT_GENERATIONS_JSON}")
|
| 1392 |
+
|
| 1393 |
+
|
| 1394 |
+
def _majority_vote(values: list[Any]) -> Any | None:
|
| 1395 |
+
clean = [v for v in values if v is not None]
|
| 1396 |
+
if not clean:
|
| 1397 |
+
return None
|
| 1398 |
+
counts = Counter(clean)
|
| 1399 |
+
return sorted(counts.items(), key=lambda kv: (-kv[1], repr(kv[0])))[0][0]
|
| 1400 |
+
|
| 1401 |
+
|
| 1402 |
+
def _log_accuracy_against_reference(df_ref: pd.DataFrame) -> None:
|
| 1403 |
+
if "answer" not in df_ref.columns:
|
| 1404 |
+
return
|
| 1405 |
+
|
| 1406 |
+
pred = pd.read_csv(OUTPUT_CSV)
|
| 1407 |
+
ref_id_col = ID_COLUMN if ID_COLUMN in df_ref.columns else "id"
|
| 1408 |
+
pred_id_col = ref_id_col if ref_id_col in pred.columns else "id"
|
| 1409 |
+
if pred_id_col not in pred.columns:
|
| 1410 |
+
raise KeyError(f"Predictions missing id column: {list(pred.columns)}")
|
| 1411 |
+
|
| 1412 |
+
pred_by_id = dict(zip(pred[pred_id_col].astype(str), pred["answer"]))
|
| 1413 |
+
|
| 1414 |
+
correct = 0
|
| 1415 |
+
total = 0
|
| 1416 |
+
missing = 0
|
| 1417 |
+
maj_correct = 0
|
| 1418 |
+
best_correct = 0
|
| 1419 |
+
rollout_correct_total = 0
|
| 1420 |
+
rollout_total = 0
|
| 1421 |
+
rows_summary: list[dict[str, Any]] = []
|
| 1422 |
+
|
| 1423 |
+
for _, row in df_ref.iterrows():
|
| 1424 |
+
rid = str(row[ref_id_col])
|
| 1425 |
+
gt = row["answer"]
|
| 1426 |
+
got = pred_by_id.get(rid)
|
| 1427 |
+
if got is None:
|
| 1428 |
+
missing += 1
|
| 1429 |
+
else:
|
| 1430 |
+
if _answers_match(got, gt):
|
| 1431 |
+
correct += 1
|
| 1432 |
+
total += 1
|
| 1433 |
+
|
| 1434 |
+
record = generation_records.get(rid)
|
| 1435 |
+
attempts_payload = list(record.get("attempts", [])) if isinstance(record, dict) else []
|
| 1436 |
+
attempt_answers = [item.get("Answer") for item in attempts_payload if isinstance(item, dict)]
|
| 1437 |
+
if not attempt_answers:
|
| 1438 |
+
rows_summary.append(
|
| 1439 |
+
{
|
| 1440 |
+
"id": rid,
|
| 1441 |
+
"majority_pred": None,
|
| 1442 |
+
"majority_correct": False,
|
| 1443 |
+
"best_correct": False,
|
| 1444 |
+
"rollout_correct": 0,
|
| 1445 |
+
"rollout_total": 0,
|
| 1446 |
+
}
|
| 1447 |
+
)
|
| 1448 |
+
continue
|
| 1449 |
+
|
| 1450 |
+
correct_flags = [_answers_match(ans, gt) for ans in attempt_answers]
|
| 1451 |
+
rollout_correct = sum(1 for ok in correct_flags if ok)
|
| 1452 |
+
rollout_n = len(attempt_answers)
|
| 1453 |
+
rollout_correct_total += rollout_correct
|
| 1454 |
+
rollout_total += rollout_n
|
| 1455 |
+
|
| 1456 |
+
maj_pred = _majority_vote(attempt_answers)
|
| 1457 |
+
maj_ok = _answers_match(maj_pred, gt)
|
| 1458 |
+
best_ok = rollout_correct > 0
|
| 1459 |
+
if maj_ok:
|
| 1460 |
+
maj_correct += 1
|
| 1461 |
+
if best_ok:
|
| 1462 |
+
best_correct += 1
|
| 1463 |
+
|
| 1464 |
+
rows_summary.append(
|
| 1465 |
+
{
|
| 1466 |
+
"id": rid,
|
| 1467 |
+
"majority_pred": maj_pred,
|
| 1468 |
+
"majority_correct": maj_ok,
|
| 1469 |
+
"best_correct": best_ok,
|
| 1470 |
+
"rollout_correct": rollout_correct,
|
| 1471 |
+
"rollout_total": rollout_n,
|
| 1472 |
+
}
|
| 1473 |
+
)
|
| 1474 |
+
|
| 1475 |
+
acc = correct / total if total else 0.0
|
| 1476 |
+
maj_at_k = maj_correct / total if total else 0.0
|
| 1477 |
+
best_at_k = best_correct / total if total else 0.0
|
| 1478 |
+
avg_rollout_acc = rollout_correct_total / rollout_total if rollout_total else 0.0
|
| 1479 |
+
|
| 1480 |
+
log.info(
|
| 1481 |
+
"Final Accuracy: %s/%s = %.2f%% (missing=%s)",
|
| 1482 |
+
correct,
|
| 1483 |
+
total,
|
| 1484 |
+
100.0 * acc,
|
| 1485 |
+
missing,
|
| 1486 |
+
)
|
| 1487 |
+
log.info(
|
| 1488 |
+
"maj@%s: %s/%s = %.4f%% | best@%s: %s/%s = %.4f%% | avg@%s: %s/%s = %.4f%%",
|
| 1489 |
+
CFG.attempts,
|
| 1490 |
+
maj_correct,
|
| 1491 |
+
total,
|
| 1492 |
+
100.0 * maj_at_k,
|
| 1493 |
+
CFG.attempts,
|
| 1494 |
+
best_correct,
|
| 1495 |
+
total,
|
| 1496 |
+
100.0 * best_at_k,
|
| 1497 |
+
CFG.attempts,
|
| 1498 |
+
rollout_correct_total,
|
| 1499 |
+
rollout_total,
|
| 1500 |
+
100.0 * avg_rollout_acc,
|
| 1501 |
+
)
|
| 1502 |
+
|
| 1503 |
+
metrics_path = OUTPUT_METRICS_JSON
|
| 1504 |
+
if not metrics_path:
|
| 1505 |
+
metrics_path = str(Path(OUTPUT_CSV).with_suffix(".metrics.json"))
|
| 1506 |
+
_ensure_output_parent(metrics_path)
|
| 1507 |
+
payload = {
|
| 1508 |
+
"reference_csv": REFERENCE_CSV,
|
| 1509 |
+
"output_csv": OUTPUT_CSV,
|
| 1510 |
+
"output_generations_json": OUTPUT_GENERATIONS_JSON,
|
| 1511 |
+
"attempts": CFG.attempts,
|
| 1512 |
+
"total_questions": total,
|
| 1513 |
+
"missing_predictions": missing,
|
| 1514 |
+
"accuracy": {
|
| 1515 |
+
"correct": correct,
|
| 1516 |
+
"total": total,
|
| 1517 |
+
"pct": round(100.0 * acc, 4),
|
| 1518 |
+
},
|
| 1519 |
+
"maj_at_k": {
|
| 1520 |
+
"correct": maj_correct,
|
| 1521 |
+
"total": total,
|
| 1522 |
+
"pct": round(100.0 * maj_at_k, 4),
|
| 1523 |
+
},
|
| 1524 |
+
"best_at_k": {
|
| 1525 |
+
"correct": best_correct,
|
| 1526 |
+
"total": total,
|
| 1527 |
+
"pct": round(100.0 * best_at_k, 4),
|
| 1528 |
+
},
|
| 1529 |
+
"avg_at_k": {
|
| 1530 |
+
"correct": rollout_correct_total,
|
| 1531 |
+
"total": rollout_total,
|
| 1532 |
+
"pct": round(100.0 * avg_rollout_acc, 4),
|
| 1533 |
+
},
|
| 1534 |
+
"per_question": rows_summary,
|
| 1535 |
+
}
|
| 1536 |
+
with open(metrics_path, "w", encoding="utf-8") as f:
|
| 1537 |
+
json.dump(payload, f, ensure_ascii=False, indent=2)
|
| 1538 |
+
log.info("Wrote %s", metrics_path)
|
| 1539 |
+
|
| 1540 |
+
|
| 1541 |
+
def main() -> int:
|
| 1542 |
+
global ground_truth
|
| 1543 |
+
|
| 1544 |
+
df = _load_reference_csv(REFERENCE_CSV)
|
| 1545 |
+
|
| 1546 |
+
q_col = QUESTION_COLUMN
|
| 1547 |
+
if not q_col:
|
| 1548 |
+
for c in ("question", "problem", "prompt", "text", "content"):
|
| 1549 |
+
if c in df.columns:
|
| 1550 |
+
q_col = c
|
| 1551 |
+
break
|
| 1552 |
+
if not q_col:
|
| 1553 |
+
raise KeyError(
|
| 1554 |
+
f"CSV has no question column. Found columns: {list(df.columns)}. "
|
| 1555 |
+
"Set QUESTION_COLUMN env var."
|
| 1556 |
+
)
|
| 1557 |
+
|
| 1558 |
+
id_col = ID_COLUMN if ID_COLUMN in df.columns else "id"
|
| 1559 |
+
if id_col not in df.columns:
|
| 1560 |
+
raise KeyError(f"CSV has no id column. Found columns: {list(df.columns)}")
|
| 1561 |
+
|
| 1562 |
+
ground_truth = dict(zip(df[id_col], df["answer"])) if "answer" in df.columns else {}
|
| 1563 |
+
|
| 1564 |
+
# Keep a reference copy without labels in cwd for compatibility with prior flow.
|
| 1565 |
+
df.drop("answer", axis=1, errors="ignore").to_csv("reference.csv", index=False)
|
| 1566 |
+
|
| 1567 |
+
def _eval_one(row) -> pl.DataFrame:
|
| 1568 |
+
raw_id = row[id_col]
|
| 1569 |
+
raw_question = row[q_col]
|
| 1570 |
+
if raw_question is None or (hasattr(raw_question, "__len__") and len(str(raw_question).strip()) == 0):
|
| 1571 |
+
log.warning(f"Empty problem text for id={raw_id}; skipping")
|
| 1572 |
+
with _predict_lock:
|
| 1573 |
+
predictions[raw_id] = 0
|
| 1574 |
+
return pl.DataFrame({"id": [raw_id], "answer": [0]})
|
| 1575 |
+
|
| 1576 |
+
id_df = pl.DataFrame({"id": [raw_id]})
|
| 1577 |
+
q_df = pl.DataFrame({"question": [str(raw_question).strip()]})
|
| 1578 |
+
return predict(id_df, q_df, None)
|
| 1579 |
+
|
| 1580 |
+
question_parallel = max(1, CFG.question_parallel)
|
| 1581 |
+
try:
|
| 1582 |
+
if question_parallel == 1:
|
| 1583 |
+
for _, row in df.iterrows():
|
| 1584 |
+
rid = row[id_col]
|
| 1585 |
+
try:
|
| 1586 |
+
_eval_one(row)
|
| 1587 |
+
except KeyboardInterrupt:
|
| 1588 |
+
raise
|
| 1589 |
+
except Exception as exc:
|
| 1590 |
+
log.warning(f"Problem id={rid} failed: {exc}")
|
| 1591 |
+
with _predict_lock:
|
| 1592 |
+
predictions[rid] = 0
|
| 1593 |
+
finally:
|
| 1594 |
+
_write_outputs()
|
| 1595 |
+
else:
|
| 1596 |
+
rows = [row for _, row in df.iterrows()]
|
| 1597 |
+
total_rows = len(rows)
|
| 1598 |
+
log.info(
|
| 1599 |
+
"Running question-parallel eval: question_parallel=%s, attempts=%s, workers=%s",
|
| 1600 |
+
question_parallel,
|
| 1601 |
+
CFG.attempts,
|
| 1602 |
+
CFG.workers,
|
| 1603 |
+
)
|
| 1604 |
+
completed = 0
|
| 1605 |
+
with ThreadPoolExecutor(max_workers=question_parallel) as eval_executor:
|
| 1606 |
+
future_to_id = {
|
| 1607 |
+
eval_executor.submit(_eval_one, row): row[id_col]
|
| 1608 |
+
for row in rows
|
| 1609 |
+
}
|
| 1610 |
+
for future in as_completed(future_to_id):
|
| 1611 |
+
rid = future_to_id[future]
|
| 1612 |
+
try:
|
| 1613 |
+
future.result()
|
| 1614 |
+
except KeyboardInterrupt:
|
| 1615 |
+
raise
|
| 1616 |
+
except Exception as exc:
|
| 1617 |
+
log.warning(f"Problem id={rid} failed: {exc}")
|
| 1618 |
+
with _predict_lock:
|
| 1619 |
+
predictions[rid] = 0
|
| 1620 |
+
finally:
|
| 1621 |
+
completed += 1
|
| 1622 |
+
if (completed % question_parallel == 0) or (completed == total_rows):
|
| 1623 |
+
log.info("Progress: %s/%s questions complete", completed, total_rows)
|
| 1624 |
+
_write_outputs()
|
| 1625 |
+
|
| 1626 |
+
_write_outputs()
|
| 1627 |
+
_log_accuracy_against_reference(df)
|
| 1628 |
+
return 0
|
| 1629 |
+
finally:
|
| 1630 |
+
solver.close()
|
| 1631 |
+
|
| 1632 |
+
|
| 1633 |
+
if __name__ == "__main__":
|
| 1634 |
+
raise SystemExit(main())
|
scaffolding_only/scaffolding/submission/step3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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# STEP3p5 MXFP4 + REAP-50 (vLLM tool-calls, majority vote)\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"This notebook is designed for Kaggle. It mirrors the `orig.ipynb` environment setup flow, then runs `scaffolding/notebook_step.py` from the repo mounted at `/kaggle/input/aimorepo`.\n"
|
| 10 |
+
]
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "code",
|
| 14 |
+
"metadata": {
|
| 15 |
+
"_kg_hide-output": true
|
| 16 |
+
},
|
| 17 |
+
"source": [
|
| 18 |
+
"%pip uninstall --yes 'keras' 'matplotlib' 'scikit-learn' 'tensorflow'"
|
| 19 |
+
],
|
| 20 |
+
"execution_count": null,
|
| 21 |
+
"outputs": []
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"cell_type": "code",
|
| 25 |
+
"metadata": {},
|
| 26 |
+
"source": [
|
| 27 |
+
"import os\n",
|
| 28 |
+
"import sys\n",
|
| 29 |
+
"import subprocess\n",
|
| 30 |
+
"from pathlib import Path\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"def set_env(input_archive: str, temp_dir: str) -> None:\n",
|
| 33 |
+
" temp_path = Path(temp_dir)\n",
|
| 34 |
+
" wheels_dir = temp_path / 'wheels'\n",
|
| 35 |
+
" if not wheels_dir.exists():\n",
|
| 36 |
+
" temp_path.mkdir(parents=True, exist_ok=True)\n",
|
| 37 |
+
" archive_path = Path(input_archive)\n",
|
| 38 |
+
" if archive_path.exists():\n",
|
| 39 |
+
" subprocess.run(['tar', '-xzf', str(archive_path), '-C', str(temp_path)], check=True)\n",
|
| 40 |
+
" if wheels_dir.exists():\n",
|
| 41 |
+
" subprocess.run([\n",
|
| 42 |
+
" sys.executable,\n",
|
| 43 |
+
" '-m',\n",
|
| 44 |
+
" 'pip',\n",
|
| 45 |
+
" 'install',\n",
|
| 46 |
+
" '--no-index',\n",
|
| 47 |
+
" '--find-links',\n",
|
| 48 |
+
" str(wheels_dir),\n",
|
| 49 |
+
" 'unsloth',\n",
|
| 50 |
+
" 'trl',\n",
|
| 51 |
+
" 'vllm',\n",
|
| 52 |
+
" 'openai_harmony',\n",
|
| 53 |
+
" ], check=True)\n",
|
| 54 |
+
" else:\n",
|
| 55 |
+
" print(f'[WARN] Wheel directory not found at {wheels_dir}; skipping offline wheel install.')\n",
|
| 56 |
+
"\n",
|
| 57 |
+
"set_env(\n",
|
| 58 |
+
" input_archive='/kaggle/input/aimo-3-utils/wheels.tar.gz',\n",
|
| 59 |
+
" temp_dir='/kaggle/tmp/setup',\n",
|
| 60 |
+
")\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"tiktoken_base = Path('/kaggle/tmp/setup/tiktoken_encodings')\n",
|
| 63 |
+
"if tiktoken_base.exists():\n",
|
| 64 |
+
" os.environ['TIKTOKEN_ENCODINGS_BASE'] = str(tiktoken_base)\n",
|
| 65 |
+
" print('[INFO] TIKTOKEN_ENCODINGS_BASE =', os.environ['TIKTOKEN_ENCODINGS_BASE'])\n"
|
| 66 |
+
],
|
| 67 |
+
"execution_count": null,
|
| 68 |
+
"outputs": []
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"cell_type": "code",
|
| 72 |
+
"metadata": {},
|
| 73 |
+
"source": [
|
| 74 |
+
"import os\n",
|
| 75 |
+
"import re\n",
|
| 76 |
+
"import subprocess\n",
|
| 77 |
+
"from pathlib import Path\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"def first_existing(paths):\n",
|
| 80 |
+
" for p in paths:\n",
|
| 81 |
+
" pp = Path(p)\n",
|
| 82 |
+
" if pp.exists():\n",
|
| 83 |
+
" return pp\n",
|
| 84 |
+
" return None\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"REPO_ROOT = first_existing([\n",
|
| 87 |
+
" '/kaggle/input/aimorepo',\n",
|
| 88 |
+
" '/kaggle/working/aimorepo',\n",
|
| 89 |
+
"])\n",
|
| 90 |
+
"if REPO_ROOT is None:\n",
|
| 91 |
+
" raise FileNotFoundError('Repo not found. Expected /kaggle/input/aimorepo (or /kaggle/working/aimorepo).')\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"PATCHED_VLLM = first_existing([\n",
|
| 94 |
+
" REPO_ROOT / 'step' / 'vllm_latest',\n",
|
| 95 |
+
" REPO_ROOT / 'vllm',\n",
|
| 96 |
+
" REPO_ROOT / 'step' / 'vllm_015_patch',\n",
|
| 97 |
+
"])\n",
|
| 98 |
+
"if PATCHED_VLLM is None:\n",
|
| 99 |
+
" raise FileNotFoundError('Could not locate patched vLLM in repo (tried step/vllm_latest, vllm, step/vllm_015_patch).')\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"def score_model_dir(path: Path) -> int:\n",
|
| 102 |
+
" text = str(path).lower()\n",
|
| 103 |
+
" score = 0\n",
|
| 104 |
+
" if 'step' in text:\n",
|
| 105 |
+
" score += 2\n",
|
| 106 |
+
" if '3.5' in text or 'step3p5' in text or 'step35' in text:\n",
|
| 107 |
+
" score += 4\n",
|
| 108 |
+
" if 'mxfp4' in text:\n",
|
| 109 |
+
" score += 6\n",
|
| 110 |
+
" if 'reap' in text or 'keep50' in text or '50' in text:\n",
|
| 111 |
+
" score += 4\n",
|
| 112 |
+
" if 'flash' in text:\n",
|
| 113 |
+
" score += 2\n",
|
| 114 |
+
" if 'gguf' in text:\n",
|
| 115 |
+
" score -= 2\n",
|
| 116 |
+
" return score\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"def discover_model_path(repo_root: Path) -> Path | None:\n",
|
| 119 |
+
" cands = []\n",
|
| 120 |
+
" for cfg in repo_root.rglob('config.json'):\n",
|
| 121 |
+
" parent = cfg.parent\n",
|
| 122 |
+
" sc = score_model_dir(parent)\n",
|
| 123 |
+
" if sc <= 0:\n",
|
| 124 |
+
" continue\n",
|
| 125 |
+
" has_weights = any(parent.glob('*.safetensors')) or (parent / 'model.safetensors.index.json').exists()\n",
|
| 126 |
+
" if has_weights:\n",
|
| 127 |
+
" cands.append((sc, len(str(parent)), parent))\n",
|
| 128 |
+
" if not cands:\n",
|
| 129 |
+
" return None\n",
|
| 130 |
+
" cands.sort(key=lambda x: (-x[0], x[1]))\n",
|
| 131 |
+
" return cands[0][2]\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"model_path = discover_model_path(REPO_ROOT)\n",
|
| 134 |
+
"if model_path is None:\n",
|
| 135 |
+
" env_model_path = os.getenv('MODEL_PATH', '').strip()\n",
|
| 136 |
+
" if env_model_path:\n",
|
| 137 |
+
" model_path = Path(env_model_path)\n",
|
| 138 |
+
" else:\n",
|
| 139 |
+
" raise FileNotFoundError('Could not auto-discover STEP3p5 MXFP4/REAP model path; set MODEL_PATH manually.')\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"reference_default = '/kaggle/input/ai-mathematical-olympiad-progress-prize-3/reference.csv'\n",
|
| 142 |
+
"if not Path(reference_default).exists():\n",
|
| 143 |
+
" reference_default = str(REPO_ROOT / 'reference.csv')\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"def detect_gpu_count() -> int:\n",
|
| 146 |
+
" cvd = os.getenv('CUDA_VISIBLE_DEVICES', '').strip()\n",
|
| 147 |
+
" if cvd and cvd != '-1':\n",
|
| 148 |
+
" ids = [x for x in cvd.split(',') if x.strip()]\n",
|
| 149 |
+
" if ids:\n",
|
| 150 |
+
" return len(ids)\n",
|
| 151 |
+
" try:\n",
|
| 152 |
+
" out = subprocess.check_output(['nvidia-smi', '-L'], text=True, stderr=subprocess.STDOUT)\n",
|
| 153 |
+
" lines = [ln for ln in out.splitlines() if ln.strip().startswith('GPU ')]\n",
|
| 154 |
+
" if lines:\n",
|
| 155 |
+
" return len(lines)\n",
|
| 156 |
+
" except Exception:\n",
|
| 157 |
+
" pass\n",
|
| 158 |
+
" return 1\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"gpu_count = detect_gpu_count()\n",
|
| 161 |
+
"effective_tp = 1 # Kaggle inference submissions are effectively one GPU / one request at a time.\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"os.environ['PYTHONPATH'] = f\"{PATCHED_VLLM}:{os.environ.get('PYTHONPATH','')}\".rstrip(':')\n",
|
| 164 |
+
"os.environ['MODEL_PATH'] = str(model_path)\n",
|
| 165 |
+
"os.environ['SERVED_MODEL_NAME'] = os.getenv('SERVED_MODEL_NAME', 'step-3.5-flash')\n",
|
| 166 |
+
"os.environ['VLLM_TOKENIZER'] = os.getenv('VLLM_TOKENIZER', str(model_path))\n",
|
| 167 |
+
"os.environ['VLLM_HF_CONFIG_PATH'] = os.getenv('VLLM_HF_CONFIG_PATH', str(model_path))\n",
|
| 168 |
+
"os.environ['VLLM_TOOL_CALL_PARSER'] = os.getenv('VLLM_TOOL_CALL_PARSER', 'step3p5')\n",
|
| 169 |
+
"os.environ['VLLM_REASONING_PARSER'] = os.getenv('VLLM_REASONING_PARSER', 'step3p5')\n",
|
| 170 |
+
"os.environ['VLLM_ENABLE_AUTO_TOOL_CHOICE'] = os.getenv('VLLM_ENABLE_AUTO_TOOL_CHOICE', '1')\n",
|
| 171 |
+
"os.environ['VLLM_ASYNC_SCHEDULING'] = os.getenv('VLLM_ASYNC_SCHEDULING', '1')\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"# Majority vote controls\n",
|
| 174 |
+
"os.environ['CFG_ATTEMPTS'] = os.getenv('CFG_ATTEMPTS', '8')\n",
|
| 175 |
+
"os.environ['CFG_EARLY_STOP'] = os.getenv('CFG_EARLY_STOP', '4')\n",
|
| 176 |
+
"os.environ['CFG_DISABLE_MAJORITY_EARLY_STOP'] = os.getenv('CFG_DISABLE_MAJORITY_EARLY_STOP', '0')\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"# Kaggle-safe defaults: one GPU TP, sequential question handling.\n",
|
| 179 |
+
"os.environ['VLLM_TENSOR_PARALLEL_SIZE'] = os.getenv('VLLM_TENSOR_PARALLEL_SIZE', str(effective_tp))\n",
|
| 180 |
+
"os.environ['VLLM_MAX_NUM_SEQS'] = os.getenv('VLLM_MAX_NUM_SEQS', '8')\n",
|
| 181 |
+
"os.environ['CFG_WORKERS'] = os.getenv('CFG_WORKERS', '8')\n",
|
| 182 |
+
"os.environ['CFG_QUESTION_PARALLEL'] = os.getenv('CFG_QUESTION_PARALLEL', '1')\n",
|
| 183 |
+
"os.environ['CFG_SANDBOX_POOL_SIZE'] = os.getenv('CFG_SANDBOX_POOL_SIZE', '16')\n",
|
| 184 |
+
"os.environ['CFG_CONTEXT_TOKENS'] = os.getenv('CFG_CONTEXT_TOKENS', '131072')\n",
|
| 185 |
+
"os.environ['CFG_MAX_TOKENS'] = os.getenv('CFG_MAX_TOKENS', '8192')\n",
|
| 186 |
+
"os.environ['CFG_MAX_NEW_TOKENS'] = os.getenv('CFG_MAX_NEW_TOKENS', os.environ['CFG_MAX_TOKENS'])\n",
|
| 187 |
+
"os.environ['CFG_TURNS'] = os.getenv('CFG_TURNS', '16')\n",
|
| 188 |
+
"os.environ['CFG_USE_SYSTEM_PROMPT'] = os.getenv('CFG_USE_SYSTEM_PROMPT', '0')\n",
|
| 189 |
+
"os.environ['CFG_APPEND_PREFERENCE_PROMPT'] = os.getenv('CFG_APPEND_PREFERENCE_PROMPT', '0')\n",
|
| 190 |
+
"os.environ['CFG_ALLOW_FALLBACK_TOOL_CODE'] = os.getenv('CFG_ALLOW_FALLBACK_TOOL_CODE', '1')\n",
|
| 191 |
+
"os.environ['CFG_DISABLE_MAJORITY_VOTE'] = os.getenv('CFG_DISABLE_MAJORITY_VOTE', '0')\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"os.environ['REFERENCE_CSV'] = os.getenv('REFERENCE_CSV', reference_default)\n",
|
| 194 |
+
"os.environ['OUTPUT_CSV'] = os.getenv('OUTPUT_CSV', '/kaggle/working/predictions.csv')\n",
|
| 195 |
+
"os.environ['OUTPUT_GENERATIONS_JSON'] = os.getenv('OUTPUT_GENERATIONS_JSON', '/kaggle/working/generations.json')\n",
|
| 196 |
+
"os.environ['OUTPUT_METRICS_JSON'] = os.getenv('OUTPUT_METRICS_JSON', '/kaggle/working/metrics.json')\n",
|
| 197 |
+
"os.environ['VLLM_SERVER_LOG'] = os.getenv('VLLM_SERVER_LOG', '/kaggle/working/vllm_server.log')\n",
|
| 198 |
+
"os.environ['NOTEBOOK_LOG'] = os.getenv('NOTEBOOK_LOG', '/kaggle/working/notebook_step.log')\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"print('[INFO] REPO_ROOT =', REPO_ROOT)\n",
|
| 201 |
+
"print('[INFO] GPU_COUNT =', gpu_count)\n",
|
| 202 |
+
"print('[INFO] EFFECTIVE_TP =', os.environ['VLLM_TENSOR_PARALLEL_SIZE'])\n",
|
| 203 |
+
"print('[INFO] PATCHED_VLLM =', PATCHED_VLLM)\n",
|
| 204 |
+
"print('[INFO] MODEL_PATH =', os.environ['MODEL_PATH'])\n",
|
| 205 |
+
"print('[INFO] REFERENCE_CSV =', os.environ['REFERENCE_CSV'])\n",
|
| 206 |
+
"print('[INFO] VLLM_TOKENIZER =', os.environ['VLLM_TOKENIZER'])\n",
|
| 207 |
+
"print('[INFO] TOOL_PARSER =', os.environ['VLLM_TOOL_CALL_PARSER'])\n",
|
| 208 |
+
"print('[INFO] OUTPUT_CSV =', os.environ['OUTPUT_CSV'])\n",
|
| 209 |
+
""
|
| 210 |
+
],
|
| 211 |
+
"execution_count": null,
|
| 212 |
+
"outputs": [],
|
| 213 |
+
"id": "1bd88fc4"
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"metadata": {},
|
| 218 |
+
"source": [
|
| 219 |
+
"import os\n",
|
| 220 |
+
"import sys\n",
|
| 221 |
+
"import subprocess\n",
|
| 222 |
+
"from pathlib import Path\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"script_path = Path(REPO_ROOT) / 'scaffolding' / 'notebook_step.py'\n",
|
| 225 |
+
"if not script_path.exists():\n",
|
| 226 |
+
" raise FileNotFoundError(f'Missing runner script: {script_path}')\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"cmd = [sys.executable, str(script_path)]\n",
|
| 229 |
+
"print('[INFO] Running:', ' '.join(cmd))\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"proc = subprocess.Popen(\n",
|
| 232 |
+
" cmd,\n",
|
| 233 |
+
" stdout=subprocess.PIPE,\n",
|
| 234 |
+
" stderr=subprocess.STDOUT,\n",
|
| 235 |
+
" text=True,\n",
|
| 236 |
+
" bufsize=1,\n",
|
| 237 |
+
" env=os.environ.copy(),\n",
|
| 238 |
+
")\n",
|
| 239 |
+
"for line in proc.stdout:\n",
|
| 240 |
+
" print(line, end='')\n",
|
| 241 |
+
"rc = proc.wait()\n",
|
| 242 |
+
"print('\\n[INFO] notebook_step.py exit code =', rc)\n",
|
| 243 |
+
"if rc != 0:\n",
|
| 244 |
+
" raise RuntimeError(f'Runner failed with exit code {rc}')\n"
|
| 245 |
+
],
|
| 246 |
+
"execution_count": null,
|
| 247 |
+
"outputs": []
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"cell_type": "code",
|
| 251 |
+
"metadata": {},
|
| 252 |
+
"source": [
|
| 253 |
+
"import pandas as pd\n",
|
| 254 |
+
"from pathlib import Path\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"pred_path = Path(os.environ['OUTPUT_CSV'])\n",
|
| 257 |
+
"if pred_path.exists():\n",
|
| 258 |
+
" pred_df = pd.read_csv(pred_path)\n",
|
| 259 |
+
" print(pred_df.head())\n",
|
| 260 |
+
" print('rows =', len(pred_df))\n",
|
| 261 |
+
"else:\n",
|
| 262 |
+
" print('[WARN] Predictions file not found:', pred_path)\n"
|
| 263 |
+
],
|
| 264 |
+
"execution_count": null,
|
| 265 |
+
"outputs": []
|
| 266 |
+
}
|
| 267 |
+
],
|
| 268 |
+
"metadata": {
|
| 269 |
+
"kernelspec": {
|
| 270 |
+
"display_name": "Python 3",
|
| 271 |
+
"language": "python",
|
| 272 |
+
"name": "python3"
|
| 273 |
+
},
|
| 274 |
+
"language_info": {
|
| 275 |
+
"name": "python",
|
| 276 |
+
"version": "3.12"
|
| 277 |
+
}
|
| 278 |
+
},
|
| 279 |
+
"nbformat": 4,
|
| 280 |
+
"nbformat_minor": 5
|
| 281 |
+
}
|
step_payload_20260214.dat
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b21bfb74255565bbdea4859742c2a89f08dfc6728437126f84276efb07d911a
|
| 3 |
+
size 62392671
|