|
| 1 | +import pytest |
| 2 | +from unittest import mock |
| 3 | + |
| 4 | +import torch # noqa I201 |
| 5 | + |
| 6 | +from mlagents.torch_utils import set_torch_config, default_device |
| 7 | +from mlagents.trainers.settings import TorchSettings |
| 8 | + |
| 9 | + |
| 10 | +@pytest.mark.parametrize( |
| 11 | + "device_str, expected_type, expected_index, expected_tensor_type", |
| 12 | + [ |
| 13 | + ("cpu", "cpu", None, torch.FloatTensor), |
| 14 | + ("cuda", "cuda", None, torch.cuda.FloatTensor), |
| 15 | + ("cuda:42", "cuda", 42, torch.cuda.FloatTensor), |
| 16 | + ("opengl", "opengl", None, torch.FloatTensor), |
| 17 | + ], |
| 18 | +) |
| 19 | +@mock.patch.object(torch, "set_default_tensor_type") |
| 20 | +def test_set_torch_device( |
| 21 | + mock_set_default_tensor_type, |
| 22 | + device_str, |
| 23 | + expected_type, |
| 24 | + expected_index, |
| 25 | + expected_tensor_type, |
| 26 | +): |
| 27 | + try: |
| 28 | + torch_settings = TorchSettings(device=device_str) |
| 29 | + set_torch_config(torch_settings) |
| 30 | + assert default_device().type == expected_type |
| 31 | + if expected_index is None: |
| 32 | + assert default_device().index is None |
| 33 | + else: |
| 34 | + assert default_device().index == expected_index |
| 35 | + mock_set_default_tensor_type.assert_called_once_with(expected_tensor_type) |
| 36 | + except Exception: |
| 37 | + raise |
| 38 | + finally: |
| 39 | + # restore the defaults |
| 40 | + torch_settings = TorchSettings(device=None) |
| 41 | + set_torch_config(torch_settings) |
0 commit comments