File size: 13,822 Bytes
ea72eb7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | # Classification Fields Environment for OpenEnv.
#
# An RL environment whose task is to reproduce Table 1 of
# arXiv:2605.07119 "Classification Fields: Arbitrarily Fine Recursive
# Hierarchical Clustering From Few Examples" on CPU in under 15 minutes:
# the nonlinear IFS benchmarks (Sierpinski triangle, Cantor dust, Koch curve),
# comparing the paper's Classification Field Predictor (CFP) against the
# affine residual predictor, ordered MSE averaged over levels 3-5 and 5 seeds.
#
# Reward is deterministic and checkable: partial credit per benchmark cell
# within tolerance of the paper's numbers, full credit only when the verdict
# and all three benchmarks match.
from __future__ import annotations
import inspect
import threading
from typing import Any, Dict, Optional
from uuid import uuid4
try:
# In-repo imports (when running from the OpenEnv repository)
from openenv.core.env_server.mcp_environment import MCPEnvironment
from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation
from openenv.core.env_server.types import Action, Observation, State
except ImportError:
# Standalone imports (when the environment is standalone with openenv from pip)
from openenv.core.env_server.mcp_environment import MCPEnvironment
from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation
from openenv.core.env_server.types import Action, Observation, State
from fastmcp import FastMCP
from .reference_table import (
BENCHMARKS,
CORRECT_VERDICT,
METHODS,
OFFICIAL_COMMIT,
OFFICIAL_REPO,
PAPER_ID,
PAPER_URL,
REFERENCE_CELLS,
VERDICT_OPTIONS,
VERIFIED_REPRO_SPACE,
cell_tolerance,
score_submission,
)
from .runner import RUN_BUDGET_SECONDS, run_official_reproduction
# The Table 1 reproduction run is a multi-minute CPU job; give it the whole
# run budget instead of the 30 s default MCP tool timeout.
LONG_TOOL_TIMEOUT_S = RUN_BUDGET_SECONDS + 60.0
LONG_TOOLS = {"run_reproduction"}
class ClassificationFieldsEnvironment(MCPEnvironment):
"""OpenEnv environment for reproducing Table 1 of arXiv:2605.07119.
Tools exposed to the agent:
- ``get_task``: the full task description and reward rubric.
- ``get_paper_summary``: method context from arXiv:2605.07119.
- ``get_submission_schema``: the exact ``submit_table`` payload format.
- ``run_reproduction``: runs the official repo's nonlinear IFS suite at the
pinned commit on CPU (Sierpinski, Cantor dust, Koch curve; CFP vs affine;
levels 3-5; 5 seeds) and returns the Table 1 cells.
- ``submit_table``: deterministic, checkable scoring of the agent's
reproduced Table 1 (partial credit per cell, full credit only when the
verdict and all three benchmarks match).
"""
SUPPORTS_CONCURRENT_SESSIONS = True
def __init__(self) -> None:
mcp = FastMCP("classification_fields_env")
# Per-episode state. One env instance serves one HTTP session.
self._lock = threading.Lock()
self._run_result: Optional[Dict[str, Any]] = None
self._submitted: bool = False
self._final_reward: Optional[float] = None
@mcp.tool
def get_task() -> dict:
"""Get the task: reproduce Table 1 of arXiv:2605.07119 (Classification Fields, nonlinear IFS benchmarks) and submit it for deterministic scoring."""
return {
"paper": PAPER_ID,
"paper_url": PAPER_URL,
"task": (
"Reproduce Table 1 of arXiv:2605.07119 (Classification Fields): "
"the nonlinear IFS benchmarks. For each of the three benchmarks "
"(Sierpinski triangle, Cantor dust, Koch curve) report the "
"ordered MSE (x 1e-3, mean over evaluation levels 3-5 and over "
"5 seeds) of the paper's Classification Field Predictor (CFP) "
"and of the affine residual predictor, trained on levels 0-2 "
"and rolled out to levels 3-5. Then state the paper's verdict."
),
"reward_rubric": (
"Deterministic and checkable. Each of the 6 benchmark cells "
"(3 benchmarks x {cfp, affine}) earns 0.8/6 of the reward if it "
"is within tolerance of the paper's number "
"(|submitted - paper_mean| <= max(2 * paper_std, 0.20 * paper_mean)). "
"The verdict earns the remaining 0.2. Full credit (1.0) requires "
"the verdict AND all three benchmarks to match. Everything runs "
"on CPU in under 15 minutes per episode."
),
"verdict_options": list(VERDICT_OPTIONS),
"official_repo": OFFICIAL_REPO,
"official_commit": OFFICIAL_COMMIT,
"verified_reproduction_space": VERIFIED_REPRO_SPACE,
}
@mcp.tool
def get_paper_summary() -> dict:
"""Get method context from arXiv:2605.07119 needed to reproduce Table 1."""
return {
"paper": PAPER_ID,
"title": (
"Classification Fields: Arbitrarily Fine Recursive Hierarchical "
"Clustering From Few Examples"
),
"method": (
"A Classification Field Generator (CFG) is a local rule mapping "
"each parent cluster centre to an ordered K-tuple of child "
"residuals: x_{ak} = x_a + s^(|a|+1) * r(x_a)_k. Given only the "
"observed hierarchy prefix (levels 0-2), a Classification Field "
"Predictor (CFP) - a neural network approximating the residual "
"rule r^ - is trained and then rolled out recursively to depths "
"the predictor never saw. The affine residual predictor (a "
"linear map trained with Adam) is the paper's main baseline."
),
"table_1_protocol": (
"Nonlinear IFS benchmarks (Sierpinski triangle, Cantor dust, "
"Koch curve). Train on levels 0-2; evaluate rollout ordered MSE "
"on levels 3, 4, 5; 5 seeds (5000-5004); 2000 epochs per model; "
"metric reported in units of 1e-3."
),
"verdict": (
"The CFP's level-3-5 rollout MSE is >= 10x lower than the "
"affine residual predictor on all three benchmarks "
"(Sierpinski ~18x, Cantor dust ~34x, Koch curve ~13x)."
),
"caveat": (
"An exact least-squares affine baseline diverges from the "
"paper's affine numbers: the paper's affine baseline depends on "
"Adam's implicit bias, not on fit quality. Reproduce with the "
"official pipeline at the pinned commit for the paper's numbers."
),
}
@mcp.tool
def get_submission_schema() -> dict:
"""Get the exact submit_table payload schema for the Table 1 reproduction."""
return {
"tool": "submit_table",
"verdict": list(VERDICT_OPTIONS),
"cells": {
benchmark: {method: "<ordered MSE x 1e-3, mean over levels 3-5 "
"and 5 seeds>" for method in METHODS}
for benchmark in BENCHMARKS
},
"example_correct_shape": {
"verdict": CORRECT_VERDICT,
"cells": {
"sierpinski": {"cfp": 0.90, "affine": 16.46},
"cantor_dust": {"cfp": 0.47, "affine": 16.15},
"koch_curve": {"cfp": 0.71, "affine": 9.13},
},
"note": "values shown are illustrative; run the pipeline for yours",
},
}
@mcp.tool
def run_reproduction() -> dict:
"""Run the official nonlinear IFS suite (Table 1 of arXiv:2605.07119) on CPU at the pinned commit and return the resulting Table 1 cells. Takes several minutes; results are cached for the episode."""
with self._lock:
if self._run_result is not None:
return {
**self._run_result,
"cached": True,
"note": "already ran in this episode; returning cached results",
}
result = run_official_reproduction()
with self._lock:
self._run_result = result
return {**result, "cached": False}
@mcp.tool
def submit_table(verdict: str, cells: dict) -> dict:
"""Submit the reproduced Table 1 of arXiv:2605.07119 for deterministic scoring: verdict plus ordered-MSE cells (x 1e-3) for Sierpinski, Cantor dust and Koch curve, CFP and affine. Ends the episode with a reward in [0, 1]."""
report = score_submission(verdict, cells)
with self._lock:
if self._submitted:
return {
**report,
"reward": self._final_reward,
"already_submitted": True,
}
self._submitted = True
self._final_reward = float(report["reward"])
return report
super().__init__(mcp)
self._state = State(episode_id=str(uuid4()), step_count=0)
# ------------------------------------------------------------------
# OpenEnv Environment interface
# ------------------------------------------------------------------
def reset(
self,
seed: Optional[int] = None,
episode_id: Optional[str] = None,
**kwargs: Any,
) -> Observation:
"""Reset the episode: clears the cached run and any submission."""
with self._lock:
self._run_result = None
self._submitted = False
self._final_reward = None
self._state = State(
episode_id=episode_id or str(uuid4()),
step_count=0,
)
return Observation(
done=False,
reward=0.0,
metadata={
"status": "ready",
"task": (
f"Reproduce Table 1 of {PAPER_ID} (Classification Fields): "
"nonlinear IFS benchmarks, CFP vs affine residual predictor, "
"ordered MSE (x 1e-3) at levels 3-5 over 5 seeds. Partial "
"credit per benchmark cell within tolerance; full credit when "
"the verdict and all three benchmarks match. CPU-only, under "
"15 minutes. Start with the get_task tool."
),
"reward_range": [0.0, 1.0],
},
)
def _step_impl(
self,
action: Action,
timeout_s: Optional[float] = None,
**kwargs: Any,
) -> Observation:
"""Handle non-MCP actions (this env is MCP-only)."""
return Observation(
done=False,
reward=0.0,
metadata={
"error": (
f"Unknown action type: {type(action).__name__}. Use "
"ListToolsAction or CallToolAction for MCP interactions."
)
},
)
def _effective_timeout(
self, action: Action, timeout_s: Optional[float]
) -> Optional[float]:
"""Raise the default MCP tool timeout for the long-running run tool."""
if (
isinstance(action, CallToolAction)
and action.tool_name in LONG_TOOLS
and timeout_s is None
):
return LONG_TOOL_TIMEOUT_S
return timeout_s
def _finalize(self, obs: Observation, action: Action) -> Observation:
"""Attach the deterministic reward to a successful submit_table call."""
if (
isinstance(action, CallToolAction)
and action.tool_name == "submit_table"
and getattr(obs, "error", None) is None
):
data = getattr(obs.result, "data", None)
if isinstance(data, dict) and "reward" in data:
return CallToolObservation(
tool_name=action.tool_name,
result=obs.result,
reward=float(data["reward"]),
done=True,
metadata={
"score_details": data,
"paper": PAPER_ID,
},
)
return obs
def step(
self,
action: Action,
timeout_s: Optional[float] = None,
**kwargs: Any,
) -> Observation:
"""Execute a step; MCP actions are routed by the base class."""
self._state.step_count += 1
obs = super().step(
action, timeout_s=self._effective_timeout(action, timeout_s), **kwargs
)
return self._finalize(obs, action)
async def step_async(
self,
action: Action,
timeout_s: Optional[float] = None,
**kwargs: Any,
) -> Observation:
"""Async step used by the WebSocket handler."""
self._state.step_count += 1
obs = await super().step_async(
action, timeout_s=self._effective_timeout(action, timeout_s), **kwargs
)
return self._finalize(obs, action)
@property
def state(self) -> State:
"""Current episode state."""
return self._state
|