-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[RLlib] Fix convert to torch tensor (#31023)
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
- Loading branch information
1 parent
76b22f4
commit 8e9fa22
Showing
3 changed files
with
53 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import unittest | ||
|
||
import numpy as np | ||
import torch.cuda | ||
|
||
import ray | ||
from ray.rllib.utils.torch_utils import convert_to_torch_tensor | ||
|
||
|
||
class TestTorchUtils(unittest.TestCase): | ||
@classmethod | ||
def setUpClass(cls) -> None: | ||
ray.init() | ||
|
||
@classmethod | ||
def tearDownClass(cls) -> None: | ||
ray.shutdown() | ||
|
||
def test_convert_to_torch_tensor(self): | ||
# Tests whether convert_to_torch_tensor works as expected | ||
|
||
# Test single array | ||
array = np.array([1, 2, 3]) | ||
tensor = torch.from_numpy(array) | ||
self.assertTrue(all(convert_to_torch_tensor(array) == tensor)) | ||
|
||
# Test torch tensor | ||
self.assertTrue(convert_to_torch_tensor(tensor) is tensor) | ||
|
||
# Test conversion to 32-bit float | ||
tensor_2 = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float64) | ||
self.assertTrue(convert_to_torch_tensor(tensor_2).dtype is torch.float32) | ||
|
||
# Test nested structure with objects tested above | ||
converted = convert_to_torch_tensor({"a": (array, tensor), "b": tensor_2}) | ||
self.assertTrue(all(convert_to_torch_tensor(converted["a"][0]) == tensor)) | ||
self.assertTrue(convert_to_torch_tensor(converted["a"][1]) is tensor) | ||
self.assertTrue(convert_to_torch_tensor(converted["b"]).dtype is torch.float32) | ||
|
||
|
||
if __name__ == "__main__": | ||
import pytest | ||
import sys | ||
|
||
sys.exit(pytest.main(["-v", __file__])) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters