|
1 | 1 | from typing import Any |
2 | 2 |
|
| 3 | +import torch |
3 | 4 | from pytest import mark, raises |
4 | 5 | from torch import Tensor |
5 | 6 | from torch.testing import assert_close |
@@ -266,6 +267,29 @@ def test_noncontiguous_jac() -> None: |
266 | 267 | assert_grad_close(t, g) |
267 | 268 |
|
268 | 269 |
|
| 270 | +@mark.parametrize("optimize", [True, False]) |
| 271 | +def test_mixed_dtypes(optimize: bool) -> None: |
| 272 | + """ |
| 273 | + Tests that jac_to_grad works when the tensors do not all have the same dtype. Each tensor should |
| 274 | + get a .grad of its own dtype, as torch's backward would do. |
| 275 | + """ |
| 276 | + |
| 277 | + aggregator = base_agg() |
| 278 | + t1 = tensor_(1.0, dtype=torch.float32, requires_grad=True) |
| 279 | + t2 = tensor_([2.0, 3.0], dtype=torch.float64, requires_grad=True) |
| 280 | + jac = tensor_([[-4.0, 1.0, 1.0], [6.0, 1.0, 1.0]], dtype=torch.float64) |
| 281 | + t1.__setattr__("jac", jac[:, 0].to(dtype=torch.float32)) |
| 282 | + t2.__setattr__("jac", jac[:, 1:]) |
| 283 | + expected_grad = aggregator(jac) |
| 284 | + |
| 285 | + jac_to_grad([t1, t2], aggregator, optimize_gramian_computation=optimize) |
| 286 | + |
| 287 | + assert t1.grad is not None and t1.grad.dtype == torch.float32 |
| 288 | + assert t2.grad is not None and t2.grad.dtype == torch.float64 |
| 289 | + assert_grad_close(t1, expected_grad[0].to(dtype=torch.float32)) |
| 290 | + assert_grad_close(t2, expected_grad[1:]) |
| 291 | + |
| 292 | + |
269 | 293 | @mark.parametrize("aggregator", [base_agg(), ConFIG()]) |
270 | 294 | def test_aggregator_hook_is_run(aggregator: Aggregator) -> None: |
271 | 295 | """ |
|
0 commit comments