|
| 1 | +# Copyright (c) ProrokLab. |
| 2 | +# |
| 3 | +# This source code is licensed under the license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | + |
| 6 | +import pytest |
| 7 | +import torch |
| 8 | + |
| 9 | +from vmas import make_env |
| 10 | + |
| 11 | + |
| 12 | +class TestRoadTraffic: |
| 13 | + def setup_env(self, n_envs, device="cpu", **kwargs) -> None: |
| 14 | + self.env = make_env( |
| 15 | + scenario="road_traffic", |
| 16 | + num_envs=n_envs, |
| 17 | + device=device, |
| 18 | + continuous_actions=True, |
| 19 | + **kwargs, |
| 20 | + ) |
| 21 | + self.env.seed(0) |
| 22 | + |
| 23 | + def _seed_buffer(self, device): |
| 24 | + """Seed initial_state_buffer with a real state and force it to always be used.""" |
| 25 | + scenario = self.env.scenario |
| 26 | + buf = scenario.initial_state_buffer |
| 27 | + buf.add(scenario.state_buffer.get_latest(n=1)[0]) |
| 28 | + buf.probability_use_recording = torch.tensor(1.0, device=device) |
| 29 | + |
| 30 | + @pytest.mark.parametrize("map_type", ["1", "2"]) |
| 31 | + def test_map_type_runs(self, map_type, n_envs=4, n_steps=10): |
| 32 | + self.setup_env(n_envs=n_envs, map_type=map_type) |
| 33 | + self.env.reset() |
| 34 | + for _ in range(n_steps): |
| 35 | + actions = [ |
| 36 | + torch.zeros(n_envs, agent.action.action_size) |
| 37 | + for agent in self.env.agents |
| 38 | + ] |
| 39 | + obs, rews, dones, _ = self.env.step(actions) |
| 40 | + if dones.any(): |
| 41 | + for env_index, done in enumerate(dones): |
| 42 | + if done: |
| 43 | + self.env.reset_at(env_index) |
| 44 | + |
| 45 | + def test_map_type_2_reset_uses_buffer(self, n_envs=4): |
| 46 | + self.setup_env(n_envs=n_envs, map_type="2") |
| 47 | + self.env.reset() |
| 48 | + actions = [ |
| 49 | + torch.zeros(n_envs, agent.action.action_size) |
| 50 | + for agent in self.env.agents |
| 51 | + ] |
| 52 | + self.env.step(actions) |
| 53 | + self._seed_buffer(device="cpu") |
| 54 | + self.env.reset_at(0) |
| 55 | + |
| 56 | + @pytest.mark.skipif( |
| 57 | + not torch.cuda.is_available(), |
| 58 | + reason="GPU required to reproduce road_traffic map_type=2 device bugs", |
| 59 | + ) |
| 60 | + def test_gpu_map_type_2_rand_device(self, n_envs=4): |
| 61 | + self.setup_env(n_envs=n_envs, device="cuda", map_type="2") |
| 62 | + self.env.reset() |
| 63 | + actions = [ |
| 64 | + torch.zeros(n_envs, agent.action.action_size, device="cuda") |
| 65 | + for agent in self.env.agents |
| 66 | + ] |
| 67 | + self.env.step(actions) |
| 68 | + self._seed_buffer(device="cuda") |
| 69 | + self.env.reset_at(0) |
0 commit comments