File size: 20,205 Bytes
7d90172 | 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 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | """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
|