Assert that types and all values of two data objects are close. Args: actual: Pytorch Tensor or numpy array for comparison. desired: Pytorch Tensor or numpy array to compare against. type_test: whether to test that `actual` and `desired` are both numpy arrays or tor
(
actual: NdarrayOrTensor,
desired: NdarrayOrTensor,
type_test: bool | str = True,
device_test: bool = False,
*args,
**kwargs,
)
| 121 | |
| 122 | |
| 123 | def assert_allclose( |
| 124 | actual: NdarrayOrTensor, |
| 125 | desired: NdarrayOrTensor, |
| 126 | type_test: bool | str = True, |
| 127 | device_test: bool = False, |
| 128 | *args, |
| 129 | **kwargs, |
| 130 | ): |
| 131 | """ |
| 132 | Assert that types and all values of two data objects are close. |
| 133 | |
| 134 | Args: |
| 135 | actual: Pytorch Tensor or numpy array for comparison. |
| 136 | desired: Pytorch Tensor or numpy array to compare against. |
| 137 | type_test: whether to test that `actual` and `desired` are both numpy arrays or torch tensors. |
| 138 | if type_test == "tensor", it checks whether the `actual` is a torch.tensor or metatensor according to |
| 139 | `get_track_meta`. |
| 140 | device_test: whether to test the device property. |
| 141 | args: extra arguments to pass on to `np.testing.assert_allclose`. |
| 142 | kwargs: extra arguments to pass on to `np.testing.assert_allclose`. |
| 143 | |
| 144 | |
| 145 | """ |
| 146 | if isinstance(type_test, str) and type_test == "tensor": |
| 147 | if get_track_meta(): |
| 148 | np.testing.assert_equal(isinstance(actual, MetaTensor), True, "must be a MetaTensor") |
| 149 | else: |
| 150 | np.testing.assert_equal( |
| 151 | isinstance(actual, torch.Tensor) and not isinstance(actual, MetaTensor), True, "must be a torch.Tensor" |
| 152 | ) |
| 153 | elif type_test: |
| 154 | # check both actual and desired are of the same type |
| 155 | np.testing.assert_equal(isinstance(actual, np.ndarray), isinstance(desired, np.ndarray), "numpy type") |
| 156 | np.testing.assert_equal(isinstance(actual, torch.Tensor), isinstance(desired, torch.Tensor), "torch type") |
| 157 | |
| 158 | if isinstance(desired, torch.Tensor) or isinstance(actual, torch.Tensor): |
| 159 | if device_test: |
| 160 | np.testing.assert_equal(str(actual.device), str(desired.device), "torch device check") # type: ignore |
| 161 | actual = actual.detach().cpu().numpy() if isinstance(actual, torch.Tensor) else actual |
| 162 | desired = desired.detach().cpu().numpy() if isinstance(desired, torch.Tensor) else desired |
| 163 | np.testing.assert_allclose(actual, desired, *args, **kwargs) |
| 164 | |
| 165 | |
| 166 | @contextmanager |
no test coverage detected
searching dependent graphs…