File size: 12,073 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
"""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"<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 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 "<answer>" in content and "</answer>" 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 <tool_call> found in your response. Call the move tool "
                "with one direction, or finalize with "
                "<answer>full action sequence space-separated</answer>."
            )
        else:
            try:
                tool_call = json.loads(match.group(1))
            except json.JSONDecodeError:
                body_text = (
                    "Your <tool_call> JSON was malformed. Use exactly:\n"
                    '<tool_call>{"name": "move", "arguments": '
                    '{"direction": "Down"}}</tool_call>'
                )
            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 <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}
            )
            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