|
| 1 | +import logging |
| 2 | +import numpy as np |
| 3 | +from pykeops.torch import LazyTensor |
| 4 | +import torch |
| 5 | +from typing import Callable, Dict, List, Optional, Tuple, Union |
| 6 | +from alibi_detect.cd.base import BaseMMDDrift |
| 7 | +from alibi_detect.utils.keops.kernels import GaussianRBF |
| 8 | +from alibi_detect.utils.pytorch import get_device |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +class MMDDriftKeops(BaseMMDDrift): |
| 14 | + def __init__( |
| 15 | + self, |
| 16 | + x_ref: Union[np.ndarray, list], |
| 17 | + p_val: float = .05, |
| 18 | + x_ref_preprocessed: bool = False, |
| 19 | + preprocess_at_init: bool = True, |
| 20 | + update_x_ref: Optional[Dict[str, int]] = None, |
| 21 | + preprocess_fn: Optional[Callable] = None, |
| 22 | + kernel: Callable = GaussianRBF, |
| 23 | + sigma: Optional[np.ndarray] = None, |
| 24 | + configure_kernel_from_x_ref: bool = True, |
| 25 | + n_permutations: int = 100, |
| 26 | + batch_size_permutations: int = 1000000, |
| 27 | + device: Optional[str] = None, |
| 28 | + input_shape: Optional[tuple] = None, |
| 29 | + data_type: Optional[str] = None |
| 30 | + ) -> None: |
| 31 | + """ |
| 32 | + Maximum Mean Discrepancy (MMD) data drift detector using a permutation test. |
| 33 | +
|
| 34 | + Parameters |
| 35 | + ---------- |
| 36 | + x_ref |
| 37 | + Data used as reference distribution. |
| 38 | + p_val |
| 39 | + p-value used for the significance of the permutation test. |
| 40 | + x_ref_preprocessed |
| 41 | + Whether the given reference data `x_ref` has been preprocessed yet. If `x_ref_preprocessed=True`, only |
| 42 | + the test data `x` will be preprocessed at prediction time. If `x_ref_preprocessed=False`, the reference |
| 43 | + data will also be preprocessed. |
| 44 | + preprocess_at_init |
| 45 | + Whether to preprocess the reference data when the detector is instantiated. Otherwise, the reference |
| 46 | + data will be preprocessed at prediction time. Only applies if `x_ref_preprocessed=False`. |
| 47 | + update_x_ref |
| 48 | + Reference data can optionally be updated to the last n instances seen by the detector |
| 49 | + or via reservoir sampling with size n. For the former, the parameter equals {'last': n} while |
| 50 | + for reservoir sampling {'reservoir_sampling': n} is passed. |
| 51 | + preprocess_fn |
| 52 | + Function to preprocess the data before computing the data drift metrics. |
| 53 | + kernel |
| 54 | + Kernel used for the MMD computation, defaults to Gaussian RBF kernel. |
| 55 | + sigma |
| 56 | + Optionally set the GaussianRBF kernel bandwidth. Can also pass multiple bandwidth values as an array. |
| 57 | + The kernel evaluation is then averaged over those bandwidths. |
| 58 | + configure_kernel_from_x_ref |
| 59 | + Whether to already configure the kernel bandwidth from the reference data. |
| 60 | + n_permutations |
| 61 | + Number of permutations used in the permutation test. |
| 62 | + batch_size_permutations |
| 63 | + KeOps computes the n_permutations of the MMD^2 statistics in chunks of batch_size_permutations. |
| 64 | + device |
| 65 | + Device type used. The default None tries to use the GPU and falls back on CPU if needed. |
| 66 | + Can be specified by passing either 'cuda', 'gpu' or 'cpu'. |
| 67 | + input_shape |
| 68 | + Shape of input data. |
| 69 | + data_type |
| 70 | + Optionally specify the data type (tabular, image or time-series). Added to metadata. |
| 71 | + """ |
| 72 | + super().__init__( |
| 73 | + x_ref=x_ref, |
| 74 | + p_val=p_val, |
| 75 | + x_ref_preprocessed=x_ref_preprocessed, |
| 76 | + preprocess_at_init=preprocess_at_init, |
| 77 | + update_x_ref=update_x_ref, |
| 78 | + preprocess_fn=preprocess_fn, |
| 79 | + sigma=sigma, |
| 80 | + configure_kernel_from_x_ref=configure_kernel_from_x_ref, |
| 81 | + n_permutations=n_permutations, |
| 82 | + input_shape=input_shape, |
| 83 | + data_type=data_type |
| 84 | + ) |
| 85 | + self.meta.update({'backend': 'keops'}) |
| 86 | + |
| 87 | + # set device |
| 88 | + self.device = get_device(device) |
| 89 | + |
| 90 | + # initialize kernel |
| 91 | + sigma = torch.from_numpy(sigma).to(self.device) if isinstance(sigma, # type: ignore[assignment] |
| 92 | + np.ndarray) else None |
| 93 | + self.kernel = kernel(sigma).to(self.device) if kernel == GaussianRBF else kernel |
| 94 | + |
| 95 | + # set the correct MMD^2 function based on the batch size for the permutations |
| 96 | + self.batch_size = batch_size_permutations |
| 97 | + self.n_batches = 1 + (n_permutations - 1) // batch_size_permutations |
| 98 | + |
| 99 | + # infer the kernel bandwidth from the reference data |
| 100 | + if isinstance(sigma, torch.Tensor): |
| 101 | + self.infer_sigma = False |
| 102 | + elif self.infer_sigma: |
| 103 | + x = torch.from_numpy(self.x_ref).to(self.device) |
| 104 | + _ = self.kernel(LazyTensor(x[:, None, :]), LazyTensor(x[None, :, :]), infer_sigma=self.infer_sigma) |
| 105 | + self.infer_sigma = False |
| 106 | + else: |
| 107 | + self.infer_sigma = True |
| 108 | + |
| 109 | + def _mmd2(self, x_all: torch.Tensor, perms: List[torch.Tensor], m: int, n: int) \ |
| 110 | + -> Tuple[torch.Tensor, torch.Tensor]: |
| 111 | + """ |
| 112 | + Batched (across the permutations) MMD^2 computation for the original test statistic and the permutations. |
| 113 | +
|
| 114 | + Parameters |
| 115 | + ---------- |
| 116 | + x_all |
| 117 | + Concatenated reference and test instances. |
| 118 | + perms |
| 119 | + List with permutation vectors. |
| 120 | + m |
| 121 | + Number of reference instances. |
| 122 | + n |
| 123 | + Number of test instances. |
| 124 | +
|
| 125 | + Returns |
| 126 | + ------- |
| 127 | + MMD^2 statistic for the original and permuted reference and test sets. |
| 128 | + """ |
| 129 | + k_xx, k_yy, k_xy = [], [], [] |
| 130 | + for batch in range(self.n_batches): |
| 131 | + i, j = batch * self.batch_size, (batch + 1) * self.batch_size |
| 132 | + # construct stacked tensors with a batch of permutations for the reference set x and test set y |
| 133 | + x = torch.cat([x_all[perm[:m]][None, :, :] for perm in perms[i:j]], 0) |
| 134 | + y = torch.cat([x_all[perm[m:]][None, :, :] for perm in perms[i:j]], 0) |
| 135 | + if batch == 0: |
| 136 | + x = torch.cat([x_all[None, :m, :], x], 0) |
| 137 | + y = torch.cat([x_all[None, m:, :], y], 0) |
| 138 | + x, y = x.to(self.device), y.to(self.device) |
| 139 | + |
| 140 | + # batch-wise kernel matrix computation over the permutations |
| 141 | + k_xy.append(self.kernel( |
| 142 | + LazyTensor(x[:, :, None, :]), LazyTensor(y[:, None, :, :]), self.infer_sigma).sum(1).sum(1).squeeze(-1)) |
| 143 | + k_xx.append(self.kernel( |
| 144 | + LazyTensor(x[:, :, None, :]), LazyTensor(x[:, None, :, :])).sum(1).sum(1).squeeze(-1)) |
| 145 | + k_yy.append(self.kernel( |
| 146 | + LazyTensor(y[:, :, None, :]), LazyTensor(y[:, None, :, :])).sum(1).sum(1).squeeze(-1)) |
| 147 | + c_xx, c_yy, c_xy = 1 / (m * (m - 1)), 1 / (n * (n - 1)), 2. / (m * n) |
| 148 | + # Note that the MMD^2 estimates assume that the diagonal of the kernel matrix consists of 1's |
| 149 | + stats = c_xx * (torch.cat(k_xx) - m) + c_yy * (torch.cat(k_yy) - n) - c_xy * torch.cat(k_xy) |
| 150 | + return stats[0], stats[1:] |
| 151 | + |
| 152 | + def score(self, x: Union[np.ndarray, list]) -> Tuple[float, float, float]: |
| 153 | + """ |
| 154 | + Compute the p-value resulting from a permutation test using the maximum mean discrepancy |
| 155 | + as a distance measure between the reference data and the data to be tested. |
| 156 | +
|
| 157 | + Parameters |
| 158 | + ---------- |
| 159 | + x |
| 160 | + Batch of instances. |
| 161 | +
|
| 162 | + Returns |
| 163 | + ------- |
| 164 | + p-value obtained from the permutation test, the MMD^2 between the reference and test set, |
| 165 | + and the MMD^2 threshold above which drift is flagged. |
| 166 | + """ |
| 167 | + x_ref, x = self.preprocess(x) |
| 168 | + x_ref = torch.from_numpy(x_ref).float() # type: ignore[assignment] |
| 169 | + x = torch.from_numpy(x).float() # type: ignore[assignment] |
| 170 | + # compute kernel matrix, MMD^2 and apply permutation test |
| 171 | + m, n = x_ref.shape[0], x.shape[0] |
| 172 | + perms = [torch.randperm(m + n) for _ in range(self.n_permutations)] |
| 173 | + # TODO - Rethink typings (related to https://github.com/SeldonIO/alibi-detect/issues/540) |
| 174 | + x_all = torch.cat([x_ref, x], 0) # type: ignore[list-item] |
| 175 | + mmd2, mmd2_permuted = self._mmd2(x_all, perms, m, n) |
| 176 | + if self.device.type == 'cuda': |
| 177 | + mmd2, mmd2_permuted = mmd2.cpu(), mmd2_permuted.cpu() |
| 178 | + p_val = (mmd2 <= mmd2_permuted).float().mean() |
| 179 | + # compute distance threshold |
| 180 | + idx_threshold = int(self.p_val * len(mmd2_permuted)) |
| 181 | + distance_threshold = torch.sort(mmd2_permuted, descending=True).values[idx_threshold] |
| 182 | + return p_val.numpy().item(), mmd2.numpy().item(), distance_threshold.numpy() |
0 commit comments