"""SPAgent GRPO plugin for deterministic VRBench navigation. The model-facing interaction contract matches FrozenLake v3: explicit image placement, one-step ``move`` calls, cumulative image anchors, full conversation history, and final-answer replay from the initial state. """ from __future__ import annotations import json import os import re import sys import uuid from pathlib import Path from typing import Any, Dict, List REPO_ROOT = Path(__file__).resolve().parents[1] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) from spagent.vrbench_navigation_protocol import ( # noqa: E402 SUPPORTED_TASKS, clone_state, create_tool_response, decode_initial_state, encode_initial_state, parse_action_tokens, render_state, replay_actions, step_state, ) from swift.llm import RolloutInferRequest # noqa: E402 sys.path.insert(0, str(Path(__file__).resolve().parent)) import grpo_filtered_trainer # noqa: E402,F401 from swift.llm.infer.protocol import ChatCompletionResponseChoice # noqa: E402 from swift.plugin import ORM, orms # noqa: E402 from swift.plugin.multi_turn import MultiTurnScheduler, multi_turns # noqa: E402 from swift.utils import get_logger # noqa: E402 logger = get_logger() TOOL_CALL_RE = re.compile(r"\s*(.*?)\s*", re.DOTALL) ANSWER_RE = re.compile(r"(.*?)", re.DOTALL) _THINK_INNER = r"(?:(?!||).)*" _TOOL_CALL_TURN_RE = re.compile( rf"^{_THINK_INNER}\s*.*?(?![\s\S])", re.DOTALL, ) _ANSWER_TURN_RE = re.compile( rf"^{_THINK_INNER}\s*.*?(?![\s\S])", re.DOTALL, ) def _is_canonical_format(completion: str) -> bool: value = (completion or "").strip() return bool( _TOOL_CALL_TURN_RE.match(value) or _ANSWER_TURN_RE.match(value) ) def _batch_values(value: Any, count: int) -> List[Any]: if isinstance(value, list) and len(value) == count: return value return [value] * count class VRBenchNavigationReward(ORM): """Reward a final direction sequence that reaches the recorded goal.""" def __call__( self, completions, task_id=None, initial_state=None, **kwargs, ) -> List[float]: completions = list(completions or []) tasks = _batch_values(task_id, len(completions)) states = _batch_values(initial_state, len(completions)) rewards: List[float] = [] for completion, task, state in zip(completions, tasks, states): match = ANSWER_RE.search(completion or "") if not match or task not in SUPPORTED_TASKS or not state: rewards.append(0.0) continue actions = parse_action_tokens(match.group(1)) solved = bool(actions) and replay_actions(task, state, actions) rewards.append(1.0 if solved else 0.0) return rewards orms["vrbench_navigation_reward"] = VRBenchNavigationReward class VRBenchNavigationFormatReward(ORM): """Use the same canonical format reward scale as FrozenLake v3.""" def __call__(self, completions, **kwargs) -> List[float]: rewards: List[float] = [] for completion in completions or []: completion = completion or "" match = ANSWER_RE.search(completion) valid_actions = bool( match and parse_action_tokens(match.group(1)) ) rewards.append( 0.3 * float(_is_canonical_format(completion)) + 0.2 * float(valid_actions) ) return rewards orms["vrbench_navigation_format"] = VRBenchNavigationFormatReward class VRBenchNavigationScheduler(MultiTurnScheduler): """FrozenLake-v3-style scheduler for three VRBench grid tasks.""" def __init__(self, max_turns: int = 100, *args, **kwargs): super().__init__(max_turns=max_turns, *args, **kwargs) self.tool_img_dir = Path( os.environ.get( "VRBENCH_NAV_IMG_DIR", "/tmp/vrbench_navigation_rollout", ) ) self.tool_img_dir.mkdir(parents=True, exist_ok=True) def _state(self, infer_request: RolloutInferRequest) -> Dict[str, Any]: if ( not hasattr(infer_request, "data_dict") or infer_request.data_dict is None ): infer_request.data_dict = {} data = infer_request.data_dict if "_vrbench_navigation" not in data: task_id = data.get("task_id") initial_state = data.get("initial_state") if task_id not in SUPPORTED_TASKS: raise RuntimeError( "VRBenchNavigationScheduler requires task_id in " f"{SUPPORTED_TASKS}; got {task_id!r}" ) if not initial_state: raise RuntimeError( "VRBenchNavigationScheduler requires the dataset column " "`initial_state`." ) decoded = decode_initial_state(initial_state) encoded = encode_initial_state(decoded) data["initial_state"] = encoded data["_vrbench_navigation"] = { "task_id": task_id, "initial_state": encoded, "state": clone_state(decoded), "done": False, "success": False, "actions": [], } if "rollout_uuid" not in data: data["rollout_uuid"] = uuid.uuid4().hex[:12] if "session_messages" not in data: data["session_messages"] = [ { "role": message["role"], "content": message["content"], } for message in (infer_request.messages or []) if message.get("role") != "assistant" ] return data["_vrbench_navigation"] @staticmethod def _sample_id(infer_request: RolloutInferRequest) -> str: data = infer_request.data_dict or {} if "rollout_uuid" not in data: data["rollout_uuid"] = uuid.uuid4().hex[:12] infer_request.data_dict = data return data["rollout_uuid"] def check_finished( self, infer_request: RolloutInferRequest, response_choice: ChatCompletionResponseChoice, current_turn: int, ) -> bool: state = self._state(infer_request) content = response_choice.message.content or "" if "" in content and "" in content: return True if state.get("done"): return True return super().check_finished( infer_request, response_choice, current_turn, ) def step( self, infer_request: RolloutInferRequest, response_choice: ChatCompletionResponseChoice, current_turn: int, ) -> Dict[str, Any]: rollout_state = self._state(infer_request) task_id = rollout_state["task_id"] content = response_choice.message.content or "" new_images: List[str] = [] match = TOOL_CALL_RE.search(content) if not match: body_text = ( "No found in your response. Call the move tool " "with one direction, or finalize with " "full action sequence space-separated." ) else: try: tool_call = json.loads(match.group(1)) except json.JSONDecodeError: body_text = ( "Your JSON was malformed. Use exactly:\n" '{"name": "move", "arguments": ' '{"direction": "Down"}}' ) else: if not isinstance(tool_call, dict): body_text = ( "Malformed tool call: the JSON value must be an object." ) else: name = tool_call.get("name") arguments = tool_call.get("arguments") or {} if name != "move": body_text = ( f"Unknown tool {name!r}. Only `move` is available." ) elif not isinstance(arguments, dict): body_text = ( "Malformed move arguments: `arguments` must be " "a JSON object." ) else: direction = arguments.get("direction", "") outcome = step_state( task_id, rollout_state["state"], direction, ) body_text = outcome.body_text if outcome.changed: rollout_state["actions"].append(direction) rollout_state["done"] = outcome.done rollout_state["success"] = outcome.success image_path = self.tool_img_dir / ( f"{self._sample_id(infer_request)}_" f"t{current_turn:03d}.png" ) try: render_state( task_id, rollout_state["state"], image_path, ) except Exception as exc: logger.warning( f"VRBench navigation render failed: {exc}" ) else: new_images.append(str(image_path)) if rollout_state.get("done"): body_text += ( "\n\nThe episode has ended. Output your full executed action " "sequence as Direction1 Direction2 ...." ) all_images = list(infer_request.images or []) + new_images labelled = [ ( "initial state" if index == 0 else f"after step {index}", path, ) for index, path in enumerate(all_images) ] continuation_prompt = create_tool_response(body_text, labelled) data = infer_request.data_dict or {} session_messages = data.get("session_messages") if session_messages is not None: session_messages.append( {"role": "assistant", "content": content} ) session_messages.append( {"role": "user", "content": continuation_prompt} ) next_messages = list(session_messages) else: next_messages = [ {"role": "user", "content": continuation_prompt} ] new_request = RolloutInferRequest( messages=next_messages, images=all_images, audios=getattr(infer_request, "audios", None), videos=getattr(infer_request, "videos", None), tools=getattr(infer_request, "tools", None), objects=getattr(infer_request, "objects", None), data_dict=infer_request.data_dict, ) return { "infer_request": new_request, "rollout_infos": { "task_id": task_id, "navigation_actions": list(rollout_state["actions"]), "navigation_done": rollout_state["done"], "navigation_success": rollout_state["success"], "num_turns": current_turn, }, } multi_turns["vrbench_navigation_scheduler"] = VRBenchNavigationScheduler