|
| 1 | +from typing import Tuple |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import pytest |
| 5 | +import torch |
| 6 | +from scipy.special import softmax |
| 7 | +from scipy.stats import entropy |
| 8 | +from torch import Tensor |
| 9 | + |
| 10 | +import ignite.distributed as idist |
| 11 | + |
| 12 | +from ignite.engine import Engine |
| 13 | +from ignite.exceptions import NotComputableError |
| 14 | +from ignite.metrics import MutualInformation |
| 15 | + |
| 16 | + |
| 17 | +def np_mutual_information(np_y_pred: np.ndarray) -> float: |
| 18 | + prob = softmax(np_y_pred, axis=1) |
| 19 | + marginal_ent = entropy(np.mean(prob, axis=0)) |
| 20 | + conditional_ent = np.mean(entropy(prob, axis=1)) |
| 21 | + return max(0.0, marginal_ent - conditional_ent) |
| 22 | + |
| 23 | + |
| 24 | +def test_zero_sample(): |
| 25 | + mi = MutualInformation() |
| 26 | + with pytest.raises( |
| 27 | + NotComputableError, match=r"MutualInformation must have at least one example before it can be computed" |
| 28 | + ): |
| 29 | + mi.compute() |
| 30 | + |
| 31 | + |
| 32 | +def test_invalid_shape(): |
| 33 | + mi = MutualInformation() |
| 34 | + y_pred = torch.randn(10).float() |
| 35 | + with pytest.raises(ValueError, match=r"y_pred must be in the shape of \(B, C\) or \(B, C, ...\), got"): |
| 36 | + mi.update((y_pred, None)) |
| 37 | + |
| 38 | + |
| 39 | +@pytest.fixture(params=list(range(4))) |
| 40 | +def test_case(request): |
| 41 | + return [ |
| 42 | + (torch.randn((100, 10)).float(), torch.randint(0, 10, size=[100]), 1), |
| 43 | + (torch.rand((100, 500)).float(), torch.randint(0, 500, size=[100]), 1), |
| 44 | + # updated batches |
| 45 | + (torch.normal(0.0, 5.0, size=(100, 10)).float(), torch.randint(0, 10, size=[100]), 16), |
| 46 | + (torch.normal(5.0, 3.0, size=(100, 200)).float(), torch.randint(0, 200, size=[100]), 16), |
| 47 | + # image segmentation |
| 48 | + (torch.randn((100, 5, 32, 32)).float(), torch.randint(0, 5, size=(100, 32, 32)), 16), |
| 49 | + (torch.randn((100, 5, 224, 224)).float(), torch.randint(0, 5, size=(100, 224, 224)), 16), |
| 50 | + ][request.param] |
| 51 | + |
| 52 | + |
| 53 | +@pytest.mark.parametrize("n_times", range(5)) |
| 54 | +def test_compute(n_times, test_case: Tuple[Tensor, Tensor, int]): |
| 55 | + mi = MutualInformation() |
| 56 | + |
| 57 | + y_pred, y, batch_size = test_case |
| 58 | + |
| 59 | + mi.reset() |
| 60 | + if batch_size > 1: |
| 61 | + n_iters = y.shape[0] // batch_size + 1 |
| 62 | + for i in range(n_iters): |
| 63 | + idx = i * batch_size |
| 64 | + mi.update((y_pred[idx : idx + batch_size], y[idx : idx + batch_size])) |
| 65 | + else: |
| 66 | + mi.update((y_pred, y)) |
| 67 | + |
| 68 | + np_res = np_mutual_information(y_pred.numpy()) |
| 69 | + res = mi.compute() |
| 70 | + |
| 71 | + assert isinstance(res, float) |
| 72 | + assert pytest.approx(np_res, rel=1e-4) == res |
| 73 | + |
| 74 | + |
| 75 | +def test_accumulator_detached(): |
| 76 | + mi = MutualInformation() |
| 77 | + |
| 78 | + y_pred = torch.tensor([[2.0, 3.0], [-2.0, -1.0]], requires_grad=True) |
| 79 | + y = torch.zeros(2) |
| 80 | + mi.update((y_pred, y)) |
| 81 | + |
| 82 | + assert not mi._sum_of_probabilities.requires_grad |
| 83 | + |
| 84 | + |
| 85 | +@pytest.mark.usefixtures("distributed") |
| 86 | +class TestDistributed: |
| 87 | + def test_integration(self): |
| 88 | + tol = 1e-4 |
| 89 | + n_iters = 100 |
| 90 | + batch_size = 10 |
| 91 | + n_cls = 50 |
| 92 | + device = idist.device() |
| 93 | + rank = idist.get_rank() |
| 94 | + torch.manual_seed(12 + rank) |
| 95 | + |
| 96 | + metric_devices = [torch.device("cpu")] |
| 97 | + if device.type != "xla": |
| 98 | + metric_devices.append(device) |
| 99 | + |
| 100 | + for metric_device in metric_devices: |
| 101 | + y_true = torch.randint(0, n_cls, size=[n_iters * batch_size], dtype=torch.long).to(device) |
| 102 | + y_preds = torch.normal(0.0, 3.0, size=(n_iters * batch_size, n_cls), dtype=torch.float).to(device) |
| 103 | + |
| 104 | + engine = Engine( |
| 105 | + lambda e, i: ( |
| 106 | + y_preds[i * batch_size : (i + 1) * batch_size], |
| 107 | + y_true[i * batch_size : (i + 1) * batch_size], |
| 108 | + ) |
| 109 | + ) |
| 110 | + |
| 111 | + m = MutualInformation(device=metric_device) |
| 112 | + m.attach(engine, "mutual_information") |
| 113 | + |
| 114 | + data = list(range(n_iters)) |
| 115 | + engine.run(data=data, max_epochs=1) |
| 116 | + |
| 117 | + y_preds = idist.all_gather(y_preds) |
| 118 | + y_true = idist.all_gather(y_true) |
| 119 | + |
| 120 | + assert "mutual_information" in engine.state.metrics |
| 121 | + res = engine.state.metrics["mutual_information"] |
| 122 | + |
| 123 | + true_res = np_mutual_information(y_preds.cpu().numpy()) |
| 124 | + |
| 125 | + assert pytest.approx(true_res, rel=tol) == res |
| 126 | + |
| 127 | + def test_accumulator_device(self): |
| 128 | + device = idist.device() |
| 129 | + metric_devices = [torch.device("cpu")] |
| 130 | + if device.type != "xla": |
| 131 | + metric_devices.append(device) |
| 132 | + for metric_device in metric_devices: |
| 133 | + mi = MutualInformation(device=metric_device) |
| 134 | + |
| 135 | + devices = (mi._device, mi._sum_of_probabilities.device) |
| 136 | + for dev in devices: |
| 137 | + assert dev == metric_device, f"{type(dev)}:{dev} vs {type(metric_device)}:{metric_device}" |
| 138 | + |
| 139 | + y_pred = torch.tensor([[2.0, 3.0], [-2.0, -1.0]], requires_grad=True) |
| 140 | + y = torch.zeros(2) |
| 141 | + mi.update((y_pred, y)) |
| 142 | + |
| 143 | + devices = (mi._device, mi._sum_of_probabilities.device) |
| 144 | + for dev in devices: |
| 145 | + assert dev == metric_device, f"{type(dev)}:{dev} vs {type(metric_device)}:{metric_device}" |
0 commit comments