File size: 12,680 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
#!/usr/bin/env python3
"""Dependency-light tests for the SPAgent grid-puzzle training environment."""

from __future__ import annotations

import importlib.util
import os
import sys
import tempfile
import types
from pathlib import Path

from PIL import Image


ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from spagent.frozenlake_v3_protocol import count_explicit_images  # noqa: E402
from spagent.grid_puzzle_protocol import (  # noqa: E402
    FIFTEEN_TASK,
    SOKOBAN_TASK,
    build_system_prompt,
    build_user_prompt,
    canonical_fifteen_state,
    canonical_sokoban_state,
    decode_initial_state,
    encode_initial_state,
    is_solved,
    parse_action_tokens,
    render_state,
    replay_actions,
    state_text,
    step_state,
)

_builder_spec = importlib.util.spec_from_file_location(
    "build_grid_puzzle_training_data",
    ROOT / "train" / "build_grid_puzzle_training_data.py",
)
builder = importlib.util.module_from_spec(_builder_spec)
assert _builder_spec.loader is not None
_builder_spec.loader.exec_module(builder)


def simple_sokoban_state() -> dict:
    return canonical_sokoban_state(
        rows=3,
        cols=5,
        walls={
            (0, 0), (0, 1), (0, 2), (0, 3), (0, 4),
            (1, 0), (1, 4),
            (2, 0), (2, 1), (2, 2), (2, 3), (2, 4),
        },
        goals={(1, 3)},
        boxes={(1, 2)},
        player=(1, 1),
    )


def one_move_fifteen_state() -> dict:
    return canonical_fifteen_state(
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 15]
    )


def test_action_parser() -> None:
    assert parse_action_tokens("left, DOWN; right. up") == [
        "Left", "Down", "Right", "Up"
    ]
    assert parse_action_tokens("junk") == []


def test_state_json_round_trip() -> None:
    state = simple_sokoban_state()
    assert decode_initial_state(encode_initial_state(state)) == state


def test_sokoban_push_and_replay() -> None:
    state = simple_sokoban_state()
    outcome = step_state(SOKOBAN_TASK, state, "Right")
    assert outcome.changed
    assert outcome.success
    assert outcome.done
    assert state["player"] == [1, 2]
    assert state["boxes"] == [[1, 3]]
    assert replay_actions(
        SOKOBAN_TASK, encode_initial_state(simple_sokoban_state()), ["Right"]
    )


def test_sokoban_blocked_push() -> None:
    state = simple_sokoban_state()
    state["goals"] = [[1, 2]]
    state["boxes"] = [[1, 3]]
    state["player"] = [1, 2]
    outcome = step_state(SOKOBAN_TASK, state, "Right")
    assert not outcome.changed
    assert outcome.tool_result["error"] == "blocked_box"


def test_fifteen_direction_matches_upstream() -> None:
    state = one_move_fifteen_state()
    outcome = step_state(FIFTEEN_TASK, state, "Left")
    assert outcome.changed
    assert outcome.success
    assert state["board"] == list(range(1, 16)) + [0]
    assert replay_actions(
        FIFTEEN_TASK,
        encode_initial_state(one_move_fifteen_state()),
        ["Left"],
    )


def test_fifteen_invalid_slide() -> None:
    solved = canonical_fifteen_state(list(range(1, 16)) + [0])
    outcome = step_state(FIFTEEN_TASK, solved, "Left")
    assert not outcome.changed
    assert outcome.tool_result["error"] == "invalid_slide"
    assert is_solved(FIFTEEN_TASK, solved)


def test_invalid_direction_type() -> None:
    state = one_move_fifteen_state()
    outcome = step_state(FIFTEEN_TASK, state, ["Left"])
    assert not outcome.changed
    assert outcome.tool_result["error"] == "invalid_direction"
    assert not replay_actions(
        FIFTEEN_TASK,
        encode_initial_state(state),
        [["Left"]],
    )


def test_fifteen_solvability_filter() -> None:
    solved = list(range(1, 16)) + [0]
    unsolvable = solved.copy()
    unsolvable[0], unsolvable[1] = unsolvable[1], unsolvable[0]
    assert builder.is_fifteen_solvable(solved)
    assert not builder.is_fifteen_solvable(unsolvable)


def test_sokoban_padding_is_deterministic() -> None:
    base = [
        {
            "id": "sokoban_000000",
            "task_id": SOKOBAN_TASK,
            "initial_state": "state-a",
        },
        {
            "id": "sokoban_000001",
            "task_id": SOKOBAN_TASK,
            "initial_state": "state-b",
        },
    ]
    padded = builder.pad_records(base, count=5, seed=0)
    assert len(padded) == 5
    assert len({row["initial_state"] for row in padded}) == 2
    assert [row["id"] for row in padded] == [
        f"sokoban_{index:06d}" for index in range(5)
    ]
    assert all("duplicate_of" in row for row in padded[2:])
    assert builder.pad_records(base, count=5, seed=0) == padded


def test_text_and_prompt_contract(tmp: Path) -> None:
    state = simple_sokoban_state()
    image_path = tmp / "initial.png"
    render_state(SOKOBAN_TASK, state, image_path)
    prompt = build_user_prompt(SOKOBAN_TASK, state, image_path)
    assert "# Initial Grid (text view, 3x5)" in prompt
    assert state_text(SOKOBAN_TASK, state) in prompt
    assert count_explicit_images(prompt) == 1
    assert '"name": "move"' in build_system_prompt(SOKOBAN_TASK)


def test_renderers(tmp: Path) -> None:
    sokoban_path = tmp / "sokoban.png"
    fifteen_path = tmp / "fifteen.png"
    render_state(SOKOBAN_TASK, simple_sokoban_state(), sokoban_path)
    render_state(FIFTEEN_TASK, one_move_fifteen_state(), fifteen_path)
    with Image.open(sokoban_path) as image:
        assert image.mode == "RGB"
        assert image.size == (360, 232)
    with Image.open(fifteen_path) as image:
        assert image.mode == "RGB"
        assert image.size == (360, 360)


def load_plugin_with_stubs():
    class FakeRolloutInferRequest:
        def __init__(self, **kwargs):
            self.__dict__.update(kwargs)

    class FakeScheduler:
        def __init__(self, max_turns=20, *args, **kwargs):
            self.max_turns = max_turns

        def check_finished(self, infer_request, response_choice, current_turn):
            return current_turn >= self.max_turns

    class FakeORM:
        pass

    class FakeLogger:
        def info(self, *args, **kwargs):
            pass

        def warning(self, *args, **kwargs):
            pass

    swift = types.ModuleType("swift")
    swift_llm = types.ModuleType("swift.llm")
    swift_llm.RolloutInferRequest = FakeRolloutInferRequest
    swift_infer = types.ModuleType("swift.llm.infer")
    swift_protocol = types.ModuleType("swift.llm.infer.protocol")
    swift_protocol.ChatCompletionResponseChoice = object
    swift_plugin = types.ModuleType("swift.plugin")
    swift_plugin.ORM = FakeORM
    swift_plugin.orms = {}
    swift_multi = types.ModuleType("swift.plugin.multi_turn")
    swift_multi.MultiTurnScheduler = FakeScheduler
    swift_multi.multi_turns = {}
    swift_utils = types.ModuleType("swift.utils")
    swift_utils.get_logger = lambda: FakeLogger()
    trainer = types.ModuleType("grpo_filtered_trainer")
    trainer.CURRENT_STEP = 0

    modules = {
        "swift": swift,
        "swift.llm": swift_llm,
        "swift.llm.infer": swift_infer,
        "swift.llm.infer.protocol": swift_protocol,
        "swift.plugin": swift_plugin,
        "swift.plugin.multi_turn": swift_multi,
        "swift.utils": swift_utils,
        "grpo_filtered_trainer": trainer,
    }
    previous = {name: sys.modules.get(name) for name in modules}
    sys.modules.update(modules)
    try:
        spec = importlib.util.spec_from_file_location(
            "grid_puzzle_plugin_under_test",
            ROOT / "train" / "grid_puzzle_plugin.py",
        )
        module = importlib.util.module_from_spec(spec)
        assert spec.loader is not None
        spec.loader.exec_module(module)
        return module, FakeRolloutInferRequest
    finally:
        for name, old in previous.items():
            if old is None:
                sys.modules.pop(name, None)
            else:
                sys.modules[name] = old


def test_reward_and_scheduler_step(tmp: Path) -> None:
    plugin, request_type = load_plugin_with_stubs()
    initial = one_move_fifteen_state()
    encoded = encode_initial_state(initial)
    completion = "<think>One move.</think><answer>Left</answer>"
    assert plugin.GridPuzzleReward()(
        [completion], [FIFTEEN_TASK], [encoded]
    ) == [1.0]
    assert plugin.GridPuzzleReward()(
        ["<think>Push.</think><answer>Right</answer>"],
        [SOKOBAN_TASK],
        [encode_initial_state(simple_sokoban_state())],
    ) == [1.0]
    assert plugin.GridPuzzleFormatReward()([completion]) == [0.5]

    initial_image = tmp / "initial_fifteen.png"
    render_state(FIFTEEN_TASK, initial, initial_image)
    old_dir = os.environ.get("GRID_PUZZLE_IMG_DIR")
    os.environ["GRID_PUZZLE_IMG_DIR"] = str(tmp / "rollout")
    try:
        scheduler = plugin.GridPuzzleScheduler(max_turns=5)
        request = request_type(
            messages=[
                {"role": "system", "content": "system"},
                {"role": "user", "content": "user"},
            ],
            images=[str(initial_image)],
            audios=None,
            videos=None,
            tools=None,
            objects=None,
            data_dict={
                "task_id": FIFTEEN_TASK,
                "initial_state": encoded,
            },
        )
        choice = types.SimpleNamespace(
            message=types.SimpleNamespace(
                content=(
                    "<think>Slide 15 left.</think>"
                    '<tool_call>{"name":"move","arguments":'
                    '{"direction":"Left"}}</tool_call>'
                )
            )
        )
        result = scheduler.step(request, choice, 1)
        assert result["rollout_infos"]["gp_success"]
        next_request = result["infer_request"]
        assert len(next_request.images) == 2
        assert Path(next_request.images[-1]).is_file()
        assert "<image>[image:" in next_request.messages[-1]["content"]
        final_choice = types.SimpleNamespace(
            message=types.SimpleNamespace(content=completion)
        )
        assert scheduler.check_finished(next_request, final_choice, 2)

        for malformed_content, expected_phrase in (
            (
                "<think>Bad shape.</think><tool_call>[]</tool_call>",
                "JSON value must be an object",
            ),
            (
                (
                    "<think>Bad arguments.</think>"
                    '<tool_call>{"name":"move","arguments":["Left"]}'
                    "</tool_call>"
                ),
                "`arguments` must be a JSON object",
            ),
        ):
            malformed_request = request_type(
                messages=[
                    {"role": "system", "content": "system"},
                    {"role": "user", "content": "user"},
                ],
                images=[str(initial_image)],
                audios=None,
                videos=None,
                tools=None,
                objects=None,
                data_dict={
                    "task_id": FIFTEEN_TASK,
                    "initial_state": encoded,
                },
            )
            malformed_choice = types.SimpleNamespace(
                message=types.SimpleNamespace(content=malformed_content)
            )
            malformed_result = scheduler.step(
                malformed_request, malformed_choice, 1
            )
            assert len(malformed_result["infer_request"].images) == 1
            assert count_explicit_images(
                malformed_result["infer_request"].messages[-1]["content"]
            ) == 1
            logged_tool_result = malformed_result["rollout_infos"]
            assert not logged_tool_result["gp_success"]
            continuation = malformed_result["infer_request"].messages[-1][
                "content"
            ]
            assert expected_phrase in continuation
    finally:
        if old_dir is None:
            os.environ.pop("GRID_PUZZLE_IMG_DIR", None)
        else:
            os.environ["GRID_PUZZLE_IMG_DIR"] = old_dir


def main() -> None:
    with tempfile.TemporaryDirectory() as directory:
        tmp = Path(directory)
        test_action_parser()
        test_state_json_round_trip()
        test_sokoban_push_and_replay()
        test_sokoban_blocked_push()
        test_fifteen_direction_matches_upstream()
        test_fifteen_invalid_slide()
        test_invalid_direction_type()
        test_fifteen_solvability_filter()
        test_sokoban_padding_is_deterministic()
        test_text_and_prompt_contract(tmp)
        test_renderers(tmp)
        test_reward_and_scheduler_step(tmp)
    print("grid-puzzle training tests passed")


if __name__ == "__main__":
    main()