Download code/train/grid_puzzle_plugin.py from AIcell/SPAgent-NonFrozenLake-2K: direct link, hf CLI and curl.
- Browser
- Download file 20.2 kB
-
https://huggingface.co/datasets/AIcell/SPAgent-NonFrozenLake-2K/resolve/main/code/train/grid_puzzle_plugin.py
- Command line
-
hf download hf://datasets/AIcell/SPAgent-NonFrozenLake-2K/code/train/grid_puzzle_plugin.py
-
curl -L -o grid_puzzle_plugin.py https://huggingface.co/datasets/AIcell/SPAgent-NonFrozenLake-2K/resolve/main/code/train/grid_puzzle_plugin.py
20.2 kB
| """SPAgent GRPO plugin for deterministic Sokoban and FifteenPuzzle. | |
| The plugin mirrors the FrozenLake v3 training contract: | |
| - explicit per-turn ``<image>[image: ...]`` placement; | |
| - canonical ``<think>`` plus ``<tool_call>``/``<answer>`` output; | |
| - stateful one-step ``move`` tool execution; | |
| - cumulative image history after valid moves; | |
| - final-answer replay from the initial state; | |
| - per-rollout trajectory logs with reward backfill. | |
| Datasets are built by ``train/build_grid_puzzle_training_data.py``. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import uuid | |
| from datetime import datetime | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Mapping, Optional | |
| REPO_ROOT = Path(__file__).resolve().parents[1] | |
| if str(REPO_ROOT) not in sys.path: | |
| sys.path.insert(0, str(REPO_ROOT)) | |
| from spagent.grid_puzzle_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"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL) | |
| ANSWER_RE = re.compile(r"<answer>(.*?)</answer>", re.DOTALL) | |
| _THINK_INNER = r"(?:(?!</think>|<tool_call>|<answer>).)*" | |
| _TOOL_CALL_TURN_RE = re.compile( | |
| rf"^<think>{_THINK_INNER}</think>\s*<tool_call>.*?</tool_call>(?![\s\S])", | |
| re.DOTALL, | |
| ) | |
| _ANSWER_TURN_RE = re.compile( | |
| rf"^<think>{_THINK_INNER}</think>\s*<answer>.*?</answer>(?![\s\S])", | |
| re.DOTALL, | |
| ) | |
| def _is_canonical_format(completion: str) -> bool: | |
| value = (completion or "").strip() | |
| return ( | |
| _TOOL_CALL_TURN_RE.match(value) is not None | |
| or _ANSWER_TURN_RE.match(value) is not None | |
| ) | |
| def _batch_values(value: Any, count: int) -> List[Any]: | |
| if isinstance(value, list) and len(value) == count: | |
| return value | |
| return [value] * count | |
| class GridPuzzleReward(ORM): | |
| """Reward a final direction sequence that solves the recorded puzzle.""" | |
| 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["grid_puzzle_reward"] = GridPuzzleReward | |
| class GridPuzzleFormatReward(ORM): | |
| """Match the FrozenLake v3 canonical format reward scale.""" | |
| def __call__(self, completions, **kwargs) -> List[float]: | |
| rewards: List[float] = [] | |
| for completion in completions or []: | |
| completion = completion or "" | |
| canonical = _is_canonical_format(completion) | |
| match = ANSWER_RE.search(completion) | |
| valid_actions = bool( | |
| match and parse_action_tokens(match.group(1)) | |
| ) | |
| rewards.append( | |
| 0.3 * float(canonical) + 0.2 * float(valid_actions) | |
| ) | |
| return rewards | |
| orms["grid_puzzle_format"] = GridPuzzleFormatReward | |
| class GridPuzzleScheduler(MultiTurnScheduler): | |
| """Stateful scheduler shared by Sokoban and FifteenPuzzle.""" | |
| 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("GRID_PUZZLE_IMG_DIR", "/tmp/grid_puzzle_rollout") | |
| ) | |
| self.tool_img_dir.mkdir(parents=True, exist_ok=True) | |
| base_traj_dir = os.environ.get("TRAJ_LOG_DIR", "") | |
| if base_traj_dir: | |
| run_id = ( | |
| os.environ.get("RUN_ID") | |
| or datetime.now().strftime("%Y%m%d-%H%M%S") | |
| ) | |
| self._traj_log_dir = os.path.join(base_traj_dir, run_id) | |
| os.makedirs(self._traj_log_dir, exist_ok=True) | |
| logger.info( | |
| f"Grid-puzzle trajectory logging enabled: {self._traj_log_dir}" | |
| ) | |
| else: | |
| self._traj_log_dir = "" | |
| self._traj_step_counter = 0 | |
| self._traj_rank = os.environ.get( | |
| "RANK", os.environ.get("LOCAL_RANK", "0") | |
| ) | |
| self._trajectories: Dict[str, Dict[str, Any]] = {} | |
| 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 "_grid_puzzle" not in data: | |
| task_id = data.get("task_id") | |
| initial_state = data.get("initial_state") | |
| if task_id not in SUPPORTED_TASKS: | |
| raise RuntimeError( | |
| f"GridPuzzleScheduler requires task_id in {SUPPORTED_TASKS}; " | |
| f"got {task_id!r}" | |
| ) | |
| if not initial_state: | |
| raise RuntimeError( | |
| "GridPuzzleScheduler requires the dataset column " | |
| "`initial_state`." | |
| ) | |
| decoded = decode_initial_state(initial_state) | |
| encoded = encode_initial_state(decoded) | |
| data["initial_state"] = encoded | |
| data["_grid_puzzle"] = { | |
| "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["_grid_puzzle"] | |
| def _get_sample_id(self, infer_request: RolloutInferRequest) -> str: | |
| if ( | |
| not hasattr(infer_request, "data_dict") | |
| or infer_request.data_dict is None | |
| ): | |
| infer_request.data_dict = {} | |
| data = infer_request.data_dict | |
| if "rollout_uuid" not in data: | |
| data["rollout_uuid"] = uuid.uuid4().hex[:12] | |
| return data["rollout_uuid"] | |
| def _compute_rewards( | |
| self, | |
| final_response: str, | |
| task_id: Optional[str], | |
| initial_state: Optional[str | Mapping[str, Any]], | |
| ) -> Dict[str, Any]: | |
| output: Dict[str, Any] = { | |
| "format_reward": 0.0, | |
| "outcome_reward": 0.0, | |
| "total_reward": 0.0, | |
| "acc_reward": 0.0, | |
| "extracted_answer": None, | |
| } | |
| canonical = _is_canonical_format(final_response or "") | |
| match = ANSWER_RE.search(final_response or "") | |
| actions: List[str] = [] | |
| if match: | |
| output["extracted_answer"] = match.group(1).strip() | |
| actions = parse_action_tokens(match.group(1)) | |
| output["format_reward"] = ( | |
| 0.3 * float(canonical) + 0.2 * float(bool(actions)) | |
| ) | |
| if ( | |
| task_id in SUPPORTED_TASKS | |
| and initial_state | |
| and actions | |
| and replay_actions(task_id, initial_state, actions) | |
| ): | |
| output["outcome_reward"] = 1.0 | |
| output["acc_reward"] = output["outcome_reward"] | |
| output["total_reward"] = ( | |
| output["format_reward"] + output["outcome_reward"] | |
| ) | |
| return output | |
| def _log_turn( | |
| self, | |
| *, | |
| infer_request: RolloutInferRequest, | |
| model_response: str, | |
| tool_call: Optional[Dict[str, Any]], | |
| tool_result: Optional[Dict[str, Any]], | |
| continuation_prompt: Optional[str], | |
| new_images: List[str], | |
| current_turn: int, | |
| ) -> None: | |
| if not self._traj_log_dir: | |
| return | |
| sample_id = self._get_sample_id(infer_request) | |
| data = infer_request.data_dict or {} | |
| if sample_id not in self._trajectories: | |
| self._trajectories[sample_id] = { | |
| "initial_messages": [ | |
| {"role": message["role"], "content": message["content"]} | |
| for message in (infer_request.messages or []) | |
| if message.get("role") != "assistant" | |
| ], | |
| "initial_images": list(infer_request.images or []), | |
| "turns": [], | |
| } | |
| self._trajectories[sample_id]["turns"].append( | |
| { | |
| "turn": current_turn, | |
| "model_response": model_response, | |
| "tool_call": tool_call, | |
| "tool_result": tool_result, | |
| "continuation_prompt": continuation_prompt, | |
| "new_images": list(new_images), | |
| "full_conversation": list( | |
| data.get("session_messages") or [] | |
| ), | |
| } | |
| ) | |
| def _current_training_step(self) -> int: | |
| try: | |
| from grpo_filtered_trainer import CURRENT_STEP as module_step | |
| except Exception: | |
| module_step = 0 | |
| try: | |
| return int(os.environ.get("SPAGENT_CURRENT_STEP", module_step)) | |
| except ValueError: | |
| return int(module_step or 0) | |
| def _flush_trajectory( | |
| self, | |
| infer_request: RolloutInferRequest, | |
| final_response: str, | |
| current_turn: int, | |
| ) -> None: | |
| if not self._traj_log_dir: | |
| return | |
| sample_id = self._get_sample_id(infer_request) | |
| data = infer_request.data_dict or {} | |
| trajectory = self._trajectories.pop(sample_id, None) | |
| if trajectory is None: | |
| trajectory = { | |
| "initial_messages": [ | |
| {"role": message["role"], "content": message["content"]} | |
| for message in (infer_request.messages or []) | |
| if message.get("role") != "assistant" | |
| ], | |
| "initial_images": list(infer_request.images or []), | |
| "turns": [], | |
| } | |
| session_messages = data.get("session_messages") | |
| if session_messages is not None: | |
| session_messages.append( | |
| {"role": "assistant", "content": final_response} | |
| ) | |
| trajectory["turns"].append( | |
| { | |
| "turn": current_turn, | |
| "model_response": final_response, | |
| "tool_call": None, | |
| "tool_result": None, | |
| "continuation_prompt": None, | |
| "new_images": [], | |
| "is_final": True, | |
| "full_conversation": list(session_messages or []), | |
| } | |
| ) | |
| state = data.get("_grid_puzzle") or {} | |
| rewards = self._compute_rewards( | |
| final_response, | |
| state.get("task_id"), | |
| state.get("initial_state"), | |
| ) | |
| summary = { | |
| "global_step": self._current_training_step(), | |
| "rewards": rewards, | |
| "extracted_answer": rewards["extracted_answer"], | |
| "total_turns": current_turn, | |
| "task_id": state.get("task_id"), | |
| "final_environment": { | |
| "actions": list(state.get("actions") or []), | |
| "done": bool(state.get("done")), | |
| "success": bool(state.get("success")), | |
| "state": state.get("state"), | |
| }, | |
| } | |
| summary.update(trajectory) | |
| step_dir = os.path.join( | |
| self._traj_log_dir, f"step{summary['global_step']}" | |
| ) | |
| try: | |
| os.makedirs(step_dir, exist_ok=True) | |
| except OSError: | |
| step_dir = self._traj_log_dir | |
| self._traj_step_counter += 1 | |
| path = os.path.join( | |
| step_dir, | |
| f"traj_r{self._traj_rank}_{self._traj_step_counter:06d}_" | |
| f"{sample_id}.json", | |
| ) | |
| try: | |
| with open(path, "w", encoding="utf-8") as handle: | |
| json.dump(summary, handle, indent=2, default=str) | |
| except Exception as exc: | |
| logger.warning(f"Failed to write grid-puzzle trajectory: {exc}") | |
| 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 "<answer>" in content and "</answer>" in content: | |
| self._flush_trajectory(infer_request, content, current_turn) | |
| return True | |
| if state.get("done"): | |
| self._flush_trajectory(infer_request, content, current_turn) | |
| return True | |
| finished = super().check_finished( | |
| infer_request, response_choice, current_turn | |
| ) | |
| if finished: | |
| self._flush_trajectory(infer_request, content, current_turn) | |
| return finished | |
| 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] = [] | |
| tool_call: Optional[Dict[str, Any]] = None | |
| tool_result: Optional[Dict[str, Any]] = None | |
| match = TOOL_CALL_RE.search(content) | |
| if not match: | |
| body_text = ( | |
| "No <tool_call> found. Call the move tool with exactly one " | |
| "direction, or finalize with " | |
| "<answer>full direction sequence</answer>." | |
| ) | |
| else: | |
| try: | |
| tool_call = json.loads(match.group(1)) | |
| except json.JSONDecodeError as exc: | |
| tool_call = { | |
| "_raw": match.group(1), | |
| "_parse_error": str(exc), | |
| } | |
| body_text = ( | |
| "Malformed tool JSON. Use exactly:\n" | |
| '<tool_call>{"name": "move", "arguments": ' | |
| '{"direction": "Down"}}</tool_call>' | |
| ) | |
| else: | |
| if not isinstance(tool_call, dict): | |
| tool_result = { | |
| "success": False, | |
| "error": "tool_call_must_be_object", | |
| } | |
| 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": | |
| tool_result = { | |
| "success": False, | |
| "error": f"unknown_tool:{name}", | |
| } | |
| body_text = ( | |
| f"Unknown tool {name!r}. Only `move` is available." | |
| ) | |
| elif not isinstance(arguments, dict): | |
| tool_result = { | |
| "success": False, | |
| "error": "arguments_must_be_object", | |
| } | |
| 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 | |
| ) | |
| tool_result = dict(outcome.tool_result) | |
| 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._get_sample_id(infer_request)}_" | |
| f"t{current_turn:03d}.png" | |
| ) | |
| try: | |
| render_state( | |
| task_id, | |
| rollout_state["state"], | |
| image_path, | |
| ) | |
| new_images.append(str(image_path)) | |
| tool_result["output_path"] = str(image_path) | |
| except Exception as exc: | |
| logger.warning( | |
| f"Grid-puzzle render failed: {exc}" | |
| ) | |
| if rollout_state.get("done"): | |
| body_text += ( | |
| "\n\nThe puzzle is solved. Output the full executed direction " | |
| "sequence as <answer>Direction1 Direction2 ...</answer>." | |
| ) | |
| 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} | |
| ) | |
| self._log_turn( | |
| infer_request=infer_request, | |
| model_response=content, | |
| tool_call=tool_call, | |
| tool_result=tool_result, | |
| continuation_prompt=continuation_prompt, | |
| new_images=new_images, | |
| current_turn=current_turn, | |
| ) | |
| if session_messages is not None: | |
| session_messages.append( | |
| {"role": "user", "content": continuation_prompt} | |
| ) | |
| next_messages = ( | |
| list(session_messages) | |
| if session_messages is not None | |
| else [{"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, | |
| "gp_actions": list(rollout_state["actions"]), | |
| "gp_done": rollout_state["done"], | |
| "gp_success": rollout_state["success"], | |
| "num_turns": current_turn, | |
| }, | |
| } | |
| multi_turns["grid_puzzle_scheduler"] = GridPuzzleScheduler | |