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
paname/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Main module."""
2
+
3
+ # SPDX-FileCopyrightText: 2026 PANAME Consortium (ANSSI, CNIL, Inria and PEReN)
4
+ #
5
+ # SPDX-License-Identifier: MIT
6
+
7
+ import logging
8
+
9
+
10
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
paname/config.py ADDED
@@ -0,0 +1,111 @@
1
+ # SPDX-FileCopyrightText: 2026 PANAME Consortium (ANSSI, CNIL, Inria and PEReN)
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Configuration and logging setup for the project.
6
+
7
+ This module defines the directory structure, default logging configuration,
8
+ and the Pydantic settings class used to manage environment variables and
9
+ application settings.
10
+ """
11
+
12
+ import json
13
+ import logging
14
+ import logging.config
15
+ from pathlib import Path
16
+ from typing import Literal
17
+
18
+ from platformdirs import user_cache_dir, user_data_dir
19
+ from pydantic import Field
20
+ from pydantic_settings import BaseSettings
21
+
22
+
23
+ # Constants for platform-specific directories
24
+ APP_NAME = "paname"
25
+
26
+ PACKAGE_PATH = Path(__file__).resolve().parent
27
+ SRC_PATH = PACKAGE_PATH.parent
28
+ PANAME_PATH = SRC_PATH.parent
29
+
30
+ EPSILON = 1e-15
31
+ DIV_EPSILON = 1e-6
32
+
33
+ # Use platformdir
34
+ _LOGS_PATH = PANAME_PATH / "logs"
35
+ _CACHE_PATH = Path(user_cache_dir(APP_NAME))
36
+ _HF_CACHE_DIR = _CACHE_PATH / "hf_cache"
37
+ _ONNX_CACHE_DIR = _CACHE_PATH / "onnx_cache"
38
+ _OUTPUT_PATH = Path(user_data_dir(APP_NAME)) / "output"
39
+
40
+ # Ensure directories exist
41
+ for path in [_CACHE_PATH, _OUTPUT_PATH]:
42
+ path.mkdir(parents=True, exist_ok=True)
43
+
44
+ DEFAULT_LOGGING_CONF_DICT = {
45
+ "version": 1,
46
+ "disable_existing_loggers": False,
47
+ "formatters": {
48
+ "simple": {
49
+ "class": "logging.Formatter",
50
+ "format": "%(asctime)s %(levelname)s [%(name)s] %(message)s",
51
+ "datefmt": "%Y/%m/%d %H:%M:%S",
52
+ }
53
+ },
54
+ "handlers": {
55
+ "console": {"class": "logging.StreamHandler", "formatter": "simple", "level": "INFO"},
56
+ },
57
+ "loggers": {
58
+ "paname": {"handlers": ["console"], "level": "INFO", "propagate": False},
59
+ },
60
+ }
61
+
62
+ DEFAULT_LOGGING_CONF = json.dumps(DEFAULT_LOGGING_CONF_DICT)
63
+
64
+
65
+ class Config(BaseSettings):
66
+ """Configuration settings for the application."""
67
+
68
+ logging_conf_str: str | None = Field(default=None, description="Opt-in logging configuration as a JSON string")
69
+
70
+
71
+ env_config = Config()
72
+
73
+
74
+ LogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
75
+ _owned_handlers: list[logging.Handler] = []
76
+
77
+
78
+ def configure_logging(level: LogLevel = "INFO", log_file: Path | None = None) -> None:
79
+ """Configure PANAME stderr and optional file output, leaving root handlers intact.
80
+
81
+ Repeated calls replace only handlers installed by this function. An explicit
82
+ ``LOGGING_CONF_STR`` environment setting instead applies a custom dictConfig;
83
+ that configuration takes precedence over ``level`` and ``log_file``.
84
+ """
85
+ logger = logging.getLogger("paname")
86
+ handlers: list[logging.Handler] = []
87
+ if env_config.logging_conf_str is None:
88
+ # Open the file before changing existing handlers, so failures preserve them.
89
+ if log_file is not None:
90
+ log_file.parent.mkdir(parents=True, exist_ok=True)
91
+ handlers.append(logging.FileHandler(log_file, encoding="utf-8"))
92
+ handlers.append(logging.StreamHandler())
93
+ formatter = logging.Formatter("%(asctime)s %(levelname)s [%(name)s] %(message)s", "%Y/%m/%d %H:%M:%S")
94
+ for handler in handlers:
95
+ handler.setFormatter(formatter)
96
+ handler.setLevel(level)
97
+
98
+ for handler in _owned_handlers:
99
+ logger.removeHandler(handler)
100
+ handler.close()
101
+ _owned_handlers.clear()
102
+
103
+ if env_config.logging_conf_str is not None:
104
+ logging.config.dictConfig(json.loads(env_config.logging_conf_str))
105
+ return
106
+
107
+ for handler in handlers:
108
+ logger.addHandler(handler)
109
+ _owned_handlers.extend(handlers)
110
+ logger.setLevel(level)
111
+ logger.propagate = False
@@ -0,0 +1,5 @@
1
+ # SPDX-FileCopyrightText: 2026 PANAME Consortium (ANSSI, CNIL, Inria and PEReN)
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Privacy extraction techniques implementations."""
@@ -0,0 +1,155 @@
1
+ # SPDX-FileCopyrightText: 2026 PANAME Consortium (ANSSI, CNIL, Inria and PEReN)
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Derived configuration dataclasses for extraction objects.
6
+
7
+ Every extraction object (MIA, reconstruction, discoverable-extraction) exposes
8
+ its CLI-tunable constructor defaults through the :meth:`Configurable._get_config`
9
+ classmethod, which returns a dataclass describing those sensible defaults. For
10
+ the simple case the dataclass is derived automatically from the constructor
11
+ signature (see :func:`_derive_config`); an object that needs custom control can
12
+ override :meth:`Configurable._get_config` to return a hand-written dataclass.
13
+
14
+ The constructor is the single source of truth: each *scalar* constructor
15
+ parameter with a default value becomes a dataclass field defaulting to the same
16
+ value. Runtime-injected dependencies (model wrappers, shadow pools, extractors,
17
+ evaluators, ...) are either default-less or object-typed, and are therefore
18
+ excluded automatically.
19
+ """
20
+
21
+ import inspect
22
+ import re
23
+ import types
24
+ from collections.abc import Mapping
25
+ from dataclasses import field, make_dataclass
26
+ from pathlib import Path
27
+ from typing import Any, ClassVar, Literal, TypeVar, Union, get_args, get_origin, get_type_hints
28
+
29
+ import numpy as np
30
+
31
+
32
+ #: Concrete types treated as scalar, CLI-tunable configuration values, as opposed
33
+ #: to object-typed runtime dependencies. ``None`` is included so ``T | None``
34
+ #: (an optional scalar) counts as scalar too.
35
+ _SCALAR_TYPES: tuple[type, ...] = (int, float, bool, str, Path, type(None), np.integer, np.floating, np.bool_)
36
+
37
+
38
+ def config_group_name(registry_key: str) -> str:
39
+ """Lowercase a registry key into a valid-identifier config group name.
40
+
41
+ Camel-case boundaries (``NoiseLabelOnly``) become underscores and any
42
+ run of non-alphanumeric characters is folded into a single underscore, so
43
+ the result is always usable as a dataclass field name. Tyro renders the
44
+ underscores back into kebab-case for CLI flags (``noise_label_only`` shows
45
+ up as ``--configs.noise-label-only.*``).
46
+
47
+ Note the acronym edge case ``LiRA`` deliberately splits to ``li_ra``: the
48
+ derivation is a pure slug, with no hand-written exceptions.
49
+ """
50
+ # Split camel-case boundaries, then normalise separators and case.
51
+ split = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", registry_key)
52
+ return re.sub(r"[^A-Za-z0-9]+", "_", split).strip("_").lower()
53
+
54
+
55
+ def _is_scalar(annotation: Any) -> bool:
56
+ """Return whether ``annotation`` denotes a scalar, CLI-tunable value.
57
+
58
+ Scalar types (or unions / optionals thereof, and ``Literal``) are kept;
59
+ object-typed runtime dependencies (protocols, wrappers, pools, extractors)
60
+ are excluded.
61
+ """
62
+ origin = get_origin(annotation)
63
+ args = get_args(annotation)
64
+ if args and origin in (types.UnionType, Union):
65
+ return all(_is_scalar(arg) for arg in args)
66
+ if args:
67
+ return origin is Literal
68
+ return isinstance(annotation, type) and issubclass(annotation, _SCALAR_TYPES)
69
+
70
+
71
+ def _derive_config(cls: type) -> type | None:
72
+ """Derive a ``Config`` dataclass from ``cls``'s constructor.
73
+
74
+ Every constructor parameter with a default value and a scalar type becomes a
75
+ dataclass field defaulting to the same value. Returns ``None`` when ``cls``
76
+ exposes no tunable constructor parameter.
77
+ """
78
+ try:
79
+ init_hints = {name: annotation for name, annotation in get_type_hints(cls.__init__).items() if name != "return"}
80
+ except (NameError, TypeError):
81
+ # An annotation could not be resolved (e.g. postponed or TYPE_CHECKING-only).
82
+ # Fall back to the raw signature annotation, which is then treated as
83
+ # non-scalar, so the parameter is simply excluded.
84
+ init_hints = {}
85
+
86
+ decls: list[tuple[str, Any, Any]] = []
87
+ for name, param in inspect.signature(cls.__init__).parameters.items():
88
+ if name == "self":
89
+ continue
90
+ if param.default is inspect.Parameter.empty:
91
+ continue
92
+ annotation = init_hints.get(name, param.annotation)
93
+ if isinstance(annotation, str) or not _is_scalar(annotation):
94
+ continue
95
+ # Scalar defaults are immutable, so they can be used directly as dataclass
96
+ # defaults without a default_factory.
97
+ decls.append((name, annotation, param.default))
98
+ if not decls:
99
+ return None
100
+ return make_dataclass(f"{cls.__name__}Config", decls)
101
+
102
+
103
+ class Configurable:
104
+ """Give an extraction object a CLI-tunable ``Config`` dataclass.
105
+
106
+ :meth:`_get_config` returns the object's ``Config`` dataclass holding its
107
+ sensible constructor defaults, derived automatically from the constructor
108
+ signature (see :func:`_derive_config`) and cached per class. An object that
109
+ needs custom control overrides this method and returns a hand-written
110
+ dataclass; the manual class always wins.
111
+ """
112
+
113
+ #: Per-class cache of the derived ``Config`` dataclass (``None`` when the
114
+ #: class exposes no tunable constructor parameter).
115
+ _config_cache: ClassVar[dict[type, type[Any] | None]] = {}
116
+
117
+ @classmethod
118
+ def _get_config(cls) -> type | None:
119
+ """Return the object's ``Config`` dataclass, or ``None`` if not tunable.
120
+
121
+ The dataclass is derived from the constructor and cached on first call.
122
+ Override this in a subclass to return a hand-written dataclass instead.
123
+ """
124
+ if cls not in cls._config_cache:
125
+ cls._config_cache[cls] = _derive_config(cls)
126
+ return cls._config_cache[cls]
127
+
128
+
129
+ _RegistryKey = TypeVar("_RegistryKey", bound=str)
130
+
131
+
132
+ def build_config_container(
133
+ registry: Mapping[_RegistryKey, tuple[type[Configurable], Any]],
134
+ container_name: str,
135
+ ) -> tuple[dict[str, str], type[Any]]:
136
+ """Build the ``--configs`` container for a techniques registry.
137
+
138
+ Given a ``*_REGISTRY`` mapping technique names to ``(class, kwargs)``, return
139
+ a pair ``(name_to_group, Configs)`` where ``name_to_group`` maps each tunable
140
+ technique to its group field name and ``Configs`` is a dataclass bundling
141
+ every tunable technique's derived ``Config`` (see :meth:`Configurable._get_config`).
142
+ Group names are slugged from the registry keys (see :func:`config_group_name`),
143
+ so ``Min-k-prob`` shows up as ``--configs.min-k-prob.*``. Techniques without a
144
+ tunable config are omitted.
145
+ """
146
+ group_names: dict[str, str] = {}
147
+ fields: list[tuple[str, type, Any]] = []
148
+ for name, (obj_class, _kwargs) in registry.items():
149
+ cfg = obj_class._get_config() # pylint: disable=protected-access
150
+ if cfg is None:
151
+ continue
152
+ group = config_group_name(name)
153
+ group_names[name] = group
154
+ fields.append((group, cfg, field(default_factory=cfg))) # pylint: disable=invalid-field-call
155
+ return group_names, make_dataclass(container_name, fields)
@@ -0,0 +1,20 @@
1
+ # SPDX-FileCopyrightText: 2026 PANAME Consortium (ANSSI, CNIL, Inria and PEReN)
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Probabilistic discoverable extraction of causal language model training data."""
6
+
7
+ from paname.extraction_techniques.discoverable_extraction.evaluation import (
8
+ DiscoverableExtraction,
9
+ )
10
+ from paname.extraction_techniques.discoverable_extraction.metrics import (
11
+ discoverable_extraction_rate,
12
+ is_discoverably_extractable,
13
+ )
14
+
15
+
16
+ __all__ = [
17
+ "DiscoverableExtraction",
18
+ "discoverable_extraction_rate",
19
+ "is_discoverably_extractable",
20
+ ]