paname 0.0.1.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of paname might be problematic. Click here for more details.

Files changed (108) hide show
  1. paname/__init__.py +10 -0
  2. paname/config.py +111 -0
  3. paname/extraction_techniques/__init__.py +5 -0
  4. paname/extraction_techniques/configurable.py +155 -0
  5. paname/extraction_techniques/discoverable_extraction/__init__.py +20 -0
  6. paname/extraction_techniques/discoverable_extraction/evaluation.py +437 -0
  7. paname/extraction_techniques/discoverable_extraction/metrics.py +99 -0
  8. paname/extraction_techniques/mia/__init__.py +35 -0
  9. paname/extraction_techniques/mia/attack_model.py +588 -0
  10. paname/extraction_techniques/mia/base.py +195 -0
  11. paname/extraction_techniques/mia/gradient.py +129 -0
  12. paname/extraction_techniques/mia/hop_skip_jump.py +460 -0
  13. paname/extraction_techniques/mia/likelihood_ratio.py +204 -0
  14. paname/extraction_techniques/mia/lira.py +422 -0
  15. paname/extraction_techniques/mia/loss.py +122 -0
  16. paname/extraction_techniques/mia/min_k_prob.py +172 -0
  17. paname/extraction_techniques/mia/neighborhood.py +248 -0
  18. paname/extraction_techniques/mia/noise_label_only.py +202 -0
  19. paname/extraction_techniques/mia/perplexity.py +142 -0
  20. paname/extraction_techniques/mia/reference_based.py +193 -0
  21. paname/extraction_techniques/mia/rmia.py +592 -0
  22. paname/extraction_techniques/mia/shadow_model_pool/__init__.py +5 -0
  23. paname/extraction_techniques/mia/shadow_model_pool/base.py +305 -0
  24. paname/extraction_techniques/mia/shadow_model_pool/local_model.py +122 -0
  25. paname/extraction_techniques/mia/zlib.py +185 -0
  26. paname/extraction_techniques/reconstruction/__init__.py +18 -0
  27. paname/extraction_techniques/reconstruction/base.py +113 -0
  28. paname/extraction_techniques/reconstruction/diffusion_clique.py +697 -0
  29. paname/extraction_techniques/reconstruction/informed_adversary.py +569 -0
  30. paname/extraction_techniques/reconstruction/llm_from_sampling.py +311 -0
  31. paname/extraction_techniques/reconstruction/utils.py +332 -0
  32. paname/io/__init__.py +10 -0
  33. paname/io/dataset.py +414 -0
  34. paname/io/huggingface.py +132 -0
  35. paname/io/sklearn.py +190 -0
  36. paname/io/torch.py +313 -0
  37. paname/metrics/__init__.py +5 -0
  38. paname/metrics/base.py +127 -0
  39. paname/metrics/metrics.py +502 -0
  40. paname/metrics/mia.py +159 -0
  41. paname/metrics/reconstruction.py +923 -0
  42. paname/mia_runner.py +91 -0
  43. paname/perturbators/__init__.py +5 -0
  44. paname/perturbators/base.py +140 -0
  45. paname/perturbators/gaussian.py +114 -0
  46. paname/perturbators/hsja.py +440 -0
  47. paname/perturbators/text_neighbors.py +321 -0
  48. paname/py.typed +0 -0
  49. paname/reporting/__init__.py +8 -0
  50. paname/reporting/lang.py +519 -0
  51. paname/reporting/report.py +1618 -0
  52. paname/scripts/__init__.py +54 -0
  53. paname/scripts/discoverable_extraction.py +124 -0
  54. paname/scripts/mia.py +274 -0
  55. paname/scripts/reconstruction.py +214 -0
  56. paname/signal_extraction/__init__.py +5 -0
  57. paname/signal_extraction/extractors.py +225 -0
  58. paname/signal_extraction/model_wrappers/__init__.py +90 -0
  59. paname/signal_extraction/model_wrappers/base.py +565 -0
  60. paname/signal_extraction/model_wrappers/gguf_lm.py +488 -0
  61. paname/signal_extraction/model_wrappers/huggingface_base.py +249 -0
  62. paname/signal_extraction/model_wrappers/huggingface_diffusers.py +156 -0
  63. paname/signal_extraction/model_wrappers/huggingface_lm.py +757 -0
  64. paname/signal_extraction/model_wrappers/huggingface_text_utils.py +67 -0
  65. paname/signal_extraction/model_wrappers/huggingface_token_classification.py +108 -0
  66. paname/signal_extraction/model_wrappers/online_api_lm.py +594 -0
  67. paname/signal_extraction/model_wrappers/onnx.py +204 -0
  68. paname/signal_extraction/model_wrappers/sklearn.py +103 -0
  69. paname/signal_extraction/model_wrappers/text_generation_utils.py +72 -0
  70. paname/signal_extraction/model_wrappers/text_sampling.py +146 -0
  71. paname/signal_extraction/model_wrappers/torch_classifier.py +396 -0
  72. paname/signal_extraction/model_wrappers/vllm_offline_lm.py +498 -0
  73. paname/signal_extraction/utils/__init__.py +5 -0
  74. paname/signal_extraction/utils/process_logprobs.py +329 -0
  75. paname/signal_extraction/utils/signal_transformations.py +43 -0
  76. paname/typing.py +78 -0
  77. paname/use_case.py +53 -0
  78. paname/utils/__init__.py +5 -0
  79. paname/utils/device.py +110 -0
  80. paname/utils/gradient_estimation.py +142 -0
  81. paname/utils/lp.py +90 -0
  82. paname/utils/resampling.py +74 -0
  83. paname/utils/seeding.py +30 -0
  84. paname-0.0.1.dev0.dist-info/METADATA +226 -0
  85. paname-0.0.1.dev0.dist-info/RECORD +108 -0
  86. paname-0.0.1.dev0.dist-info/WHEEL +4 -0
  87. paname-0.0.1.dev0.dist-info/entry_points.txt +2 -0
  88. paname-0.0.1.dev0.dist-info/licenses/LICENSES/CC0-1.0.txt +121 -0
  89. paname-0.0.1.dev0.dist-info/licenses/LICENSES/MIT.txt +21 -0
  90. paname_use_cases/apertus70b_canaries.py +48 -0
  91. paname_use_cases/bert_wnut.py +163 -0
  92. paname_use_cases/cifar10_mobilenet.py +148 -0
  93. paname_use_cases/discoverable_extraction_wikipedia.py +943 -0
  94. paname_use_cases/gpt2_imdb.py +58 -0
  95. paname_use_cases/gpt2_imdb_overfit.py +79 -0
  96. paname_use_cases/gpt2_wikitext.py +77 -0
  97. paname_use_cases/ministrallm_fineweb_gguf.py +102 -0
  98. paname_use_cases/ministrallm_fineweb_hf_lm.py +167 -0
  99. paname_use_cases/ministrallm_fineweb_vllm_offline.py +108 -0
  100. paname_use_cases/pleias1b_wtotext.py +91 -0
  101. paname_use_cases/pythia_mimir.py +110 -0
  102. paname_use_cases/random_forest_1m.py +34 -0
  103. paname_use_cases/resnet18_cifar10_shadow.py +202 -0
  104. paname_use_cases/sklearn_classifier_synthetic.py +43 -0
  105. paname_use_cases/sklearn_regressor_synthetic.py +36 -0
  106. paname_use_cases/utils/cifar10_helpers.py +157 -0
  107. paname_use_cases/utils/huggingface_text_helpers.py +97 -0
  108. paname_use_cases/utils/sklearn_helpers.py +199 -0
@@ -0,0 +1,460 @@
1
+ # SPDX-FileCopyrightText: 2026 PANAME Consortium (ANSSI, CNIL, Inria and PEReN)
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+
6
+ import logging
7
+ import math
8
+ from typing import Literal
9
+
10
+ import numpy as np
11
+ import torch
12
+ from sklearn.exceptions import NotFittedError
13
+ from tqdm import tqdm
14
+
15
+ from paname.extraction_techniques.mia.base import AbstractMIA
16
+ from paname.io.dataset import DataloaderBuilder, PanameDataset
17
+ from paname.perturbators.hsja import HopSkipJumpPerturbator
18
+ from paname.signal_extraction.model_wrappers.base import PredictedLabelModelWrapper
19
+ from paname.typing import MIAScore, SklearnBatch, SklearnData, TorchBatch, TorchData
20
+ from paname.utils.device import resolve_user_specified_device
21
+ from paname.utils.lp import lp_distance
22
+
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ class MultiTargetHSJA(AbstractMIA[PredictedLabelModelWrapper, TorchData | SklearnData]):
28
+ r"""
29
+ Label-Only Membership Inference Attack based on decision-boundary distance (Multi-Target HopSkipJump).
30
+
31
+ This attack operates in a strictly **label-only** black-box setting: the adversary may
32
+ only query the model's predicted class label, with no access to parameters, gradients,
33
+ losses, logits or probabilities. It infers membership from how far an input lies from the
34
+ model's decision boundaries, estimated with the HopSkipJump adversarial attack.
35
+
36
+ Note: this MIA is not divided into signal acquisition and computation like other
37
+ `SignalBasedAbstractMIA` due to its complexity and lack of reusability of extracted signals
38
+
39
+ **Overview**
40
+
41
+ The attack estimates, for each sample, the minimal perturbation (boundary distance)
42
+ needed to flip its prediction toward each of the *other* classes. The underlying
43
+ robustness hypothesis is that training examples tend to live in “flatter”,
44
+ more robust regions of the decision boundary and therefore require a **larger**
45
+ perturbation to be misclassified than unseen (non-member) examples. By measuring the
46
+ distance to the *nearest* wrong-class boundary, the attack turns this intuition into a
47
+ membership score while querying only hard labels.
48
+
49
+ Optionally, the absolute boundary distance can be *calibrated* against the distances of
50
+ slightly translated “neighbours” of the same input, yielding a relative score that is
51
+ more robust to samples that are naturally close to a boundary for everyone.
52
+
53
+ .. note::
54
+ **References:**
55
+ Chen, J., Jordan, M. I., & Wainwright, M. J. (2020).
56
+ *HopSkipJumpAttack: A Query-Efficient Decision-Based Attack*.
57
+ `arXiv:1904.02144 <https://arxiv.org/abs/1904.02144>`_
58
+
59
+ Choquette-Choo, C. A., Tramer, F., Carlini, N., & Papernot, N. (2021).
60
+ *Label-Only Membership Inference Attacks*. ICLR.
61
+ `arXiv:2007.14321 <https://arxiv.org/abs/2007.14321>`_
62
+
63
+ **Mathematical Principle**
64
+
65
+ Given a sample :math:`x` and a norm :math:`\|\cdot\|` (:math:`\ell_2` or
66
+ :math:`\ell_{\infty}`), the attack runs a targeted adversarial search toward each
67
+ class :math:`c \neq \hat{f}(x)` (where :math:`\hat{f}(x)` is the model's predicted
68
+ label), seeded by one adversarial example per class collected during
69
+ :meth:`fit_mia` (:math:`D_{aux}`). The **absolute boundary distance** is the
70
+ smallest perturbation found over all target classes:
71
+
72
+ .. math::
73
+ d(x) = \min_{c \neq \hat{f}(x)} \, \| x_{adv}^{(c)} - x \|
74
+
75
+ A larger :math:`d(x)` suggests the sample lies far from every decision boundary, i.e. is
76
+ robust and therefore more likely a member.
77
+
78
+
79
+ When :math:`N` neighbour shifts :math:`(\delta_1, \dots, \delta_N)` are configured,
80
+ the **relative boundary distance** is used instead:
81
+
82
+ .. math::
83
+ s(x) = d(x) - \frac{1}{N} \sum_{i=1}^{N} d(x + \delta_i)
84
+
85
+ so that :math:`s(x)` is the difference between the sample's own boundary distance and the
86
+ average boundary distance of its translated neighbours. A high :math:`s(x)` indicates the
87
+ sample is unusually far from the boundary compared to its surroundings. If none of the
88
+ neighbour attacks succeeds, the implementation falls back to the absolute distance
89
+ :math:`d(x)`.
90
+
91
+ **Threat Model**
92
+
93
+ +------------------------+-------------------------------------------------------------+
94
+ | Attribute | Description |
95
+ +========================+=============================================================+
96
+ | **Knowledge** | Label-Only (hard predicted labels only) |
97
+ +------------------------+-------------------------------------------------------------+
98
+ | **Signal** | Decision-boundary distance (absolute or relative) |
99
+ +------------------------+-------------------------------------------------------------+
100
+ | **Computation** | High (many label queries: HSJA iterations × |
101
+ | | target classes × neighbours) |
102
+ +------------------------+-------------------------------------------------------------+
103
+ | **Data Requirements** | Auxiliary seed pool covering every class (`fit_mia` must be |
104
+ | | called) |
105
+ +------------------------+-------------------------------------------------------------+
106
+
107
+ Parameters
108
+ ----------
109
+ model_wrapper : PredictedLabelModelWrapper
110
+ The model wrapper providing hard predicted labels via ``get_predicted_labels``.
111
+ n_classes : int
112
+ Number of classes of the classification problem. ``fit_mia`` must be able to find
113
+ at least one seed sample predicted as each of these classes.
114
+ n_iter : int, default=64
115
+ Number of outer HopSkipJump iterations run toward each target class.
116
+ filter_period : int, default=10
117
+ Every this-many iterations, the candidate target classes are pruned by boundary
118
+ distance to limit computation while the attack is still only approximate.
119
+ filter_keep_ratio : float, default=0.5
120
+ Fraction of the closest candidate target classes kept at each ``filter_period`` step
121
+ (at least one is always kept).
122
+ neighbour_shifts : list | None, default=None
123
+ Optional list of ``(row_delta, col_delta)`` pixel translations used to build the
124
+ translated neighbours for the relative boundary-distance score. When ``None``, the
125
+ absolute boundary distance is returned instead.
126
+ norm : Literal["l2", "linf"], default="l2"
127
+ Norm used to measure the boundary distance (and to constrain the HopSkipJump search).
128
+ device : str | torch.device | None, default=None
129
+ Device on which the model queries are run.
130
+ **hsja_kwargs
131
+ Additional keyword arguments forwarded to
132
+ :class:`~paname.perturbators.hsja.HopSkipJumpPerturbator` (e.g. ``verbose``,
133
+ ``initial_num_evals``, ``max_num_evals``, ``n_binary_search_steps``,
134
+ ``clip_min``/``clip_max``).
135
+
136
+ See Also
137
+ --------
138
+ :class:`paname.extraction_techniques.mia.noise_label_only.NoiseLabelOnlyMIA`
139
+ Another label-only attack, based on resistance of the predicted label to Gaussian noise.
140
+ :class:`paname.extraction_techniques.mia.loss_mia.LossMIA`
141
+ A much cheaper loss-based baseline, for when loss/logits are available.
142
+ """
143
+
144
+ requires_fitting: bool = True # fit_mia()'s D_aux seed tensors are needed for scoring
145
+ _model_wrapper: PredictedLabelModelWrapper
146
+
147
+ def __init__(
148
+ self,
149
+ model_wrapper: PredictedLabelModelWrapper,
150
+ n_classes: int,
151
+ n_iter: int = 64,
152
+ filter_period: int = 10,
153
+ filter_keep_ratio: float = 0.5,
154
+ neighbour_shifts: list | None = None,
155
+ norm: Literal["l2", "linf"] = "l2",
156
+ device: str | torch.device | None = None,
157
+ seed: int | None = None,
158
+ **hsja_kwargs,
159
+ ):
160
+
161
+ super().__init__(model_wrapper)
162
+ self.n_classes = n_classes
163
+ self.n_iter = n_iter
164
+ self.filter_period = filter_period
165
+ self.filter_keep_ratio = filter_keep_ratio
166
+ self.neighbour_shifts = neighbour_shifts
167
+ self.norm: Literal["l2", "linf"] = norm
168
+ self.device = resolve_user_specified_device(device)
169
+ self.seed = seed
170
+ self.hsja_kwargs = hsja_kwargs
171
+ self.verbose = hsja_kwargs.get("verbose", False)
172
+
173
+ def fit_mia(
174
+ self, mia_dataset: PanameDataset, dataloader_builder: DataloaderBuilder[TorchData | SklearnData]
175
+ ) -> None:
176
+ """Build the per-class seed examples used by the boundary-distance attacks.
177
+
178
+ This MIA requires fitting before scoring: the attack needs one ``seed`` tensor
179
+ per class (``self.D_aux``) to use as the starting point of the targeted
180
+ HopSkipJump searches toward each wrong class. The seeds are picked by scanning
181
+ the dataset through the provided dataloader and keeping, for each class, the
182
+ first sample the model wrapper predicts as that class.
183
+
184
+ Parameters
185
+ ----------
186
+ mia_dataset : PanameDataset
187
+ The dataset used to pick the per-class seed examples.
188
+ dataloader_builder : DataloaderBuilder[TorchData | SklearnData]
189
+ A callable that returns an iterable dataloader over the dataset.
190
+
191
+ Raises
192
+ ------
193
+ ValueError
194
+ If no sample predicted as some class is found among the whole dataset
195
+ (i.e. fewer than ``n_classes`` distinct predictions are observed).
196
+ """
197
+ self.D_aux = self._create_one_target_per_class_dict(mia_dataset, dataloader_builder)
198
+
199
+ @property
200
+ def is_fitted(self) -> bool:
201
+ """Whether the attack is ready to score.
202
+
203
+ ``True`` once :meth:`fit_mia` has been called and produced a complete per-class
204
+ seed set (i.e. ``self.D_aux`` holds exactly one seed per ``n_classes``).
205
+ """
206
+ return hasattr(self, "D_aux") and len(self.D_aux) == self.n_classes
207
+
208
+ def _create_one_target_per_class_dict(
209
+ self, dataset: PanameDataset, dataloader_builder: DataloaderBuilder[TorchData | SklearnData]
210
+ ) -> list:
211
+ """Build a list of seed tensors (one per class) by iterating the dataset via the dataloader
212
+ and picking the first sample predicted as each class by the model wrapper."""
213
+ class_to_seed: dict[int, torch.Tensor | np.ndarray] = {}
214
+ for batch in dataloader_builder(dataset):
215
+ x, _ = batch
216
+ preds = self._model_wrapper.get_predicted_labels((x, None))
217
+ for i, pred in enumerate(preds):
218
+ c = pred.item()
219
+ if c not in class_to_seed:
220
+ class_to_seed[c] = x[i : i + 1].copy() if isinstance(x, np.ndarray) else x[i : i + 1].clone()
221
+ if len(class_to_seed) == self.n_classes:
222
+ break
223
+
224
+ missing = set(range(self.n_classes)) - set(class_to_seed.keys())
225
+ if missing:
226
+ raise ValueError(
227
+ f"Could not find seed examples for classes {missing}. "
228
+ "Check that the dataset contains at least one example per class "
229
+ "and/ or that the model wrapper's predictions are correct."
230
+ )
231
+ return [class_to_seed[c] for c in range(self.n_classes)]
232
+
233
+ def _filter_best_master_candidate(self, candidates: list) -> list:
234
+ """Keep only the best ``filter_keep_ratio`` master candidates by boundary distance.
235
+
236
+ Sort the in-progress candidates by their current boundary distance and drop
237
+ the worst ones, so that HopSkipJump iterations focus on the classes whose
238
+ decision boundary is closest. This caps the computational cost of the repeated
239
+ gradient steps over the remaining classes.
240
+
241
+ Parameters
242
+ ----------
243
+ candidates : list
244
+ The list of candidate ``{"class", "x_adv", "dist"}`` dicts to prune.
245
+
246
+ Returns
247
+ -------
248
+ list
249
+ The pruned candidates, keeping at least one (the nearest) and at most
250
+ ``ceil(len(candidates) * filter_keep_ratio)`` of the best ones.
251
+ """
252
+ candidates.sort(key=lambda c: c["dist"])
253
+ keep = max(1, math.ceil(len(candidates) * self.filter_keep_ratio))
254
+ candidates = candidates[:keep]
255
+ return candidates
256
+
257
+ def compute_mia_score(
258
+ self, mia_dataset: PanameDataset, dataloader_builder: DataloaderBuilder[TorchData | SklearnData]
259
+ ) -> MIAScore:
260
+ """Compute MIA scores over the dataset using the multi-target HSJA boundary distance.
261
+
262
+ Each sample is scored individually via :meth:`compute_sample_mia_score`
263
+ (only batch size 1 is supported for now).
264
+
265
+ Requires :meth:`fit_mia` to have been called first, so the per-class seed tensors
266
+ (``self.D_aux``) used by :meth:`compute_sample_mia_score` are available.
267
+
268
+ Parameters
269
+ ----------
270
+ mia_dataset : PanameDataset
271
+ The dataset to score.
272
+ dataloader_builder : DataloaderBuilder[TorchData | SklearnData]
273
+ A callable that returns an iterable dataloader over the dataset.
274
+
275
+ Returns
276
+ -------
277
+ mia_scores : np.ndarray
278
+ A 1D array of MIA scores, one per sample. Higher = more likely a member.
279
+ """
280
+ # Scoring needs the per-class seed tensors built by fit_mia(). MultiTargetHSJA
281
+ # overrides is_fitted() below to report whether these are present and complete.
282
+ if not self.is_fitted:
283
+ raise NotFittedError(
284
+ f"{self.__class__.__name__} must be fitted first: call fit_mia() to build the "
285
+ "per-class seed examples used by the boundary-distance attacks."
286
+ )
287
+
288
+ # User provided dataloader builder for arrow table dataset
289
+ dataloader = dataloader_builder(mia_dataset)
290
+
291
+ # compute mia score per sample (batch size 1 per sample for now)
292
+ mia_scores = []
293
+ with tqdm(total=len(mia_dataset.ds), desc="MultiTargetHSJA") as pbar: # type: ignore
294
+ for x, y in dataloader:
295
+ for i in range(len(x)):
296
+ sample_batch = (x[i : i + 1], y[i : i + 1] if y is not None else None)
297
+ mia_scores.append(self.compute_sample_mia_score(sample_batch)) # type: ignore[arg-type]
298
+ pbar.update(1)
299
+
300
+ return np.array(mia_scores)
301
+
302
+ def compute_sample_mia_score(self, batch: TorchBatch | SklearnBatch) -> float:
303
+ """Compute the multi-target HopSkipJump boundary-distance MIA score for one sample.
304
+
305
+ For each class other than the sample's predicted label, a targeted HopSkipJump
306
+ search is run toward that class, starting from the corresponding per-class seed
307
+ of ``self.D_aux`` (built by :meth:`fit_mia`). Repeated gradient steps shrink the
308
+ boundary distance of the most promising candidates until :meth:`compute_mia_score`
309
+ returns the smallest distance found.
310
+
311
+ When ``neighbour_shifts`` is configured, the score is the *relative* boundary
312
+ distance ``d(x) - E[d(x_neighbours)]`` (Eq. 5/6): the sample's minimum distance
313
+ minus the average distance of its translated neighbours, providing a calibrated
314
+ membership signal. Otherwise the absolute distance ``d(x)`` is returned.
315
+
316
+ Parameters
317
+ ----------
318
+ batch : TorchBatch | SklearnBatch
319
+ A single-sample batch ``(x, y)``. Only batch size 1 is supported.
320
+
321
+ Returns
322
+ -------
323
+ score : float
324
+ The per-sample MIA score. A smaller boundary distance (or relative
325
+ distance) suggests a higher likelihood of membership.
326
+
327
+ Raises
328
+ ------
329
+ ValueError
330
+ If ``batch`` does not contain exactly one sample.
331
+
332
+ Notes
333
+ -----
334
+ Requires :meth:`fit_mia` to have been called so that ``self.D_aux`` holds the
335
+ per-class seed tensors used to seed the targeted HopSkipJump searches.
336
+ """
337
+ x, _ = batch
338
+ if len(x) != 1:
339
+ raise ValueError("Only batch size 1 is supported for compute_sample_mia_score.")
340
+
341
+ candidates = []
342
+ orig_label = self._model_wrapper.get_predicted_labels(batch)
343
+
344
+ for c in range(self.n_classes):
345
+ if c == orig_label:
346
+ continue
347
+ candidates.append(
348
+ {
349
+ "class": c,
350
+ "x_adv": self.D_aux[c].copy() if isinstance(self.D_aux[c], np.ndarray) else self.D_aux[c].clone(),
351
+ "dist": float("inf"),
352
+ }
353
+ )
354
+
355
+ perturbator = HopSkipJumpPerturbator(
356
+ model=self._model_wrapper,
357
+ norm=self.norm,
358
+ targeted=True,
359
+ n_iter=1,
360
+ device=self.device,
361
+ seed=self.seed,
362
+ **self.hsja_kwargs,
363
+ )
364
+
365
+ for t in range(1, self.n_iter + 1):
366
+ for cand in candidates:
367
+ perturb_result = perturbator.perturbate(
368
+ batch, # type: ignore
369
+ x_seed=cand["x_adv"],
370
+ target_label=cand["class"],
371
+ t_start=t,
372
+ skip_final_search=(t < self.n_iter),
373
+ )
374
+ # New datasetwise API: a single perturbation (x_adv, None) plus a mask.
375
+ (x_adv, _) = perturb_result.perturbations[0]
376
+ cand["x_adv"] = x_adv
377
+ cand["dist"] = lp_distance(x_adv, x, norm=self.norm, batched=False)
378
+
379
+ # Only keep candidates whose decision boundary dist drops fast along the gradient to reduce
380
+ # computation overload
381
+ if t % self.filter_period == 0 and len(candidates) > 1:
382
+ candidates = self._filter_best_master_candidate(candidates)
383
+
384
+ best = min(candidates, key=lambda c: c["dist"])
385
+
386
+ # relative boundary distance (Eq. 5/6)
387
+ relative_dist = None
388
+
389
+ if self.neighbour_shifts is not None:
390
+ neighbour_dists = []
391
+ for shift in self.neighbour_shifts:
392
+ x_nb = self._translate(batch[0], shift)
393
+ nb_perturbator = HopSkipJumpPerturbator(
394
+ model=self._model_wrapper,
395
+ norm=self.norm, # type: ignore
396
+ targeted=True,
397
+ n_iter=self.n_iter,
398
+ device=self.device,
399
+ seed=self.seed,
400
+ **self.hsja_kwargs,
401
+ )
402
+ nb_result = nb_perturbator.perturbate(
403
+ data=(x_nb, None), # type: ignore
404
+ x_seed=(
405
+ self.D_aux[best["class"]].copy()
406
+ if isinstance(self.D_aux[best["class"]], np.ndarray)
407
+ else self.D_aux[best["class"]].clone()
408
+ ),
409
+ target_label=best["class"],
410
+ )
411
+ # New datasetwise API: a single variation (x_adv, None) plus a mask.
412
+ (x_adv, _) = nb_result.perturbations[0]
413
+ success_mask = nb_result.masks[0]
414
+ nb_success = bool(success_mask.item())
415
+ if nb_success:
416
+ dist = lp_distance(x_adv, x_nb, norm=self.norm, batched=False)
417
+ if isinstance(dist, torch.Tensor):
418
+ dist = dist.item()
419
+ neighbour_dists.append(dist)
420
+ if self.verbose:
421
+ logger.debug("Successful neighbours: %s/%s", len(neighbour_dists), len(self.neighbour_shifts))
422
+ if neighbour_dists:
423
+ # s_ours(x) = d(x) − E[d(X_neighbours)] (Eq. 5)
424
+ relative_dist = best["dist"] - float(np.mean(neighbour_dists))
425
+ return relative_dist
426
+ else:
427
+ logger.warning("Relative distance score is None. Using absolute distance as MIA score instead.")
428
+ return best["dist"]
429
+
430
+ def _translate(self, x: torch.Tensor | np.ndarray, shift: tuple) -> np.ndarray | torch.Tensor:
431
+ """
432
+ Translate an image by (row_delta, col_delta) pixels using np.roll or torch.roll.
433
+ Handles (H, W), (H, W, C), and (C, H, W) layouts.
434
+ """
435
+ x = x.copy() if isinstance(x, np.ndarray) else x.clone()
436
+ dr, dc = shift
437
+ if len(x.shape) == 2:
438
+ if isinstance(x, np.ndarray):
439
+ x = np.roll(x, dr, axis=0)
440
+ x = np.roll(x, dc, axis=1)
441
+ else:
442
+ x = torch.roll(x, shifts=dr, dims=0)
443
+ x = torch.roll(x, shifts=dc, dims=1)
444
+
445
+ elif len(x.shape) == 3:
446
+ if x.shape[0] in (1, 3): # (C, H, W)
447
+ if isinstance(x, np.ndarray):
448
+ x = np.roll(x, dr, axis=1)
449
+ x = np.roll(x, dc, axis=2)
450
+ else:
451
+ x = torch.roll(x, dr, dims=1)
452
+ x = torch.roll(x, dc, dims=2)
453
+ else: # (H, W, C)
454
+ if isinstance(x, np.ndarray):
455
+ x = np.roll(x, dr, axis=0)
456
+ x = np.roll(x, dc, axis=1)
457
+ else:
458
+ x = torch.roll(x, dr, dims=0)
459
+ x = torch.roll(x, dc, dims=1)
460
+ return x
@@ -0,0 +1,204 @@
1
+ # SPDX-FileCopyrightText: 2026 PANAME Consortium (ANSSI, CNIL, Inria and PEReN)
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+
6
+ """Base class for likelihood-ratio membership inference attacks using shadow models.
7
+
8
+ Likelihood-ratio attacks (LiRA, RMIA), based on :class:`AbstractLikelihoodRatioMIA`,
9
+ use shadow models to estimate reference signal distributions or probabilities and
10
+ compare them with the target model's signals to compute membership scores.
11
+
12
+ For these attacks, **online** mode uses shadow models trained with each sample being
13
+ audited (IN) and others trained without it (OUT). **Offline** mode uses only OUT shadow
14
+ models for that sample. Online mode currently requires
15
+ :meth:`AbstractLikelihoodRatioMIA.fit_compute_mia_score`: the audit dataset must match
16
+ the shadow pool's population dataset, in the same order.
17
+ """
18
+
19
+ import logging
20
+ from abc import abstractmethod
21
+ from typing import NamedTuple, cast
22
+
23
+ import numpy as np
24
+
25
+ from paname.extraction_techniques.mia.base import AbstractShadowMIA
26
+ from paname.extraction_techniques.mia.shadow_model_pool.local_model import LocalModelShadowModelPool
27
+ from paname.io.dataset import DataloaderBuilder, PanameDataset, raise_if_non_deterministic_dataloader
28
+ from paname.signal_extraction.extractors import LogitsExtractor, SignalExtractor, TrueLabelExtractor
29
+ from paname.signal_extraction.model_wrappers.base import LogitsAndTrueLabelModelWrapper
30
+ from paname.typing import ArraySignal, DataT, LabelSignal, MIAScore
31
+
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ class LikelihoodRatioAttackSignals(NamedTuple):
37
+ target_logits: ArraySignal
38
+ shadow_logits: tuple[ArraySignal, ...]
39
+ labels: LabelSignal
40
+
41
+
42
+ class AbstractLikelihoodRatioMIA(AbstractShadowMIA[LogitsAndTrueLabelModelWrapper, DataT]):
43
+ """Base class for likelihood-ratio MIAs using shadow models (LiRA, RMIA, ...).
44
+
45
+ This class factors common signal extraction for attacks that compute likelihood-ratio
46
+ scores using shadow models.
47
+
48
+ Parameters
49
+ ----------
50
+ model_wrapper : LogitsAndTrueLabelModelWrapper
51
+ ModelWrapper providing logits and true labels.
52
+ shadow_model_pool : LocalModelShadowModelPool
53
+ Pool of shadow models for the MIA.
54
+ online : bool, default=False
55
+ If True, enables online mode (only supported for fit_compute_mia_score).
56
+
57
+ Attributes
58
+ ----------
59
+ shadow_model_pool : LocalModelShadowModelPool
60
+ The pool of shadow models.
61
+ online : bool
62
+ Whether the MIA is in online mode.
63
+
64
+ Notes
65
+ -----
66
+ - Only handles LocalModelShadowModelPool for now.
67
+ - A TrainableShadowModelPool would allow training shadow models during fit_mia/fit_compute_mia_score.
68
+ - In fit_mia:
69
+ - ShadowModelPool: validate if pre-trained, train if not (not supported yet).
70
+ - Optionally computes statistics and stores them in attributes (RMIA)
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ model_wrapper: LogitsAndTrueLabelModelWrapper,
76
+ shadow_model_pool: LocalModelShadowModelPool, # NOTE: only local models handled for now
77
+ online: bool = False,
78
+ ):
79
+ super().__init__(model_wrapper, shadow_model_pool)
80
+ self.online = online
81
+ self._state = None
82
+ self._logits_extractor = LogitsExtractor()
83
+ self._true_labels_extractor = TrueLabelExtractor()
84
+
85
+ @property
86
+ def is_fitted(self) -> bool:
87
+ """Check if the MIA has been fitted.
88
+
89
+ Returns
90
+ -------
91
+ bool
92
+ True if fitted, False otherwise.
93
+ """
94
+ return self._state is not None
95
+
96
+ def _get_target_model_signals(
97
+ self,
98
+ mia_dataset: PanameDataset,
99
+ dataloader_builder: DataloaderBuilder[DataT],
100
+ signal_extractor: SignalExtractor,
101
+ ) -> np.ndarray:
102
+ """Extract signals from the target model for the given dataset.
103
+
104
+ Parameters
105
+ ----------
106
+ mia_dataset : PanameDataset
107
+ Dataset for membership inference.
108
+ dataloader_builder : DataloaderBuilder[DataT]
109
+ Builder for data loaders.
110
+ signal_extractor : SignalExtractor
111
+ Extractor for the desired signal (e.g., logits, labels).
112
+
113
+ Returns
114
+ -------
115
+ ModelSignal
116
+ Extracted signal as a numpy array.
117
+
118
+ Notes
119
+ -----
120
+ - Ensures deterministic dataloader for consistency.
121
+ """
122
+ dataloader = dataloader_builder(mia_dataset)
123
+ raise_if_non_deterministic_dataloader(dataloader)
124
+ batch_scores = [signal_extractor.extract(self._model_wrapper, batch) for batch in dataloader]
125
+ return np.concatenate(batch_scores)
126
+
127
+ def _acquire_signals(
128
+ self,
129
+ mia_dataset: PanameDataset,
130
+ dataloader_builder: DataloaderBuilder[DataT],
131
+ ) -> LikelihoodRatioAttackSignals:
132
+ """Extract raw (cacheable) signals from target and shadow models.
133
+
134
+ Attack-specific transforms (LiRA logit rescaling, RMIA confidences) are applied
135
+ downstream.
136
+
137
+ Parameters
138
+ ----------
139
+ mia_dataset : PanameDataset
140
+ Dataset for membership inference.
141
+ dataloader_builder : DataloaderBuilder[DataT]
142
+ Builder for data loaders.
143
+
144
+ Returns
145
+ -------
146
+ target_logits : np.ndarray
147
+ logits from the target model. Shape: ``(n_samples, n_classes)``.
148
+ shadow_logits : tuple[np.ndarray]
149
+ logits from shadow models, one array per shadow model.
150
+ Each element shape: ``(n_samples, n_classes)``.
151
+ labels : np.ndarray
152
+ True class labels. Shape: ``(n_samples,)``.
153
+
154
+ Notes
155
+ -----
156
+ - We use self.shadow_model_pool (not self._state.shadow_model_pool)
157
+ """
158
+ labels = self._get_target_model_signals(mia_dataset, dataloader_builder, self._true_labels_extractor)
159
+ target_logits = self._get_target_model_signals(mia_dataset, dataloader_builder, self._logits_extractor)
160
+ shadow_logits = self.shadow_model_pool.get_signals(mia_dataset, dataloader_builder, self._logits_extractor)
161
+ return LikelihoodRatioAttackSignals(target_logits, cast(tuple[ArraySignal, ...], shadow_logits), labels)
162
+
163
+ @abstractmethod
164
+ def fit_compute_mia_score(
165
+ self,
166
+ mia_dataset: PanameDataset,
167
+ dataloader_builder: DataloaderBuilder[DataT],
168
+ ) -> MIAScore:
169
+ """Fit and score on the same (population) dataset (transductive case).
170
+
171
+ Each sample is treated as both calibration reference (z) and audit target (x).
172
+
173
+ Parameters
174
+ ----------
175
+ mia_dataset : PanameDataset
176
+ Dataset for membership inference.
177
+ dataloader_builder : DataloaderBuilder[DataT]
178
+ Builder for data loaders.
179
+
180
+ Returns
181
+ -------
182
+ MIAScore
183
+ Membership inference score.
184
+
185
+ Notes
186
+ -----
187
+ - uses ShadowModelPool membership masks to split.
188
+ - In the LiRA & RMIA papers, datasets have no overlap. However, it is more computationally efficient
189
+ to build the ShadowModelPool at once, and not per inference sample/batch.
190
+ - In the offline case, it is a bit unusual: the population dataset Z = audit dataset X, which the
191
+ ShadowModelPool was trained on. There is no extra data to audit on. Maybe it should be online only.
192
+ """
193
+ raise NotImplementedError
194
+
195
+ def _warn_if_local_shadow_pool(self):
196
+ if isinstance(self.shadow_model_pool, LocalModelShadowModelPool):
197
+ logger.warning(
198
+ "Used a ShadowModelPool instantiating (already trained) models locally. "
199
+ "Please ensure that the dataset used in LiRA/RMIA (here %s) "
200
+ "is EXACTLY the one (same samples, "
201
+ "same order) as the one used to train the shadow models. "
202
+ "This ensures consistency between masks and MIA train/test split.",
203
+ self.__class__.__name__,
204
+ )