#!/usr/bin/env python3 """Step-3.5 Flash GGUF eval runner with vLLM tool-calling. This runner is intentionally non-Harmony. It uses OpenAI Chat Completions with vLLM auto tool-choice + Step tool-call parser, and executes Python tool calls in a stateful, killable sandbox process. """ from __future__ import annotations import io import json import logging import math import multiprocessing as mp import os import queue import re import signal import subprocess import sys import threading import time from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import redirect_stderr, redirect_stdout from dataclasses import dataclass from pathlib import Path from typing import Any, Optional import pandas as pd import polars as pl from openai import OpenAI # ------------------------------- # Environment / defaults # ------------------------------- MODEL_PATH = os.getenv("MODEL_PATH", "stepfun-ai/Step-3.5-Flash-GGUF-Q4_K_S") VLLM_TOKENIZER = os.getenv("VLLM_TOKENIZER", "stepfun-ai/Step-3.5-Flash") VLLM_HF_CONFIG_PATH = os.getenv("VLLM_HF_CONFIG_PATH", VLLM_TOKENIZER) REFERENCE_CSV = os.getenv("REFERENCE_CSV", "data/rollout_datasets/imo_answerbench_random100.csv") OUTPUT_CSV = os.getenv("OUTPUT_CSV", "step/predictions_step.csv") OUTPUT_GENERATIONS_JSON = os.getenv("OUTPUT_GENERATIONS_JSON", "step/generations_step.json") OUTPUT_METRICS_JSON = os.getenv("OUTPUT_METRICS_JSON", "") VLLM_SERVER_LOG = os.getenv("VLLM_SERVER_LOG", "step/vllm_server_step.log") NOTEBOOK_LOG = os.getenv("NOTEBOOK_LOG", "step/notebook_step.log") LOCAL_RUN = os.getenv("LOCAL_RUN", "1") ID_COLUMN = os.getenv("ID_COLUMN", "id") QUESTION_COLUMN = os.getenv("QUESTION_COLUMN", "") VLLM_CHAT_TEMPLATE = os.getenv("VLLM_CHAT_TEMPLATE", "") VLLM_TOOL_CALL_PARSER = os.getenv("VLLM_TOOL_CALL_PARSER", "step3") VLLM_REASONING_PARSER = os.getenv("VLLM_REASONING_PARSER", "step3") VLLM_ENABLE_AUTO_TOOL_CHOICE = os.getenv("VLLM_ENABLE_AUTO_TOOL_CHOICE", "1") VLLM_ASYNC_SCHEDULING = os.getenv("VLLM_ASYNC_SCHEDULING", "1") VLLM_KV_CACHE_DTYPE = os.getenv("VLLM_KV_CACHE_DTYPE", "") VLLM_LOAD_FORMAT = os.getenv("VLLM_LOAD_FORMAT", "") VLLM_EXTERNAL_BASE_URL = os.getenv("VLLM_EXTERNAL_BASE_URL", "") VLLM_SERVER_PORT = int(os.getenv("VLLM_SERVER_PORT", "8340")) VLLM_TENSOR_PARALLEL_SIZE = int(os.getenv("VLLM_TENSOR_PARALLEL_SIZE", "2")) VLLM_MAX_NUM_SEQS = int(os.getenv("VLLM_MAX_NUM_SEQS", "16")) def _env_int(name: str, default: int) -> int: raw = os.getenv(name) if raw is None: return default try: return int(raw) except ValueError: return default def _env_float(name: str, default: float) -> float: raw = os.getenv(name) if raw is None: return default try: return float(raw) except ValueError: return default def _env_bool(name: str, default: bool) -> bool: raw = os.getenv(name) if raw is None: return default return raw.strip().lower() in {"1", "true", "yes", "y", "on"} def _env_optional_int(name: str, default: int | None) -> int | None: raw = os.getenv(name) if raw is None or raw.strip() == "": return default try: return int(raw) except ValueError: return default @dataclass(frozen=True) class Config: model_path: str = MODEL_PATH served_model_name: str = os.getenv("SERVED_MODEL_NAME", "step-3.5-flash") # Math/tool instructions system_prompt: str = ( "You are a careful competition math solver. " "You may use the python tool to compute or verify results. " "Return only the final answer in \\boxed{} at the end." ) preference_prompt: str = ( "Solve this problem. If useful, call the python tool with valid Python code. " "Final answer must be in \\boxed{} ." ) tool_prompt: str = ( "Execute Python code in a persistent session. " "Use print(...) to show outputs. Available modules include math, numpy, sympy, " "itertools, and collections." ) # Runtime controls high_problem_timeout: int = _env_int("CFG_HIGH_PROBLEM_TIMEOUT", 900) base_problem_timeout: int = _env_int("CFG_BASE_PROBLEM_TIMEOUT", 300) session_limit: int = _env_int("CFG_SESSION_LIMIT", 17520) server_timeout: int = _env_int("CFG_SERVER_TIMEOUT", 900) session_timeout: int = _env_int("CFG_SESSION_TIMEOUT", 1800) execution_timeout: int = _env_int("CFG_EXECUTION_TIMEOUT", 10) sandbox_timeout: int = _env_int("CFG_SANDBOX_TIMEOUT", 5) chat_timeout: int = _env_int("CFG_CHAT_TIMEOUT", 180) max_chat_retries: int = _env_int("CFG_MAX_CHAT_RETRIES", 8) context_tokens: int = _env_int("CFG_CONTEXT_TOKENS", 65536) max_tokens: int = _env_int("CFG_MAX_TOKENS", context_tokens) # Backward-compatible alias: if CFG_MAX_TOKENS is unset, allow CFG_MAX_NEW_TOKENS. max_new_tokens: int = _env_int("CFG_MAX_NEW_TOKENS", max_tokens) turn_max_tokens: int = _env_int("CFG_TURN_MAX_TOKENS", 0) continue_after_length: bool = _env_bool("CFG_CONTINUE_AFTER_LENGTH", True) append_preference_prompt: bool = _env_bool("CFG_APPEND_PREFERENCE_PROMPT", False) use_system_prompt: bool = _env_bool("CFG_USE_SYSTEM_PROMPT", True) allow_fallback_tool_code: bool = _env_bool("CFG_ALLOW_FALLBACK_TOOL_CODE", True) disable_majority_vote: bool = _env_bool("CFG_DISABLE_MAJORITY_VOTE", False) early_stop: int = _env_int("CFG_EARLY_STOP", 4) disable_majority_early_stop: bool = _env_bool("CFG_DISABLE_MAJORITY_EARLY_STOP", False) attempts: int = _env_int("CFG_ATTEMPTS", 8) workers: int = _env_int("CFG_WORKERS", 8) question_parallel: int = _env_int("CFG_QUESTION_PARALLEL", 1) sandbox_pool_size: int = _env_int("CFG_SANDBOX_POOL_SIZE", 0) turns: int = _env_int("CFG_TURNS", 64) seed: int = _env_int("CFG_SEED", 42) gpu_memory_utilization: float = _env_float("CFG_GPU_MEMORY_UTILIZATION", 0.96) temperature: float = _env_float("CFG_TEMPERATURE", 1.0) min_p: float = _env_float("CFG_MIN_P", 0.02) dtype: str = os.getenv("VLLM_DTYPE", "auto") CFG = Config() # ------------------------------- # Logging # ------------------------------- Path(NOTEBOOK_LOG).parent.mkdir(parents=True, exist_ok=True) log = logging.getLogger("notebook_step") log.setLevel(logging.INFO) log.handlers.clear() _fmt = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") _file_handler = logging.FileHandler(NOTEBOOK_LOG) _file_handler.setFormatter(_fmt) log.addHandler(_file_handler) _stdout_handler = logging.StreamHandler(sys.stdout) _stdout_handler.setFormatter(_fmt) log.addHandler(_stdout_handler) def _normalize_answer(value: Any) -> Any: if value is None: return None try: if pd.isna(value): return None except Exception: pass if isinstance(value, bool): return int(value) if isinstance(value, int): return value if isinstance(value, float): if value.is_integer(): return int(value) return str(value).strip() text = str(value).strip() if not text: return "" if text.startswith(r"\(") and text.endswith(r"\)"): text = text[2:-2].strip() if text.startswith("$") and text.endswith("$"): text = text[1:-1].strip() boxed_match = re.fullmatch(r"\\boxed\{(.+)\}", text) if boxed_match: text = boxed_match.group(1).strip() if re.fullmatch(r"[+-]?\d+", text): try: return int(text) except ValueError: pass if re.fullmatch(r"[+-]?\d+\.0+", text): try: return int(float(text)) except ValueError: pass return text def _extract_boxed_candidates(text: str) -> list[str]: if not text: return [] return [m.strip() for m in re.findall(r"\\boxed\s*\{\s*([^{}]+?)\s*\}", text)] def _answers_match(pred: Any, gt: Any) -> bool: pred_norm = _normalize_answer(pred) gt_norm = _normalize_answer(gt) if pred_norm == gt_norm: return True pred_text = str(pred_norm).strip() if pred_norm is not None else "" gt_text = str(gt_norm).strip() if gt_norm is not None else "" if not pred_text or not gt_text: return False pred_boxed = _extract_boxed_candidates(pred_text) if pred_boxed and any(gt_text in candidate for candidate in pred_boxed): return True if gt_text in pred_text: return True return False # ------------------------------- # Stateful, killable sandbox # ------------------------------- class AIMO3Sandbox: """Persistent Python worker process. Kills/restarts on timeout.""" _init_code = ( "import math\n" "import sympy\n" "import itertools\n" "import collections\n" "import numpy as np\n" ) @staticmethod def _worker_main(conn, init_code: str) -> None: namespace: dict[str, Any] = {} def _format_traceback(tb_str: str) -> str: return re.sub(r"\x1b\[[0-9;]*m", "", tb_str) def _init_namespace() -> None: namespace.clear() out = io.StringIO() err = io.StringIO() with redirect_stdout(out), redirect_stderr(err): exec(init_code, namespace) try: _init_namespace() except BaseException as exc: conn.send({"ok": False, "output": f"[ERROR] Sandbox init failed: {exc}"}) conn.close() return while True: try: msg = conn.recv() except EOFError: break cmd = msg.get("cmd") if cmd == "close": conn.send({"ok": True, "output": ""}) break if cmd == "reset": try: _init_namespace() conn.send({"ok": True, "output": ""}) except BaseException as exc: conn.send({"ok": False, "output": f"[ERROR] Sandbox reset failed: {exc}"}) continue if cmd != "exec": conn.send({"ok": False, "output": f"[ERROR] Unknown command: {cmd}"}) continue code = msg.get("code", "") out_io = io.StringIO() err_io = io.StringIO() try: with redirect_stdout(out_io), redirect_stderr(err_io): exec(code, namespace) except Exception: import traceback err_io.write(_format_traceback(traceback.format_exc())) stdout = out_io.getvalue() stderr = err_io.getvalue() if stderr: output = f"{stdout.rstrip()}\n{stderr}" if stdout else stderr else: output = stdout if stdout.strip() else "[WARN] No output. Use print() to see results." conn.send({"ok": True, "output": output}) conn.close() def __init__(self, timeout: float): self._default_timeout = timeout self._mp_ctx = mp.get_context("fork") self._lock = threading.Lock() self._worker = None self._parent_conn = None self._start_worker() def _start_worker(self) -> None: if self._worker is not None and self._worker.is_alive(): return parent_conn, child_conn = self._mp_ctx.Pipe(duplex=True) worker = self._mp_ctx.Process( target=AIMO3Sandbox._worker_main, args=(child_conn, self._init_code), daemon=True, ) worker.start() child_conn.close() self._worker = worker self._parent_conn = parent_conn def _stop_worker(self, graceful: bool) -> None: worker = self._worker parent_conn = self._parent_conn if parent_conn is not None and worker is not None and worker.is_alive() and graceful: try: parent_conn.send({"cmd": "close"}) if parent_conn.poll(0.5): parent_conn.recv() except (BrokenPipeError, EOFError, OSError): pass if worker is not None and worker.is_alive(): worker.terminate() worker.join(timeout=1.0) if worker.is_alive(): worker.kill() worker.join(timeout=1.0) if parent_conn is not None: try: parent_conn.close() except Exception: pass self._worker = None self._parent_conn = None def _restart_worker(self) -> None: self._stop_worker(graceful=False) self._start_worker() def execute(self, code: str, timeout: float | None = None) -> str: effective_timeout = self._default_timeout if timeout is None else timeout with self._lock: if self._worker is None or not self._worker.is_alive(): self._restart_worker() try: assert self._parent_conn is not None self._parent_conn.send({"cmd": "exec", "code": code}) if effective_timeout is not None and effective_timeout > 0: if not self._parent_conn.poll(effective_timeout): self._restart_worker() return f"[ERROR] Execution timed out after {effective_timeout} seconds" response = self._parent_conn.recv() output = str(response.get("output", "")) return output if output else "[WARN] No output. Use print() to see results." except (BrokenPipeError, EOFError, OSError): self._restart_worker() return "[ERROR] Sandbox worker crashed and was restarted" def reset(self) -> None: with self._lock: if self._worker is None or not self._worker.is_alive(): self._restart_worker() return try: assert self._parent_conn is not None self._parent_conn.send({"cmd": "reset"}) if self._default_timeout is not None and self._default_timeout > 0: if not self._parent_conn.poll(self._default_timeout): self._restart_worker() return self._parent_conn.recv() except (BrokenPipeError, EOFError, OSError): self._restart_worker() def close(self) -> None: with self._lock: self._stop_worker(graceful=True) # ------------------------------- # Solver # ------------------------------- class StepToolSolver: def __init__(self, cfg: Config, port: int = 8340): self.cfg = cfg self.port = port self.base_url = ( VLLM_EXTERNAL_BASE_URL.rstrip("/") if VLLM_EXTERNAL_BASE_URL else f"http://127.0.0.1:{port}/v1" ) self.api_key = "sk-local" self.started_server = not bool(VLLM_EXTERNAL_BASE_URL) self.server_process: subprocess.Popen | None = None if self.started_server: self.server_process = self._start_server() client_timeout: float | None = None if self.cfg.session_timeout > 0: client_timeout = float(self.cfg.session_timeout) self.client = OpenAI( base_url=self.base_url, api_key=self.api_key, timeout=client_timeout, ) self._wait_for_server() self._maybe_autodetect_served_model() self._initialize_kernels() self.python_tool = { "type": "function", "function": { "name": "python", "description": self.cfg.tool_prompt, "parameters": { "type": "object", "properties": { "code": { "type": "string", "description": "Python code to execute", } }, "required": ["code"], "additionalProperties": False, }, }, } def _start_server(self) -> subprocess.Popen: env = os.environ.copy() env["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" env.setdefault("PYTHONPATH", "/home/ubuntu/aimo/vllm") env.setdefault("TRANSFORMERS_NO_TF", "1") env.setdefault("TRANSFORMERS_NO_FLAX", "1") env.setdefault("USE_TF", "0") env.setdefault("USE_FLAX", "0") cmd = [ sys.executable, "-m", "vllm.entrypoints.openai.api_server", "--seed", str(self.cfg.seed), "--model", self.cfg.model_path, "--served-model-name", self.cfg.served_model_name, "--tensor-parallel-size", str(VLLM_TENSOR_PARALLEL_SIZE), "--disable-custom-all-reduce", "--max-num-seqs", str(VLLM_MAX_NUM_SEQS), "--gpu-memory-utilization", str(self.cfg.gpu_memory_utilization), "--host", "0.0.0.0", "--port", str(self.port), "--dtype", self.cfg.dtype, "--max-model-len", str(self.cfg.context_tokens), "--enable-prefix-caching", "--trust-remote-code", ] if VLLM_ASYNC_SCHEDULING == "1": cmd.append("--async-scheduling") if VLLM_KV_CACHE_DTYPE: cmd.extend(["--kv-cache-dtype", VLLM_KV_CACHE_DTYPE]) if VLLM_LOAD_FORMAT: cmd.extend(["--load-format", VLLM_LOAD_FORMAT]) if VLLM_ENABLE_AUTO_TOOL_CHOICE == "1": cmd.append("--enable-auto-tool-choice") if VLLM_TOOL_CALL_PARSER: cmd.extend(["--tool-call-parser", VLLM_TOOL_CALL_PARSER]) if VLLM_REASONING_PARSER: cmd.extend(["--reasoning-parser", VLLM_REASONING_PARSER]) if VLLM_CHAT_TEMPLATE: cmd.extend(["--chat-template", VLLM_CHAT_TEMPLATE]) if VLLM_TOKENIZER: cmd.extend(["--tokenizer", VLLM_TOKENIZER]) if VLLM_HF_CONFIG_PATH: cmd.extend(["--hf-config-path", VLLM_HF_CONFIG_PATH]) Path(VLLM_SERVER_LOG).parent.mkdir(parents=True, exist_ok=True) self.log_file = open(VLLM_SERVER_LOG, "w", encoding="utf-8") log.info("Launching vLLM server:") log.info(" ".join(cmd)) return subprocess.Popen( cmd, env=env, stdout=self.log_file, stderr=subprocess.STDOUT, start_new_session=True, ) def _wait_for_server(self) -> None: log.info("Waiting for vLLM server...") start = time.time() for _ in range(self.cfg.server_timeout): if self.started_server and self.server_process is not None: rc = self.server_process.poll() if rc is not None: self.log_file.flush() with open(VLLM_SERVER_LOG, "r", encoding="utf-8") as f: logs = f.read() raise RuntimeError(f"Server died with code {rc}. Full logs:\n{logs}\n") try: self.client.models.list() elapsed = time.time() - start log.info(f"Server is ready (took {elapsed:.2f}s)") return except Exception: time.sleep(1) raise RuntimeError("Server failed to start (timeout).") def _maybe_autodetect_served_model(self) -> None: """Avoid 404s when external server model-id differs from local default.""" try: listed = self.client.models.list() ids = [m.id for m in getattr(listed, "data", []) if getattr(m, "id", None)] if not ids: return if self.cfg.served_model_name in ids: return picked = ids[0] log.warning( "Configured model id '%s' is not served by endpoint; switching to '%s' (available=%s)", self.cfg.served_model_name, picked, ids, ) object.__setattr__(self.cfg, "served_model_name", picked) except Exception as exc: log.warning("Unable to auto-detect served model id: %s", exc) def _initialize_kernels(self) -> None: pool_size = self.cfg.sandbox_pool_size if pool_size <= 0: pool_size = max(self.cfg.workers, self.cfg.attempts * self.cfg.question_parallel) log.info(f"Initializing {pool_size} sandboxes...") self.sandbox_pool: queue.Queue[AIMO3Sandbox] = queue.Queue() for _ in range(pool_size): self.sandbox_pool.put(AIMO3Sandbox(timeout=self.cfg.execution_timeout)) log.info("Sandboxes initialized") @staticmethod def _scan_for_answer(text: str) -> Any | None: # Extract the last simple boxed expression and normalize downstream. pattern = r"\\boxed\s*\{\s*([^{}]+?)\s*\}" matches = re.findall(pattern, text) if not matches: return None candidate = matches[-1].strip() if re.fullmatch(r"[+-]?\d[\d,]*", candidate): try: return int(candidate.replace(",", "")) except ValueError: pass return candidate @staticmethod def _ensure_last_print(code: str) -> str: lines = code.strip().split("\n") if not lines: return code last_line = lines[-1].strip() if not last_line: return code if last_line.startswith("#"): return code if "print(" in last_line or last_line.startswith("import ") or last_line.startswith("from "): return code lines[-1] = f"print({last_line})" return "\n".join(lines) @staticmethod def _extract_text_parts(raw: Any) -> str: if raw is None: return "" if isinstance(raw, str): return raw if isinstance(raw, list): parts: list[str] = [] for item in raw: if isinstance(item, str): if item: parts.append(item) continue if isinstance(item, dict): text = item.get("text") or item.get("content") or "" if isinstance(text, str) and text: parts.append(text) continue text = getattr(item, "text", None) or getattr(item, "content", None) if isinstance(text, str) and text: parts.append(text) return "\n".join(parts).strip() if isinstance(raw, dict): text = raw.get("text") or raw.get("content") or "" return text if isinstance(text, str) else "" return str(raw) def _extract_message_text(self, msg: Any) -> tuple[str, str]: content = self._extract_text_parts(getattr(msg, "content", None)) reasoning = self._extract_text_parts(getattr(msg, "reasoning_content", None)) if not reasoning: for attr in ("reasoning", "thinking", "analysis"): val = getattr(msg, attr, None) reasoning = self._extract_text_parts(val) if reasoning: break return content, reasoning @staticmethod def _message_debug_summary(obj: Any) -> str: finish = getattr(obj, "finish_reason", None) message = getattr(obj, "message", obj) tool_calls = getattr(message, "tool_calls", None) try: payload = obj.model_dump(exclude_none=False) except Exception: payload = {} payload_json = json.dumps(payload, ensure_ascii=False, default=str) if len(payload_json) > 1600: payload_json = payload_json[:1600] + "...(truncated)" return ( f"finish_reason={finish} " f"tool_calls_type={type(tool_calls).__name__} " f"payload={payload_json}" ) @staticmethod def _safe_json_loads(raw: Any) -> dict[str, Any]: if raw is None: return {} if isinstance(raw, dict): return raw if isinstance(raw, list): return {} if not isinstance(raw, str): raw = str(raw) raw = raw.strip() if not raw: return {} try: obj = json.loads(raw) if isinstance(obj, dict): return obj return {} except json.JSONDecodeError: pass # Loose fallback for malformed arguments. code_match = re.search(r'"code"\s*:\s*"(.*)"', raw, flags=re.DOTALL) if code_match: code_raw = code_match.group(1) code = code_raw.encode("utf-8").decode("unicode_escape") return {"code": code} return {"code": raw} @staticmethod def _extract_code(args_obj: dict[str, Any]) -> str: for key in ("code", "python", "script", "input"): val = args_obj.get(key) if isinstance(val, str) and val.strip(): return val return "" def _extract_tool_calls_from_content_blocks(self, raw_content: Any) -> list[dict[str, Any]]: if not isinstance(raw_content, list): return [] calls: list[dict[str, Any]] = [] for idx, block in enumerate(raw_content): if isinstance(block, dict): payload = block else: payload = {} for attr in ("type", "id", "name", "arguments", "input", "function"): val = getattr(block, attr, None) if val is not None: payload[attr] = val block_type = str(payload.get("type", "")).lower() fn_name = "" fn_args: Any = None if block_type in {"tool_call", "function_call"}: fn_name = str(payload.get("name") or "") fn_args = payload.get("arguments", None) fn_obj = payload.get("function") if isinstance(fn_obj, dict): fn_name = str(fn_obj.get("name") or fn_name) if fn_args is None: fn_args = fn_obj.get("arguments", None) if not fn_name and isinstance(payload.get("function"), dict): fn_name = str((payload["function"] or {}).get("name") or "") fn_args = (payload["function"] or {}).get("arguments", fn_args) if not fn_name: continue if fn_args is None: fn_args = {} if isinstance(fn_args, str): args_text = fn_args else: try: args_text = json.dumps(fn_args, ensure_ascii=False) except Exception: args_text = str(fn_args) call_id = str(payload.get("id") or f"manual_content_tc_{idx}") calls.append( { "id": call_id, "function": { "name": fn_name, "arguments": args_text, }, } ) return calls @staticmethod def _extract_fallback_tool_code(text: str) -> str | None: if not text: return None code_fence = re.search(r"```python\s*(.*?)```", text, flags=re.DOTALL | re.IGNORECASE) if code_fence: candidate = code_fence.group(1).strip() if candidate: return candidate generic_fence = re.search(r"```\s*(.*?)```", text, flags=re.DOTALL) if generic_fence: candidate = generic_fence.group(1).strip() if candidate: return candidate xml_param = re.search( r"]*>(.*?)", text, flags=re.DOTALL | re.IGNORECASE, ) if xml_param: candidate = xml_param.group(1).replace("", "").strip() if candidate: return candidate function_block = re.search( r"]*>(.*?)", text, flags=re.DOTALL | re.IGNORECASE, ) if function_block: candidate = function_block.group(1).strip() if candidate: return candidate return None @staticmethod def _parse_tool_calls_from_text(content: str) -> list[dict[str, Any]]: if not content: return [] calls: list[dict[str, Any]] = [] call_pattern = re.compile( r"\s*]+)>\s*(.*?)\s*", flags=re.DOTALL, ) param_pattern = re.compile( r"\n]+)>\s*(.*?)\s*", flags=re.DOTALL, ) for idx, match in enumerate(call_pattern.finditer(content)): fn_name = match.group(1).strip() fn_body = match.group(2) args: dict[str, Any] = {} for p_name, p_val in param_pattern.findall(fn_body): key = p_name.strip() val = p_val.strip() if not key: continue args[key] = val calls.append( { "id": f"manual_tc_{idx}", "function": { "name": fn_name, "arguments": json.dumps(args, ensure_ascii=False), }, } ) return calls def _chat_once( self, messages: list[dict[str, Any]], deadline: float | None, seed: int, ): remaining = float("inf") if deadline is not None: remaining = deadline - time.time() if remaining <= 0: raise TimeoutError("Attempt deadline reached before chat request") req_timeout: float | None = None if self.cfg.chat_timeout > 0: req_timeout = max(1.0, min(float(self.cfg.chat_timeout), remaining)) requested_max_tokens = max(1, int(self.cfg.max_tokens)) if os.getenv("CFG_MAX_TOKENS") is None and os.getenv("CFG_MAX_NEW_TOKENS") is not None: requested_max_tokens = max(1, int(self.cfg.max_new_tokens)) if self.cfg.turn_max_tokens > 0: requested_max_tokens = min(requested_max_tokens, int(self.cfg.turn_max_tokens)) last_error: Exception | None = None for _ in range(max(1, self.cfg.max_chat_retries)): kwargs: dict[str, Any] = { "model": self.cfg.served_model_name, "messages": messages, "temperature": self.cfg.temperature, "max_tokens": requested_max_tokens, "seed": seed, "extra_body": {"min_p": self.cfg.min_p}, "tools": [self.python_tool], } if req_timeout is not None: kwargs["timeout"] = req_timeout if VLLM_ENABLE_AUTO_TOOL_CHOICE == "1": kwargs["tool_choice"] = "auto" else: kwargs["tool_choice"] = "none" try: return self.client.chat.completions.create(**kwargs) except Exception as exc: last_error = exc msg = str(exc) msg_l = msg.lower() maybe_context_400 = ( ("400" in msg or "badrequest" in type(exc).__name__.lower()) and any( token in msg_l for token in ("max_tokens", "max token", "context", "sequence length", "too many tokens") ) ) if maybe_context_400 and requested_max_tokens > 1: input_tokens = None match = re.search(r"request has\\s+(\\d+)\\s+input tokens", msg, flags=re.IGNORECASE) if match: try: input_tokens = int(match.group(1)) except Exception: input_tokens = None if input_tokens is not None: reduced = max(1, min(int(self.cfg.max_tokens), int(self.cfg.context_tokens) - input_tokens)) else: reduced = max(1, int(requested_max_tokens * 0.7)) if reduced >= requested_max_tokens: reduced = requested_max_tokens - 1 log.warning( "Reducing max_tokens from %s to %s after request error: %s", requested_max_tokens, reduced, msg[:220], ) requested_max_tokens = reduced continue raise assert last_error is not None raise last_error def _process_attempt( self, problem: str, system_prompt: str, attempt_index: int, stop_event: threading.Event, deadline: float | None, ) -> dict[str, Any]: if stop_event.is_set() or (deadline is not None and time.time() > deadline): return { "Attempt": attempt_index + 1, "Answer": None, "Python Calls": 0, "Python Errors": 0, "Response Length": 0, "Generation": "", } sandbox = None python_calls = 0 python_errors = 0 total_chars = 0 final_answer = None generation_chunks: list[str] = [] empty_turns = 0 attempt_seed = int(math.pow(self.cfg.seed + attempt_index, 2)) messages: list[dict[str, Any]] = [] if self.cfg.use_system_prompt and system_prompt: messages.append({"role": "system", "content": system_prompt}) messages.append({"role": "user", "content": problem}) try: if self.cfg.sandbox_timeout > 0: sandbox = self.sandbox_pool.get(timeout=self.cfg.sandbox_timeout) else: sandbox = self.sandbox_pool.get() for turn in range(self.cfg.turns): if stop_event.is_set() or (deadline is not None and time.time() > deadline): break resp = self._chat_once( messages=messages, deadline=deadline, seed=attempt_seed + turn, ) choice = resp.choices[0] msg = choice.message content, reasoning_content = self._extract_message_text(msg) if content: generation_chunks.append(content) total_chars += len(content) if reasoning_content: generation_chunks.append(f"\n[reasoning]\n{reasoning_content}") structured_tool_calls = list(msg.tool_calls or []) tool_calls: list[Any] = structured_tool_calls manual_tool_calls = [] if not tool_calls: parsed_blocks = self._extract_tool_calls_from_content_blocks(getattr(msg, "content", None)) if parsed_blocks: manual_tool_calls = parsed_blocks tool_calls = manual_tool_calls if not tool_calls: parse_sources = [] if content: parse_sources.append(content) if reasoning_content: parse_sources.append(reasoning_content) for src in parse_sources: parsed = self._parse_tool_calls_from_text(src) if parsed: manual_tool_calls = parsed tool_calls = manual_tool_calls break if tool_calls: empty_turns = 0 if structured_tool_calls: assistant_tool_calls = [] for tc in structured_tool_calls: assistant_tool_calls.append( { "id": tc.id, "type": "function", "function": { "name": tc.function.name, "arguments": tc.function.arguments or "{}", }, } ) messages.append( { "role": "assistant", "content": content or "", "tool_calls": assistant_tool_calls, } ) else: # For manual XML tool calls, keep whichever text contained the call. messages.append({"role": "assistant", "content": content or reasoning_content or ""}) for tc in tool_calls: if structured_tool_calls: fn_name = tc.function.name raw_args = tc.function.arguments or "{}" tool_call_id = tc.id else: fn_name = tc["function"]["name"] raw_args = tc["function"]["arguments"] or "{}" tool_call_id = tc["id"] args_obj = self._safe_json_loads(raw_args) if fn_name != "python": python_errors += 1 tool_output = f"[ERROR] Unsupported tool '{fn_name}'. Use only 'python'." else: code = self._extract_code(args_obj) code = self._ensure_last_print(code) python_calls += 1 exec_timeout: float | None = self.cfg.execution_timeout if exec_timeout <= 0: exec_timeout = None tool_output = sandbox.execute(code, timeout=exec_timeout) if ( tool_output.startswith("[ERROR]") or "Traceback" in tool_output or "Error:" in tool_output ): python_errors += 1 messages.append( { "role": "tool", "tool_call_id": tool_call_id, "name": "python", "content": str(tool_output), } ) continue ran_fallback_tool = False if self.cfg.allow_fallback_tool_code: fallback_code = self._extract_fallback_tool_code(content or reasoning_content or "") if fallback_code: if content or reasoning_content: messages.append({"role": "assistant", "content": content or reasoning_content or ""}) python_calls += 1 exec_timeout: float | None = self.cfg.execution_timeout if exec_timeout <= 0: exec_timeout = None tool_output = sandbox.execute(self._ensure_last_print(fallback_code), timeout=exec_timeout) if ( tool_output.startswith("[ERROR]") or "Traceback" in tool_output or "Error:" in tool_output ): python_errors += 1 messages.append({"role": "user", "content": f"Python output:\n{tool_output}"}) generation_chunks.append("\n[fallback-python]") ran_fallback_tool = True if ran_fallback_tool: continue # If assistant returned no tool calls and fallback did not fire, stop this attempt. if content or reasoning_content: messages.append({"role": "assistant", "content": content or reasoning_content or ""}) else: debug_summary = self._message_debug_summary(choice) generation_chunks.append(f"\n[empty-response] {debug_summary}") final_answer = self._scan_for_answer(content) if final_answer is None and reasoning_content: final_answer = self._scan_for_answer(reasoning_content) if final_answer is not None: break finish_reason = getattr(choice, "finish_reason", None) if self.cfg.continue_after_length and finish_reason == "length": messages.append( { "role": "user", "content": "Continue from where you stopped. End with only the final answer in \\boxed{}.", } ) generation_chunks.append("\n[continue-after-length]") continue generation_chunks.append("\n[no-tool-turn-stop]") break if final_answer is None: final_answer = self._scan_for_answer("\n".join(generation_chunks)) except Exception as exc: import traceback python_errors += 1 tb = traceback.format_exc(limit=8) generation_chunks.append(f"\n[attempt-error] {type(exc).__name__}: {exc}\n{tb}") finally: if sandbox is not None: sandbox.reset() self.sandbox_pool.put(sandbox) return { "Attempt": attempt_index + 1, "Response Length": total_chars, "Python Calls": python_calls, "Python Errors": python_errors, "Answer": final_answer, "Generation": "".join(generation_chunks), } @staticmethod def _select_answer(detailed_results: list[dict[str, Any]]) -> Any: stats = defaultdict(lambda: {"votes": 0, "calls": 0}) for result in detailed_results: ans = result.get("Answer") if ans is not None: stats[ans]["votes"] += 1 stats[ans]["calls"] += result.get("Python Calls", 0) sorted_stats = sorted( stats.items(), key=lambda item: (item[1]["votes"], item[1]["calls"]), reverse=True, ) rows = [(a, d["votes"], d["calls"]) for a, d in sorted_stats] if rows: vote_df = pd.DataFrame(rows, columns=["Answer", "Votes", "Calls"]) log.info("\n" + vote_df.to_string()) final_answer = sorted_stats[0][0] final_votes = sorted_stats[0][1]["votes"] final_calls = sorted_stats[0][1]["calls"] log.info(f"Final Result: {final_answer} | Votes: {final_votes} | Calls: {final_calls}") return final_answer @staticmethod def _select_answer_no_majority(detailed_results: list[dict[str, Any]]) -> Any: ordered_results = sorted( detailed_results, key=lambda row: int(row.get("Attempt", 10**9)), ) for row in ordered_results: answer = row.get("Answer") if answer is not None: calls = row.get("Python Calls", 0) log.info(f"Final Result: {answer} | Votes: 1 | Calls: {calls} | Strategy: first-valid-attempt") return answer raise ValueError("No valid answer found for non-majority selection.") def solve_problem(self, problem: str) -> tuple[Any, str, list[dict[str, Any]]]: problem_start = time.time() log.info(f"Problem: {problem[:200]}...") user_input = str(problem).strip() if self.cfg.append_preference_prompt: user_input = f"{user_input} {self.cfg.preference_prompt}".strip() budget: float | None = None if self.cfg.high_problem_timeout > 0: budget = float(self.cfg.high_problem_timeout) elif self.cfg.base_problem_timeout > 0: budget = float(self.cfg.base_problem_timeout) deadline = (time.time() + budget) if budget is not None else None if deadline is not None: log.info(f"Budget: {budget:.2f}s | Deadline: {deadline:.2f}") else: log.info("Budget: unlimited (timeouts disabled)") tasks = [(self.cfg.system_prompt, idx) for idx in range(self.cfg.attempts)] detailed_results: list[dict[str, Any]] = [] valid_answers: list[int] = [] early_stop_enabled = ( (not self.cfg.disable_majority_early_stop) and (1 <= self.cfg.early_stop <= self.cfg.attempts) ) stop_event = threading.Event() executor = ThreadPoolExecutor(max_workers=max(1, min(self.cfg.workers, self.cfg.attempts))) try: futures = [] for system_prompt, attempt_index in tasks: futures.append( executor.submit( self._process_attempt, user_input, system_prompt, attempt_index, stop_event, deadline, ) ) for future in as_completed(futures): try: result = future.result() detailed_results.append(result) ans = result.get("Answer") if ans is not None: valid_answers.append(ans) counts = Counter(valid_answers).most_common(1) if early_stop_enabled and counts and counts[0][1] >= self.cfg.early_stop: stop_event.set() for f in futures: f.cancel() break except Exception as exc: log.warning(f"Future failed: {exc}") finally: executor.shutdown(wait=False, cancel_futures=True) detailed_results.sort(key=lambda x: int(x.get("Attempt", 0))) used = time.time() - problem_start if budget is not None: saved = max(0.0, budget - used) log.info(f"[Budget]: {budget:.2f}s") log.info(f"[Saved time]: {saved:.2f}s") else: log.info("[Budget]: unlimited") log.info(f"[Inference] Took {used:.2f}s") if detailed_results: res_df = pd.DataFrame(detailed_results) if "Answer" in res_df.columns: res_df["Answer"] = res_df["Answer"].astype("Int64") log.info("\n" + res_df.to_string()) if not valid_answers: log.info("Result: 0") fallback = detailed_results[0].get("Generation", "") if detailed_results else "" return 0, str(fallback), detailed_results if self.cfg.disable_majority_vote: final_answer = self._select_answer_no_majority(detailed_results) else: final_answer = self._select_answer(detailed_results) generation_candidates = [ str(r.get("Generation", "")) for r in detailed_results if r.get("Answer") == final_answer ] final_generation = max(generation_candidates, key=len) if generation_candidates else "" return final_answer, final_generation, detailed_results def close(self) -> None: if self.started_server and hasattr(self, "server_process") and self.server_process is not None: try: pgid = os.getpgid(self.server_process.pid) os.killpg(pgid, signal.SIGTERM) except Exception: try: self.server_process.terminate() except Exception: pass try: self.server_process.wait(timeout=30) except Exception: pass if self.started_server and hasattr(self, "log_file") and self.log_file is not None: try: self.log_file.close() except Exception: pass if hasattr(self, "sandbox_pool"): while not self.sandbox_pool.empty(): try: sb = self.sandbox_pool.get_nowait() sb.close() except Exception: pass # ------------------------------- # Prediction loop # ------------------------------- solver = StepToolSolver(CFG, port=VLLM_SERVER_PORT) _predict_lock = threading.Lock() predictions: dict[Any, Any] = {} generation_records: dict[Any, dict[str, Any]] = {} correct_count = 0 total_count = 0 def predict(id_: pl.DataFrame, question: pl.DataFrame, answer: Optional[pl.DataFrame] = None) -> pl.DataFrame: global correct_count, total_count, predictions, generation_records question_id = id_.item(0, 0) question_text = question.item(0, 0) log.info("------") log.info(f"ID: {question_id}") log.info(f"Question: {question_text[:200]}...") final_answer, generation_text, attempt_results = solver.solve_problem(question_text) with _predict_lock: predictions[question_id] = final_answer total_count += 1 if question_id in ground_truth: gt = ground_truth[question_id] is_correct = _answers_match(final_answer, gt) if is_correct: correct_count += 1 status = "RIGHT" if is_correct else "WRONG" log.info(f"Answer: {final_answer} | Ground Truth: {gt} | {status}") log.info(f"Running Accuracy: {correct_count}/{total_count} ({100.0 * correct_count / total_count:.1f}%)") else: log.info(f"Answer: {final_answer}") generation_records[question_id] = { "id": question_id, "question": question_text, "answer": final_answer, "generation": generation_text, "attempts": attempt_results, } log.info("------") return pl.DataFrame({"id": question_id, "answer": final_answer}) def _load_reference_csv(path: str) -> pd.DataFrame: frame = pd.read_csv(path) default_question_cols = ("question", "problem", "prompt", "text", "content") has_id_col = (ID_COLUMN in frame.columns) or ("id" in frame.columns) has_question_col = any(col in frame.columns for col in ((QUESTION_COLUMN,) if QUESTION_COLUMN else default_question_cols)) if has_id_col and has_question_col: return frame fallback = pd.read_csv(path, header=None) if fallback.shape[1] < 2: raise RuntimeError(f"CSV must have at least 2 columns (id, question). Found shape={fallback.shape}.") rename_map = {0: "id", 1: "question"} if fallback.shape[1] >= 3: rename_map[2] = "answer" return fallback.rename(columns=rename_map) def _ensure_output_parent(path: str) -> None: parent = Path(path).parent if parent and str(parent) not in ("", "."): parent.mkdir(parents=True, exist_ok=True) def _write_outputs() -> None: with _predict_lock: pred_ids = list(predictions.keys()) pred_vals = list(predictions.values()) gen_vals = list(generation_records.values()) _ensure_output_parent(OUTPUT_CSV) out = pl.DataFrame({"id": pred_ids, "answer": pred_vals}) out.write_csv(OUTPUT_CSV) log.info(f"Wrote {OUTPUT_CSV}") if OUTPUT_GENERATIONS_JSON: _ensure_output_parent(OUTPUT_GENERATIONS_JSON) with open(OUTPUT_GENERATIONS_JSON, "w", encoding="utf-8") as f: json.dump(gen_vals, f, ensure_ascii=False, indent=2) log.info(f"Wrote {OUTPUT_GENERATIONS_JSON}") def _majority_vote(values: list[Any]) -> Any | None: clean = [v for v in values if v is not None] if not clean: return None counts = Counter(clean) return sorted(counts.items(), key=lambda kv: (-kv[1], repr(kv[0])))[0][0] def _log_accuracy_against_reference(df_ref: pd.DataFrame) -> None: if "answer" not in df_ref.columns: return pred = pd.read_csv(OUTPUT_CSV) ref_id_col = ID_COLUMN if ID_COLUMN in df_ref.columns else "id" pred_id_col = ref_id_col if ref_id_col in pred.columns else "id" if pred_id_col not in pred.columns: raise KeyError(f"Predictions missing id column: {list(pred.columns)}") pred_by_id = dict(zip(pred[pred_id_col].astype(str), pred["answer"])) correct = 0 total = 0 missing = 0 maj_correct = 0 best_correct = 0 rollout_correct_total = 0 rollout_total = 0 rows_summary: list[dict[str, Any]] = [] for _, row in df_ref.iterrows(): rid = str(row[ref_id_col]) gt = row["answer"] got = pred_by_id.get(rid) if got is None: missing += 1 else: if _answers_match(got, gt): correct += 1 total += 1 record = generation_records.get(rid) attempts_payload = list(record.get("attempts", [])) if isinstance(record, dict) else [] attempt_answers = [item.get("Answer") for item in attempts_payload if isinstance(item, dict)] if not attempt_answers: rows_summary.append( { "id": rid, "majority_pred": None, "majority_correct": False, "best_correct": False, "rollout_correct": 0, "rollout_total": 0, } ) continue correct_flags = [_answers_match(ans, gt) for ans in attempt_answers] rollout_correct = sum(1 for ok in correct_flags if ok) rollout_n = len(attempt_answers) rollout_correct_total += rollout_correct rollout_total += rollout_n maj_pred = _majority_vote(attempt_answers) maj_ok = _answers_match(maj_pred, gt) best_ok = rollout_correct > 0 if maj_ok: maj_correct += 1 if best_ok: best_correct += 1 rows_summary.append( { "id": rid, "majority_pred": maj_pred, "majority_correct": maj_ok, "best_correct": best_ok, "rollout_correct": rollout_correct, "rollout_total": rollout_n, } ) acc = correct / total if total else 0.0 maj_at_k = maj_correct / total if total else 0.0 best_at_k = best_correct / total if total else 0.0 avg_rollout_acc = rollout_correct_total / rollout_total if rollout_total else 0.0 log.info( "Final Accuracy: %s/%s = %.2f%% (missing=%s)", correct, total, 100.0 * acc, missing, ) log.info( "maj@%s: %s/%s = %.4f%% | best@%s: %s/%s = %.4f%% | avg@%s: %s/%s = %.4f%%", CFG.attempts, maj_correct, total, 100.0 * maj_at_k, CFG.attempts, best_correct, total, 100.0 * best_at_k, CFG.attempts, rollout_correct_total, rollout_total, 100.0 * avg_rollout_acc, ) metrics_path = OUTPUT_METRICS_JSON if not metrics_path: metrics_path = str(Path(OUTPUT_CSV).with_suffix(".metrics.json")) _ensure_output_parent(metrics_path) payload = { "reference_csv": REFERENCE_CSV, "output_csv": OUTPUT_CSV, "output_generations_json": OUTPUT_GENERATIONS_JSON, "attempts": CFG.attempts, "total_questions": total, "missing_predictions": missing, "accuracy": { "correct": correct, "total": total, "pct": round(100.0 * acc, 4), }, "maj_at_k": { "correct": maj_correct, "total": total, "pct": round(100.0 * maj_at_k, 4), }, "best_at_k": { "correct": best_correct, "total": total, "pct": round(100.0 * best_at_k, 4), }, "avg_at_k": { "correct": rollout_correct_total, "total": rollout_total, "pct": round(100.0 * avg_rollout_acc, 4), }, "per_question": rows_summary, } with open(metrics_path, "w", encoding="utf-8") as f: json.dump(payload, f, ensure_ascii=False, indent=2) log.info("Wrote %s", metrics_path) def main() -> int: global ground_truth df = _load_reference_csv(REFERENCE_CSV) q_col = QUESTION_COLUMN if not q_col: for c in ("question", "problem", "prompt", "text", "content"): if c in df.columns: q_col = c break if not q_col: raise KeyError( f"CSV has no question column. Found columns: {list(df.columns)}. " "Set QUESTION_COLUMN env var." ) id_col = ID_COLUMN if ID_COLUMN in df.columns else "id" if id_col not in df.columns: raise KeyError(f"CSV has no id column. Found columns: {list(df.columns)}") ground_truth = dict(zip(df[id_col], df["answer"])) if "answer" in df.columns else {} # Keep a reference copy without labels in cwd for compatibility with prior flow. df.drop("answer", axis=1, errors="ignore").to_csv("reference.csv", index=False) def _eval_one(row) -> pl.DataFrame: raw_id = row[id_col] raw_question = row[q_col] if raw_question is None or (hasattr(raw_question, "__len__") and len(str(raw_question).strip()) == 0): log.warning(f"Empty problem text for id={raw_id}; skipping") with _predict_lock: predictions[raw_id] = 0 return pl.DataFrame({"id": [raw_id], "answer": [0]}) id_df = pl.DataFrame({"id": [raw_id]}) q_df = pl.DataFrame({"question": [str(raw_question).strip()]}) return predict(id_df, q_df, None) question_parallel = max(1, CFG.question_parallel) try: if question_parallel == 1: for _, row in df.iterrows(): rid = row[id_col] try: _eval_one(row) except KeyboardInterrupt: raise except Exception as exc: log.warning(f"Problem id={rid} failed: {exc}") with _predict_lock: predictions[rid] = 0 finally: _write_outputs() else: rows = [row for _, row in df.iterrows()] total_rows = len(rows) log.info( "Running question-parallel eval: question_parallel=%s, attempts=%s, workers=%s", question_parallel, CFG.attempts, CFG.workers, ) completed = 0 with ThreadPoolExecutor(max_workers=question_parallel) as eval_executor: future_to_id = { eval_executor.submit(_eval_one, row): row[id_col] for row in rows } for future in as_completed(future_to_id): rid = future_to_id[future] try: future.result() except KeyboardInterrupt: raise except Exception as exc: log.warning(f"Problem id={rid} failed: {exc}") with _predict_lock: predictions[rid] = 0 finally: completed += 1 if (completed % question_parallel == 0) or (completed == total_rows): log.info("Progress: %s/%s questions complete", completed, total_rows) _write_outputs() _write_outputs() _log_accuracy_against_reference(df) return 0 finally: solver.close() if __name__ == "__main__": raise SystemExit(main())