Download server/classification_fields_environment.py from ArnavM10/rl-env-2605.07119-classification-fields: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/spaces/ArnavM10/rl-env-2605.07119-classification-fields/resolve/main/server/classification_fields_environment.py
- Command line
-
hf download hf://spaces/ArnavM10/rl-env-2605.07119-classification-fields/server/classification_fields_environment.py
-
curl -L -o classification_fields_environment.py https://huggingface.co/spaces/ArnavM10/rl-env-2605.07119-classification-fields/resolve/main/server/classification_fields_environment.py
13.8 kB
| # 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 | |
| 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, | |
| } | |
| 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." | |
| ), | |
| } | |
| 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", | |
| }, | |
| } | |
| 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} | |
| 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) | |
| def state(self) -> State: | |
| """Current episode state.""" | |
| return self._state | |