File size: 8,552 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 | #!/usr/bin/env python3
"""Dependency-light tests for VRBench SPAgent training environments."""
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.vrbench_navigation_protocol import ( # noqa: E402
EMPTY,
GOAL,
MAZE_TASK,
PATHFINDER_TASK,
TRAP,
TRAPFIELD_SOLVABLE_SEEDS,
TRAPFIELD_TASK,
WALL,
build_system_prompt,
build_user_prompt,
canonical_state,
encode_initial_state,
render_state,
replay_actions,
shortest_path,
state_text,
step_state,
)
_builder_spec = importlib.util.spec_from_file_location(
"build_vrbench_navigation_training_data",
ROOT / "train" / "build_vrbench_navigation_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_state() -> dict:
return canonical_state(
grid=[
[WALL, WALL, WALL, WALL, WALL],
[WALL, EMPTY, EMPTY, EMPTY, WALL],
[WALL, WALL, WALL, EMPTY, WALL],
[WALL, EMPTY, EMPTY, GOAL, WALL],
[WALL, WALL, WALL, WALL, WALL],
],
start=(1, 1),
goal=(3, 3),
)
def trap_state() -> dict:
return canonical_state(
grid=[
[WALL, WALL, WALL, WALL, WALL],
[WALL, EMPTY, TRAP, EMPTY, WALL],
[WALL, EMPTY, EMPTY, EMPTY, WALL],
[WALL, EMPTY, EMPTY, GOAL, WALL],
[WALL, WALL, WALL, WALL, WALL],
],
start=(1, 1),
goal=(3, 3),
)
def test_protocol_and_replay() -> None:
state = simple_state()
solution = ["Right", "Right", "Down", "Down"]
assert shortest_path(state) == solution
assert replay_actions(MAZE_TASK, encode_initial_state(state), solution)
assert not replay_actions(
MAZE_TASK,
encode_initial_state(state),
["Down"],
)
def test_blocked_wall_and_trap() -> None:
state = simple_state()
wall = step_state(PATHFINDER_TASK, state, "Down")
assert not wall.changed
assert wall.tool_result["error"] == "wall"
trapped = step_state(TRAPFIELD_TASK, trap_state(), "Right")
assert not trapped.changed
assert trapped.tool_result["error"] == "trap"
def test_text_render_and_prompt(tmp: Path) -> None:
state = simple_state()
image_path = tmp / "maze.png"
render_state(MAZE_TASK, state, image_path)
assert state_text(state, initial=True).splitlines()[1] == "#SFF#"
prompt = build_user_prompt(MAZE_TASK, state, image_path)
assert count_explicit_images(prompt) == 1
assert "# Initial Grid (text view, 5x5)" in prompt
assert '"name": "move"' in build_system_prompt(MAZE_TASK, state)
with Image.open(image_path) as image:
assert image.mode == "RGB"
assert image.size == (240, 240)
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 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")
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(
"vrbench_navigation_plugin_under_test",
ROOT / "train" / "vrbench_navigation_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(tmp: Path) -> None:
plugin, request_type = load_plugin_with_stubs()
state = simple_state()
encoded = encode_initial_state(state)
solution = "Right Right Down Down"
completion = f"<think>Plan.</think><answer>{solution}</answer>"
assert plugin.VRBenchNavigationReward()(
[completion],
[MAZE_TASK],
[encoded],
) == [1.0]
assert plugin.VRBenchNavigationFormatReward()([completion]) == [0.5]
initial_image = tmp / "initial.png"
render_state(MAZE_TASK, state, initial_image)
old_dir = os.environ.get("VRBENCH_NAV_IMG_DIR")
os.environ["VRBENCH_NAV_IMG_DIR"] = str(tmp / "rollout")
try:
scheduler = plugin.VRBenchNavigationScheduler(max_turns=10)
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": MAZE_TASK,
"initial_state": encoded,
},
)
choice = types.SimpleNamespace(
message=types.SimpleNamespace(
content=(
"<think>Move right.</think>"
'<tool_call>{"name":"move","arguments":'
'{"direction":"Right"}}</tool_call>'
)
)
)
result = scheduler.step(request, choice, 1)
next_request = result["infer_request"]
assert next_request.data_dict["_vrbench_navigation"]["actions"] == [
"Right"
]
assert len(next_request.images) == 2
assert Path(next_request.images[-1]).is_file()
assert count_explicit_images(
next_request.messages[-1]["content"]
) == 1
blocked_choice = types.SimpleNamespace(
message=types.SimpleNamespace(
content=(
"<think>Try down.</think>"
'<tool_call>{"name":"move","arguments":'
'{"direction":"Down"}}</tool_call>'
)
)
)
blocked = scheduler.step(next_request, blocked_choice, 2)
blocked_request = blocked["infer_request"]
assert len(blocked_request.images) == 2
assert count_explicit_images(
blocked_request.messages[-1]["content"]
) == 1
finally:
if old_dir is None:
os.environ.pop("VRBENCH_NAV_IMG_DIR", None)
else:
os.environ["VRBENCH_NAV_IMG_DIR"] = old_dir
def test_trapfield_seed_contract() -> None:
assert len(TRAPFIELD_SOLVABLE_SEEDS) == 30
assert len(set(TRAPFIELD_SOLVABLE_SEEDS)) == 30
def main() -> None:
with tempfile.TemporaryDirectory() as directory:
tmp = Path(directory)
test_protocol_and_replay()
test_blocked_wall_and_trap()
test_text_render_and_prompt(tmp)
test_reward_and_scheduler(tmp)
test_trapfield_seed_contract()
print("VRBench navigation training tests passed")
if __name__ == "__main__":
main()
|