ectype-data 0.1.0__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.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
|
@@ -0,0 +1,638 @@
|
|
|
1
|
+
"""Plug-in interface for learned (neural) joint models, and the escalation rule.
|
|
2
|
+
|
|
3
|
+
Safety model
|
|
4
|
+
------------
|
|
5
|
+
A learned model is stored as a **declared architecture** (a JSON config naming only
|
|
6
|
+
whitelisted layer types) plus **flat named weight arrays** in the fingerprint's ``arrays/``
|
|
7
|
+
(``.npy`` written with ``allow_pickle=False``). The names and layouts follow PyTorch
|
|
8
|
+
``nn.Sequential`` state-dict conventions (``"0.weight"``, ``"0.bias"``, ...), so the weights are
|
|
9
|
+
safetensors-compatible: a ``{name: array}`` mapping of plain numeric tensors. Every weight
|
|
10
|
+
array's SHA-256 is recorded in the spec params and verified when loading. Loading never
|
|
11
|
+
unpickles and never imports a class named by the data: the layer ``type`` strings are looked up
|
|
12
|
+
in a fixed table of NumPy implementations.
|
|
13
|
+
|
|
14
|
+
Generation runs the declared layers in NumPy, so PyTorch is not needed to *use* a model.
|
|
15
|
+
PyTorch is needed only to *train* one (:func:`train_with_torch`), via the optional
|
|
16
|
+
``[neural]`` extra.
|
|
17
|
+
|
|
18
|
+
* :class:`TorchModuleAdapter`: whitelisted config + weights; NumPy forward; optional
|
|
19
|
+
conversion to and from a ``torch.nn.Sequential``.
|
|
20
|
+
* :class:`TorchMLPFlow` (kind ``"torch_mlp_flow"``): a push-forward generator
|
|
21
|
+
``z = f(noise)`` through the declared MLP, re-standardised to N(0, 1) margins with a stored,
|
|
22
|
+
policy-coarsened quantile grid (atoms in the output, e.g. from dead ReLU regions, are spread
|
|
23
|
+
by a randomised PIT). Despite the name it is not an invertible flow; it is trained
|
|
24
|
+
by minimising the energy distance between generated and real latent scores.
|
|
25
|
+
* :func:`should_escalate`: use a learned model only if the sealed pass rate improves by at
|
|
26
|
+
least 2 percentage points and the measured privacy risk is not worse.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import hashlib
|
|
32
|
+
import math
|
|
33
|
+
import time
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
import numpy as np
|
|
37
|
+
from scipy import special
|
|
38
|
+
|
|
39
|
+
from ectype.errors import FingerprintError, IntegrityError
|
|
40
|
+
from ectype.fingerprint.core import ArrayStore
|
|
41
|
+
from ectype.fingerprint.disclosure import coarsen_array
|
|
42
|
+
from ectype.fingerprint.schema import DisclosurePolicySpec, ModelSpec
|
|
43
|
+
from ectype.models.base import JOINTS, JointModel
|
|
44
|
+
from ectype.models.copulas import _check_z
|
|
45
|
+
from ectype.rng import stream
|
|
46
|
+
|
|
47
|
+
NEURAL_HINT = "pip install ectype-data[neural]"
|
|
48
|
+
PRIVACY_WARNING = "learned model; run the privacy suite"
|
|
49
|
+
ALLOWED_LAYERS = ("Linear", "ReLU", "Tanh", "LayerNorm")
|
|
50
|
+
MAX_FEATURES = 4096
|
|
51
|
+
MAX_LAYERS = 64
|
|
52
|
+
GRID_SAMPLES = 20_000
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# ---------------------------------------------------------------------------------------------
|
|
56
|
+
# Hashing and safe array handling
|
|
57
|
+
# ---------------------------------------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
def array_sha256(a: np.ndarray) -> str:
|
|
60
|
+
"""SHA-256 of an array's little-endian bytes, its dtype and shape."""
|
|
61
|
+
a = np.asarray(a)
|
|
62
|
+
a = np.ascontiguousarray(a, dtype=a.dtype.newbyteorder("<"))
|
|
63
|
+
h = hashlib.sha256()
|
|
64
|
+
h.update(f"{a.dtype.str}|{list(a.shape)}|".encode())
|
|
65
|
+
h.update(a.tobytes())
|
|
66
|
+
return h.hexdigest()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def put_hashed(store: ArrayStore, prefix: str, name: str, a: np.ndarray, dtype: str,
|
|
70
|
+
arrays: dict[str, str], hashes: dict[str, str]) -> None:
|
|
71
|
+
arr = np.ascontiguousarray(a, dtype=dtype)
|
|
72
|
+
arrays[name] = store.put(f"{prefix}{name}", arr)
|
|
73
|
+
hashes[name] = array_sha256(arr)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_verified(spec: ModelSpec, store: ArrayStore, name: str, dtype: str) -> np.ndarray:
|
|
77
|
+
"""Fetch an array named in ``spec`` and check its dtype, finiteness and recorded hash."""
|
|
78
|
+
hashes = spec.params.get("weight_hashes")
|
|
79
|
+
if not isinstance(hashes, dict) or name not in hashes:
|
|
80
|
+
raise IntegrityError(f"{spec.kind}: no recorded hash for array {name!r}")
|
|
81
|
+
ref = spec.arrays.get(name)
|
|
82
|
+
if ref is None or ref not in store:
|
|
83
|
+
raise IntegrityError(f"{spec.kind}: array {name!r} is missing")
|
|
84
|
+
a = np.asarray(store.get(ref))
|
|
85
|
+
if a.dtype != np.dtype(dtype):
|
|
86
|
+
raise IntegrityError(f"{spec.kind}: array {name!r} has dtype {a.dtype}, "
|
|
87
|
+
f"declared {dtype}")
|
|
88
|
+
if array_sha256(a) != hashes[name]:
|
|
89
|
+
raise IntegrityError(f"{spec.kind}: SHA-256 mismatch for array {name!r} "
|
|
90
|
+
"(weights were modified after the fingerprint was written)")
|
|
91
|
+
if not np.all(np.isfinite(a)):
|
|
92
|
+
raise IntegrityError(f"{spec.kind}: array {name!r} contains non-finite values")
|
|
93
|
+
return a
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# ---------------------------------------------------------------------------------------------
|
|
97
|
+
# Re-standardisation to N(0, 1) margins via a stored quantile grid
|
|
98
|
+
# ---------------------------------------------------------------------------------------------
|
|
99
|
+
|
|
100
|
+
def grid_levels(policy: DisclosurePolicySpec) -> np.ndarray:
|
|
101
|
+
m = int(min(max(policy.quantile_resolution, 20), 1000))
|
|
102
|
+
return (np.arange(m) + 0.5) / m
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def make_grid(raw: np.ndarray, policy: DisclosurePolicySpec, *, strict: bool = True
|
|
106
|
+
) -> np.ndarray:
|
|
107
|
+
"""(m, d) policy-coarsened quantile grid of raw model output.
|
|
108
|
+
|
|
109
|
+
``strict=True`` nudges repeated values apart so the grid is strictly increasing (needed
|
|
110
|
+
for the inverse map of a continuous model). ``strict=False`` keeps ties, so atoms in the
|
|
111
|
+
raw output (e.g. dead ReLU regions of a push-forward generator) stay visible to
|
|
112
|
+
:func:`to_normal`, which spreads them with a randomised PIT.
|
|
113
|
+
"""
|
|
114
|
+
levels = grid_levels(policy)
|
|
115
|
+
g = coarsen_array(np.quantile(raw, levels, axis=0), policy)
|
|
116
|
+
g = np.maximum.accumulate(np.asarray(g, dtype=np.float64).reshape(len(levels),
|
|
117
|
+
raw.shape[1]), axis=0)
|
|
118
|
+
if strict:
|
|
119
|
+
for j in range(g.shape[1]):
|
|
120
|
+
col = g[:, j]
|
|
121
|
+
for i in range(1, len(col)):
|
|
122
|
+
floor = col[i - 1] + 1e-9 * max(1.0, abs(col[i - 1]))
|
|
123
|
+
if col[i] < floor:
|
|
124
|
+
col[i] = floor
|
|
125
|
+
g[:, j] = col
|
|
126
|
+
return g
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _interp_extrap(x: np.ndarray, xp: np.ndarray, fp: np.ndarray) -> np.ndarray:
|
|
130
|
+
"""Piecewise-linear interpolation with linear extrapolation using the end slopes."""
|
|
131
|
+
y = np.interp(x, xp, fp)
|
|
132
|
+
lo_slope = (fp[1] - fp[0]) / (xp[1] - xp[0])
|
|
133
|
+
hi_slope = (fp[-1] - fp[-2]) / (xp[-1] - xp[-2])
|
|
134
|
+
y = np.where(x < xp[0], fp[0] + (x - xp[0]) * lo_slope, y)
|
|
135
|
+
return np.where(x > xp[-1], fp[-1] + (x - xp[-1]) * hi_slope, y)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _to_normal_1d(x: np.ndarray, g: np.ndarray, u: np.ndarray | None,
|
|
139
|
+
atom_rtol: float) -> np.ndarray:
|
|
140
|
+
m = len(g)
|
|
141
|
+
p = (np.arange(m) + 0.5) / m
|
|
142
|
+
vals, first, counts = np.unique(g, return_index=True, return_counts=True)
|
|
143
|
+
# each distinct grid value sits at the mean level of its run
|
|
144
|
+
q_vals = special.ndtri(np.array([p[f:f + c].mean() for f, c in zip(first, counts)]))
|
|
145
|
+
if len(vals) >= 2:
|
|
146
|
+
out = _interp_extrap(x, vals, q_vals)
|
|
147
|
+
else:
|
|
148
|
+
out = np.zeros(len(x))
|
|
149
|
+
for v, f, c in zip(vals, first, counts):
|
|
150
|
+
if c < 2:
|
|
151
|
+
continue
|
|
152
|
+
hit = np.abs(x - v) <= atom_rtol * max(abs(v), 1e-12) + 1e-12
|
|
153
|
+
if not hit.any():
|
|
154
|
+
continue
|
|
155
|
+
lo, hi = p[f] - 0.5 / m, p[f + c - 1] + 0.5 / m
|
|
156
|
+
w = u[hit] if u is not None else np.full(int(hit.sum()), 0.5)
|
|
157
|
+
out[hit] = special.ndtri(lo + w * (hi - lo))
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def to_normal(x: np.ndarray, grid: np.ndarray, u: np.ndarray | None = None,
|
|
162
|
+
atom_rtol: float = 1e-5) -> np.ndarray:
|
|
163
|
+
"""Map raw model output to N(0, 1) margins: empirical CDF on the grid, then Phi^-1
|
|
164
|
+
(interpolated in normal-score space so the tails stay smooth).
|
|
165
|
+
|
|
166
|
+
Tied grid values mark an atom; raw values within ``atom_rtol`` (relative) of it are spread
|
|
167
|
+
uniformly over the atom's probability range using ``u`` (uniforms shaped like ``x``), or put
|
|
168
|
+
at its midpoint if ``u`` is ``None``.
|
|
169
|
+
"""
|
|
170
|
+
out = np.column_stack([
|
|
171
|
+
_to_normal_1d(x[:, j], grid[:, j], None if u is None else u[:, j], atom_rtol)
|
|
172
|
+
for j in range(x.shape[1])])
|
|
173
|
+
return np.clip(out, -38.0, 38.0)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def from_normal(z: np.ndarray, grid: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
177
|
+
"""Inverse of :func:`to_normal`. Returns ``(x, log|dx/dz| summed over columns)``."""
|
|
178
|
+
q = special.ndtri((np.arange(len(grid)) + 0.5) / len(grid))
|
|
179
|
+
x = np.column_stack([_interp_extrap(z[:, j], q, grid[:, j]) for j in range(z.shape[1])])
|
|
180
|
+
logjac = np.zeros(len(z))
|
|
181
|
+
for j in range(z.shape[1]):
|
|
182
|
+
slopes = np.diff(grid[:, j]) / np.diff(q)
|
|
183
|
+
idx = np.clip(np.searchsorted(q, z[:, j]) - 1, 0, len(slopes) - 1)
|
|
184
|
+
logjac += np.log(slopes[idx])
|
|
185
|
+
return x, logjac
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# ---------------------------------------------------------------------------------------------
|
|
189
|
+
# Declared architecture and NumPy forward pass
|
|
190
|
+
# ---------------------------------------------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
def _pos_int(v: Any, what: str) -> int:
|
|
193
|
+
if isinstance(v, bool) or not isinstance(v, int) or not 1 <= v <= MAX_FEATURES:
|
|
194
|
+
raise FingerprintError(f"{what} must be an integer in [1, {MAX_FEATURES}], got {v!r}")
|
|
195
|
+
return v
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def validate_config(config: Any) -> list[dict[str, Any]]:
|
|
199
|
+
"""Validate a declared architecture and return its normalised layer list.
|
|
200
|
+
|
|
201
|
+
``config = {"layers": [{"type": "Linear", "in_features": 4, "out_features": 8,
|
|
202
|
+
"bias": true}, {"type": "Tanh"}, {"type": "LayerNorm", "normalized_shape": 8,
|
|
203
|
+
"eps": 1e-5, "elementwise_affine": true}, ...]}``. Only ``Linear``, ``ReLU``, ``Tanh``
|
|
204
|
+
and ``LayerNorm`` are accepted; unknown types or keys raise ``FingerprintError``.
|
|
205
|
+
"""
|
|
206
|
+
if not isinstance(config, dict) or set(config) != {"layers"}:
|
|
207
|
+
raise FingerprintError("architecture config must be {'layers': [...]}")
|
|
208
|
+
layers = config["layers"]
|
|
209
|
+
if not isinstance(layers, list) or not 1 <= len(layers) <= MAX_LAYERS:
|
|
210
|
+
raise FingerprintError(f"architecture needs 1..{MAX_LAYERS} layers")
|
|
211
|
+
out: list[dict[str, Any]] = []
|
|
212
|
+
width: int | None = None
|
|
213
|
+
for i, layer in enumerate(layers):
|
|
214
|
+
if not isinstance(layer, dict) or not isinstance(layer.get("type"), str):
|
|
215
|
+
raise FingerprintError(f"layer {i} must be a dict with a string 'type'")
|
|
216
|
+
t = layer["type"]
|
|
217
|
+
if t not in ALLOWED_LAYERS:
|
|
218
|
+
raise FingerprintError(f"layer {i}: type {t!r} is not allowed; "
|
|
219
|
+
f"whitelist is {list(ALLOWED_LAYERS)}")
|
|
220
|
+
if t == "Linear":
|
|
221
|
+
extra = set(layer) - {"type", "in_features", "out_features", "bias"}
|
|
222
|
+
fin = _pos_int(layer.get("in_features"), f"layer {i} in_features")
|
|
223
|
+
fout = _pos_int(layer.get("out_features"), f"layer {i} out_features")
|
|
224
|
+
bias = layer.get("bias", True)
|
|
225
|
+
if not isinstance(bias, bool):
|
|
226
|
+
raise FingerprintError(f"layer {i}: bias must be a bool")
|
|
227
|
+
if width is not None and fin != width:
|
|
228
|
+
raise FingerprintError(f"layer {i}: in_features {fin} != previous width {width}")
|
|
229
|
+
norm = {"type": t, "in_features": fin, "out_features": fout, "bias": bias}
|
|
230
|
+
width = fout
|
|
231
|
+
elif t == "LayerNorm":
|
|
232
|
+
extra = set(layer) - {"type", "normalized_shape", "eps", "elementwise_affine"}
|
|
233
|
+
ns = layer.get("normalized_shape")
|
|
234
|
+
if isinstance(ns, list) and len(ns) == 1:
|
|
235
|
+
ns = ns[0]
|
|
236
|
+
ns = _pos_int(ns, f"layer {i} normalized_shape")
|
|
237
|
+
eps = layer.get("eps", 1e-5)
|
|
238
|
+
if isinstance(eps, bool) or not isinstance(eps, int | float) or not 0 < eps < 1:
|
|
239
|
+
raise FingerprintError(f"layer {i}: eps must be a float in (0, 1)")
|
|
240
|
+
aff = layer.get("elementwise_affine", True)
|
|
241
|
+
if not isinstance(aff, bool):
|
|
242
|
+
raise FingerprintError(f"layer {i}: elementwise_affine must be a bool")
|
|
243
|
+
if width is not None and ns != width:
|
|
244
|
+
raise FingerprintError(f"layer {i}: normalized_shape {ns} != width {width}")
|
|
245
|
+
norm = {"type": t, "normalized_shape": ns, "eps": float(eps),
|
|
246
|
+
"elementwise_affine": aff}
|
|
247
|
+
width = ns
|
|
248
|
+
else:
|
|
249
|
+
extra = set(layer) - {"type"}
|
|
250
|
+
norm = {"type": t}
|
|
251
|
+
if extra:
|
|
252
|
+
raise FingerprintError(f"layer {i} ({t}): unknown keys {sorted(extra)}")
|
|
253
|
+
out.append(norm)
|
|
254
|
+
if not any(layer["type"] == "Linear" for layer in out):
|
|
255
|
+
raise FingerprintError("architecture needs at least one Linear layer")
|
|
256
|
+
return out
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class TorchModuleAdapter:
|
|
260
|
+
"""A declared ``nn.Sequential``-style MLP with flat, safetensors-compatible weights.
|
|
261
|
+
|
|
262
|
+
Weight names and layouts follow the PyTorch state dict of ``nn.Sequential``: Linear layer
|
|
263
|
+
``i`` has ``"{i}.weight"`` of shape ``(out, in)`` and ``"{i}.bias"`` of shape ``(out,)``;
|
|
264
|
+
LayerNorm ``i`` has ``"{i}.weight"`` and ``"{i}.bias"`` of shape ``(n,)``. Weights are
|
|
265
|
+
held as float32 (the storage dtype) and computed in float64.
|
|
266
|
+
"""
|
|
267
|
+
|
|
268
|
+
def __init__(self, config: dict[str, Any], weights: dict[str, np.ndarray]) -> None:
|
|
269
|
+
self.layers = validate_config(config)
|
|
270
|
+
expected = self.expected_shapes(self.layers)
|
|
271
|
+
if set(weights) != set(expected):
|
|
272
|
+
missing = sorted(set(expected) - set(weights))
|
|
273
|
+
extra = sorted(set(weights) - set(expected))
|
|
274
|
+
raise FingerprintError(f"weights do not match the architecture "
|
|
275
|
+
f"(missing {missing}, unexpected {extra})")
|
|
276
|
+
self.weights: dict[str, np.ndarray] = {}
|
|
277
|
+
for name, shape in expected.items():
|
|
278
|
+
a = np.asarray(weights[name], dtype=np.float32)
|
|
279
|
+
if a.shape != shape:
|
|
280
|
+
raise FingerprintError(f"weight {name!r} has shape {a.shape}, expected {shape}")
|
|
281
|
+
if not np.all(np.isfinite(a)):
|
|
282
|
+
raise FingerprintError(f"weight {name!r} contains non-finite values")
|
|
283
|
+
self.weights[name] = a
|
|
284
|
+
|
|
285
|
+
@property
|
|
286
|
+
def config(self) -> dict[str, Any]:
|
|
287
|
+
return {"layers": [dict(layer) for layer in self.layers]}
|
|
288
|
+
|
|
289
|
+
@property
|
|
290
|
+
def in_features(self) -> int:
|
|
291
|
+
first = next(la for la in self.layers if la["type"] in ("Linear", "LayerNorm"))
|
|
292
|
+
return int(first["in_features"] if first["type"] == "Linear"
|
|
293
|
+
else first["normalized_shape"])
|
|
294
|
+
|
|
295
|
+
@property
|
|
296
|
+
def out_features(self) -> int:
|
|
297
|
+
last = [la for la in self.layers if la["type"] in ("Linear", "LayerNorm")][-1]
|
|
298
|
+
return int(last["out_features"] if last["type"] == "Linear"
|
|
299
|
+
else last["normalized_shape"])
|
|
300
|
+
|
|
301
|
+
@property
|
|
302
|
+
def n_parameters(self) -> int:
|
|
303
|
+
return int(sum(a.size for a in self.weights.values()))
|
|
304
|
+
|
|
305
|
+
@staticmethod
|
|
306
|
+
def expected_shapes(layers: list[dict[str, Any]]) -> dict[str, tuple[int, ...]]:
|
|
307
|
+
shapes: dict[str, tuple[int, ...]] = {}
|
|
308
|
+
for i, layer in enumerate(layers):
|
|
309
|
+
if layer["type"] == "Linear":
|
|
310
|
+
shapes[f"{i}.weight"] = (layer["out_features"], layer["in_features"])
|
|
311
|
+
if layer["bias"]:
|
|
312
|
+
shapes[f"{i}.bias"] = (layer["out_features"],)
|
|
313
|
+
elif layer["type"] == "LayerNorm" and layer["elementwise_affine"]:
|
|
314
|
+
shapes[f"{i}.weight"] = (layer["normalized_shape"],)
|
|
315
|
+
shapes[f"{i}.bias"] = (layer["normalized_shape"],)
|
|
316
|
+
return shapes
|
|
317
|
+
|
|
318
|
+
def forward(self, x: np.ndarray) -> np.ndarray:
|
|
319
|
+
"""Run the declared layers in NumPy (float64)."""
|
|
320
|
+
h = np.asarray(x, dtype=np.float64)
|
|
321
|
+
if h.ndim != 2 or h.shape[1] != self.in_features:
|
|
322
|
+
raise ValueError(f"input shape {h.shape} does not match in_features "
|
|
323
|
+
f"{self.in_features}")
|
|
324
|
+
for i, layer in enumerate(self.layers):
|
|
325
|
+
t = layer["type"]
|
|
326
|
+
if t == "Linear":
|
|
327
|
+
h = h @ self.weights[f"{i}.weight"].astype(np.float64).T
|
|
328
|
+
if layer["bias"]:
|
|
329
|
+
h = h + self.weights[f"{i}.bias"].astype(np.float64)
|
|
330
|
+
elif t == "ReLU":
|
|
331
|
+
h = np.maximum(h, 0.0)
|
|
332
|
+
elif t == "Tanh":
|
|
333
|
+
h = np.tanh(h)
|
|
334
|
+
else: # LayerNorm (biased variance, as in torch)
|
|
335
|
+
mu = h.mean(axis=1, keepdims=True)
|
|
336
|
+
var = h.var(axis=1, keepdims=True)
|
|
337
|
+
h = (h - mu) / np.sqrt(var + layer["eps"])
|
|
338
|
+
if layer["elementwise_affine"]:
|
|
339
|
+
h = (h * self.weights[f"{i}.weight"].astype(np.float64)
|
|
340
|
+
+ self.weights[f"{i}.bias"].astype(np.float64))
|
|
341
|
+
return h
|
|
342
|
+
|
|
343
|
+
__call__ = forward
|
|
344
|
+
|
|
345
|
+
# -- serialisation ------------------------------------------------------------------------
|
|
346
|
+
def to_arrays(self, store: ArrayStore, prefix: str) -> tuple[dict[str, Any], dict[str, str]]:
|
|
347
|
+
"""Write weights (float32) to ``store``. Returns ``(params, arrays)`` for a spec."""
|
|
348
|
+
arrays: dict[str, str] = {}
|
|
349
|
+
hashes: dict[str, str] = {}
|
|
350
|
+
for name, a in self.weights.items():
|
|
351
|
+
put_hashed(store, prefix, f"w.{name}", a, "<f4", arrays, hashes)
|
|
352
|
+
return {"architecture": self.config, "weight_hashes": hashes}, arrays
|
|
353
|
+
|
|
354
|
+
@classmethod
|
|
355
|
+
def from_arrays(cls, spec: ModelSpec, store: ArrayStore) -> TorchModuleAdapter:
|
|
356
|
+
config = spec.params.get("architecture")
|
|
357
|
+
layers = validate_config(config)
|
|
358
|
+
weights = {name: get_verified(spec, store, f"w.{name}", "<f4")
|
|
359
|
+
for name in cls.expected_shapes(layers)}
|
|
360
|
+
return cls({"layers": layers}, weights)
|
|
361
|
+
|
|
362
|
+
# -- PyTorch interop (optional) -----------------------------------------------------------
|
|
363
|
+
def to_torch(self) -> Any:
|
|
364
|
+
"""Build a ``torch.nn.Sequential`` with these weights (requires torch)."""
|
|
365
|
+
torch = require_torch()
|
|
366
|
+
nn = torch.nn
|
|
367
|
+
mods: list[Any] = []
|
|
368
|
+
for layer in self.layers:
|
|
369
|
+
t = layer["type"]
|
|
370
|
+
if t == "Linear":
|
|
371
|
+
mods.append(nn.Linear(layer["in_features"], layer["out_features"],
|
|
372
|
+
bias=layer["bias"]))
|
|
373
|
+
elif t == "ReLU":
|
|
374
|
+
mods.append(nn.ReLU())
|
|
375
|
+
elif t == "Tanh":
|
|
376
|
+
mods.append(nn.Tanh())
|
|
377
|
+
else:
|
|
378
|
+
mods.append(nn.LayerNorm(layer["normalized_shape"], eps=layer["eps"],
|
|
379
|
+
elementwise_affine=layer["elementwise_affine"]))
|
|
380
|
+
seq = nn.Sequential(*mods)
|
|
381
|
+
state = {k: torch.from_numpy(np.array(v, dtype=np.float32))
|
|
382
|
+
for k, v in self.weights.items()}
|
|
383
|
+
seq.load_state_dict(state, strict=True)
|
|
384
|
+
return seq
|
|
385
|
+
|
|
386
|
+
@classmethod
|
|
387
|
+
def from_torch(cls, module: Any) -> TorchModuleAdapter:
|
|
388
|
+
"""Declare a ``torch.nn.Sequential`` of whitelisted layers (requires torch)."""
|
|
389
|
+
torch = require_torch()
|
|
390
|
+
nn = torch.nn
|
|
391
|
+
if not isinstance(module, nn.Sequential):
|
|
392
|
+
raise FingerprintError("only torch.nn.Sequential modules can be declared")
|
|
393
|
+
layers: list[dict[str, Any]] = []
|
|
394
|
+
for i, m in enumerate(module):
|
|
395
|
+
if type(m) is nn.Linear:
|
|
396
|
+
layers.append({"type": "Linear", "in_features": m.in_features,
|
|
397
|
+
"out_features": m.out_features, "bias": m.bias is not None})
|
|
398
|
+
elif type(m) is nn.ReLU:
|
|
399
|
+
layers.append({"type": "ReLU"})
|
|
400
|
+
elif type(m) is nn.Tanh:
|
|
401
|
+
layers.append({"type": "Tanh"})
|
|
402
|
+
elif type(m) is nn.LayerNorm:
|
|
403
|
+
layers.append({"type": "LayerNorm",
|
|
404
|
+
"normalized_shape": int(m.normalized_shape[0]),
|
|
405
|
+
"eps": float(m.eps),
|
|
406
|
+
"elementwise_affine": bool(m.elementwise_affine)})
|
|
407
|
+
else:
|
|
408
|
+
raise FingerprintError(f"layer {i}: {type(m).__name__} is not whitelisted "
|
|
409
|
+
f"({list(ALLOWED_LAYERS)})")
|
|
410
|
+
weights = {k: v.detach().cpu().numpy().astype(np.float32)
|
|
411
|
+
for k, v in module.state_dict().items()}
|
|
412
|
+
return cls({"layers": layers}, weights)
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def require_torch() -> Any:
|
|
416
|
+
try:
|
|
417
|
+
import torch
|
|
418
|
+
except ImportError as e:
|
|
419
|
+
raise ImportError(f"PyTorch is required to train neural generators: {NEURAL_HINT}"
|
|
420
|
+
) from e
|
|
421
|
+
return torch
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def mlp_config(in_features: int, out_features: int, hidden: int = 32, n_hidden: int = 2,
|
|
425
|
+
activation: str = "Tanh") -> dict[str, Any]:
|
|
426
|
+
"""A declared MLP ``in -> hidden (x n_hidden, with activation) -> out``."""
|
|
427
|
+
if activation not in ("Tanh", "ReLU"):
|
|
428
|
+
raise ValueError("activation must be 'Tanh' or 'ReLU'")
|
|
429
|
+
layers: list[dict[str, Any]] = []
|
|
430
|
+
width = in_features
|
|
431
|
+
for _ in range(n_hidden):
|
|
432
|
+
layers += [{"type": "Linear", "in_features": width, "out_features": hidden,
|
|
433
|
+
"bias": True}, {"type": activation}]
|
|
434
|
+
width = hidden
|
|
435
|
+
layers.append({"type": "Linear", "in_features": width, "out_features": out_features,
|
|
436
|
+
"bias": True})
|
|
437
|
+
return {"layers": layers}
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def train_with_torch(z: np.ndarray, config: dict[str, Any] | None = None, *, noise_dim: int,
|
|
441
|
+
seed: int = 0, epochs: int = 300, batch_size: int = 512,
|
|
442
|
+
lr: float = 1e-3, time_limit: float = 60.0) -> TorchModuleAdapter:
|
|
443
|
+
"""Train a push-forward MLP ``f: noise -> z`` by minimising the energy distance between
|
|
444
|
+
``f(noise)`` and mini-batches of ``z`` (requires torch; CPU, deterministic seed).
|
|
445
|
+
|
|
446
|
+
Raises ``ImportError`` with an install hint if torch is not installed.
|
|
447
|
+
"""
|
|
448
|
+
torch = require_torch()
|
|
449
|
+
z = np.asarray(z, dtype=np.float64)
|
|
450
|
+
d = z.shape[1]
|
|
451
|
+
config = config or mlp_config(noise_dim, d)
|
|
452
|
+
layers = validate_config(config)
|
|
453
|
+
init_rng = stream(seed, "torch_mlp_flow", "init")
|
|
454
|
+
adapter = TorchModuleAdapter({"layers": layers}, {
|
|
455
|
+
name: init_rng.normal(0.0, 1.0 / math.sqrt(max(shape[-1], 1)), size=shape)
|
|
456
|
+
if not name.endswith("bias") else np.zeros(shape)
|
|
457
|
+
for name, shape in TorchModuleAdapter.expected_shapes(layers).items()})
|
|
458
|
+
for i, la in enumerate(layers): # LayerNorm scale starts at 1
|
|
459
|
+
if la["type"] == "LayerNorm" and la["elementwise_affine"]:
|
|
460
|
+
adapter.weights[f"{i}.weight"][:] = 1.0
|
|
461
|
+
if adapter.in_features != noise_dim or adapter.out_features != d:
|
|
462
|
+
raise ValueError("architecture must map noise_dim -> number of latent columns")
|
|
463
|
+
torch.manual_seed(int(stream(seed, "torch_mlp_flow", "torch").integers(2**31)))
|
|
464
|
+
module = adapter.to_torch().double()
|
|
465
|
+
opt = torch.optim.Adam(module.parameters(), lr=lr)
|
|
466
|
+
data = torch.from_numpy(z)
|
|
467
|
+
rng = stream(seed, "torch_mlp_flow", "batches")
|
|
468
|
+
t0 = time.monotonic()
|
|
469
|
+
bs = min(batch_size, len(z))
|
|
470
|
+
for _ in range(epochs):
|
|
471
|
+
perm = rng.permutation(len(z))
|
|
472
|
+
for s in range(0, len(z) - bs + 1, bs):
|
|
473
|
+
real = data[torch.from_numpy(perm[s:s + bs])]
|
|
474
|
+
noise = torch.from_numpy(rng.standard_normal((bs, noise_dim)))
|
|
475
|
+
fake = module(noise)
|
|
476
|
+
loss = (2 * torch.cdist(fake, real).mean() - torch.cdist(fake, fake).mean()
|
|
477
|
+
- torch.cdist(real, real).mean())
|
|
478
|
+
opt.zero_grad()
|
|
479
|
+
loss.backward()
|
|
480
|
+
opt.step()
|
|
481
|
+
if time.monotonic() - t0 >= time_limit:
|
|
482
|
+
break
|
|
483
|
+
return TorchModuleAdapter.from_torch(module.float())
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
# ---------------------------------------------------------------------------------------------
|
|
487
|
+
# Joint model: push-forward MLP declared through the adapter
|
|
488
|
+
# ---------------------------------------------------------------------------------------------
|
|
489
|
+
|
|
490
|
+
@JOINTS.register()
|
|
491
|
+
class TorchMLPFlow(JointModel):
|
|
492
|
+
"""``z = restandardise(f(noise))`` with ``f`` a declared, whitelisted MLP.
|
|
493
|
+
|
|
494
|
+
Sampling and loading need only NumPy; :meth:`fit` needs torch.
|
|
495
|
+
"""
|
|
496
|
+
|
|
497
|
+
kind = "torch_mlp_flow"
|
|
498
|
+
|
|
499
|
+
def __init__(self, columns: list[str], adapter: TorchModuleAdapter, grid: np.ndarray,
|
|
500
|
+
*, training: dict[str, Any] | None = None) -> None:
|
|
501
|
+
self.columns = list(columns)
|
|
502
|
+
self.adapter = adapter
|
|
503
|
+
self.noise_dim = adapter.in_features
|
|
504
|
+
if adapter.out_features != len(self.columns):
|
|
505
|
+
raise FingerprintError(f"architecture outputs {adapter.out_features} dims for "
|
|
506
|
+
f"{len(self.columns)} columns")
|
|
507
|
+
self.grid = np.asarray(grid, dtype=np.float64)
|
|
508
|
+
if self.grid.ndim != 2 or self.grid.shape[1] != len(self.columns) or \
|
|
509
|
+
len(self.grid) < 2 or np.any(np.diff(self.grid, axis=0) < 0):
|
|
510
|
+
raise FingerprintError("quantile grid must be (m >= 2, d) and non-decreasing")
|
|
511
|
+
self.training = dict(training or {})
|
|
512
|
+
|
|
513
|
+
@classmethod
|
|
514
|
+
def from_adapter(cls, columns: list[str], adapter: TorchModuleAdapter, *,
|
|
515
|
+
policy: DisclosurePolicySpec, seed: int = 0,
|
|
516
|
+
training: dict[str, Any] | None = None) -> TorchMLPFlow:
|
|
517
|
+
"""Wrap a (trained or hand-set) adapter, computing the re-standardisation grid."""
|
|
518
|
+
noise = stream(seed, "torch_mlp_flow", "grid").standard_normal(
|
|
519
|
+
(GRID_SAMPLES, adapter.in_features))
|
|
520
|
+
return cls(columns, adapter, make_grid(adapter.forward(noise), policy, strict=False),
|
|
521
|
+
training=training)
|
|
522
|
+
|
|
523
|
+
@classmethod
|
|
524
|
+
def fit(cls, z: np.ndarray, columns: list[str], *, policy: DisclosurePolicySpec,
|
|
525
|
+
rng: np.random.Generator | None = None, config: dict[str, Any] | None = None,
|
|
526
|
+
noise_dim: int | None = None, epochs: int = 300, time_limit: float = 60.0,
|
|
527
|
+
**kwargs: Any) -> TorchMLPFlow:
|
|
528
|
+
z = _check_z(z, columns)
|
|
529
|
+
rng = rng if rng is not None else np.random.default_rng(0)
|
|
530
|
+
seed = int(rng.integers(2**63 - 1))
|
|
531
|
+
nd = int(noise_dim or max(2, z.shape[1]))
|
|
532
|
+
adapter = train_with_torch(z, config, noise_dim=nd, seed=seed, epochs=epochs,
|
|
533
|
+
time_limit=time_limit)
|
|
534
|
+
return cls.from_adapter(columns, adapter, policy=policy, seed=seed,
|
|
535
|
+
training={"epochs": epochs, "seed": seed})
|
|
536
|
+
|
|
537
|
+
def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
|
|
538
|
+
if not self.columns:
|
|
539
|
+
return np.zeros((n, 0))
|
|
540
|
+
noise = rng.standard_normal((n, self.noise_dim))
|
|
541
|
+
u = rng.random((n, len(self.columns))) # randomised PIT for atoms
|
|
542
|
+
return to_normal(self.adapter.forward(noise), self.grid, u)
|
|
543
|
+
|
|
544
|
+
@property
|
|
545
|
+
def n_parameters(self) -> int:
|
|
546
|
+
return self.adapter.n_parameters + self.grid.size
|
|
547
|
+
|
|
548
|
+
def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
|
|
549
|
+
params, arrays = self.adapter.to_arrays(store, prefix)
|
|
550
|
+
put_hashed(store, prefix, "grid", self.grid, "<f8", arrays, params["weight_hashes"])
|
|
551
|
+
params.update({"columns": list(self.columns), "noise_dim": self.noise_dim,
|
|
552
|
+
"training": self.training, "warnings": [PRIVACY_WARNING]})
|
|
553
|
+
return ModelSpec(kind=self.kind, params=params, arrays=arrays)
|
|
554
|
+
|
|
555
|
+
@classmethod
|
|
556
|
+
def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> TorchMLPFlow:
|
|
557
|
+
adapter = TorchModuleAdapter.from_arrays(spec, store)
|
|
558
|
+
cols = [str(c) for c in spec.params.get("columns", [])] # type: ignore[union-attr]
|
|
559
|
+
if spec.params.get("noise_dim") != adapter.in_features:
|
|
560
|
+
raise FingerprintError("noise_dim does not match the declared architecture")
|
|
561
|
+
grid = get_verified(spec, store, "grid", "<f8")
|
|
562
|
+
training = spec.params.get("training")
|
|
563
|
+
return cls(cols, adapter, grid,
|
|
564
|
+
training=training if isinstance(training, dict) else None)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
# ---------------------------------------------------------------------------------------------
|
|
568
|
+
# Escalation rule
|
|
569
|
+
# ---------------------------------------------------------------------------------------------
|
|
570
|
+
|
|
571
|
+
_RISK_ORDER = ("low", "elevated", "high")
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _sealed_pass_rate(report: dict[str, Any]) -> float | None:
|
|
575
|
+
sealed = (report.get("sections") or {}).get("sealed") or {}
|
|
576
|
+
rate = sealed.get("pass_rate")
|
|
577
|
+
if rate is None and sealed.get("n"):
|
|
578
|
+
rate = sealed.get("n_passed", 0) / sealed["n"]
|
|
579
|
+
return None if rate is None else float(rate)
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def _hard_failures(report: dict[str, Any]) -> int:
|
|
583
|
+
structural = sum(not c.get("passed", True) for c in report.get("structural", []))
|
|
584
|
+
hard = sum(c.get("severity") == "hard" and not c.get("passed", True)
|
|
585
|
+
for c in report.get("constraints", []))
|
|
586
|
+
return int(structural + hard)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def _risk(report: dict[str, Any] | None) -> str | None:
|
|
590
|
+
if report is None:
|
|
591
|
+
return None
|
|
592
|
+
lvl = report.get("risk_level")
|
|
593
|
+
if lvl not in _RISK_ORDER:
|
|
594
|
+
raise ValueError(f"privacy report has unknown risk_level {lvl!r}")
|
|
595
|
+
return str(lvl)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def should_escalate(fp_baseline_report: dict[str, Any], fp_neural_report: dict[str, Any],
|
|
599
|
+
privacy_report: dict[str, Any] | None = None, *,
|
|
600
|
+
baseline_privacy_report: dict[str, Any] | None = None,
|
|
601
|
+
min_gain: float = 0.02, require_privacy: bool = True
|
|
602
|
+
) -> tuple[bool, str]:
|
|
603
|
+
"""Decide whether a learned joint model should replace the statistical baseline.
|
|
604
|
+
|
|
605
|
+
``fp_baseline_report`` and ``fp_neural_report`` are ``ValidationReport.to_dict()``
|
|
606
|
+
outputs for data generated by the baseline and the learned model. ``privacy_report`` is
|
|
607
|
+
the ``PrivacyReport.to_dict()`` of the learned model's output; ``baseline_privacy_report``
|
|
608
|
+
optionally gives the baseline's. Returns ``(escalate, reason)``.
|
|
609
|
+
|
|
610
|
+
Escalate only if the **sealed** pass rate improves by at least ``min_gain`` (2 percentage
|
|
611
|
+
points) AND the privacy risk is not worse: not above the baseline's risk level when that is
|
|
612
|
+
given, otherwise ``"low"``. Without a privacy report the answer is no (learned models can
|
|
613
|
+
memorise), unless ``require_privacy=False``. A learned model that adds structural failures
|
|
614
|
+
or hard-constraint violations is never preferred.
|
|
615
|
+
"""
|
|
616
|
+
base_rate = _sealed_pass_rate(fp_baseline_report)
|
|
617
|
+
new_rate = _sealed_pass_rate(fp_neural_report)
|
|
618
|
+
if base_rate is None or new_rate is None:
|
|
619
|
+
return False, "no sealed targets to compare"
|
|
620
|
+
gain = new_rate - base_rate
|
|
621
|
+
if gain < min_gain - 1e-12:
|
|
622
|
+
return False, (f"sealed pass rate {base_rate:.1%} -> {new_rate:.1%} "
|
|
623
|
+
f"({gain * 100:+.1f} pp) is below the {min_gain * 100:.0f} pp threshold")
|
|
624
|
+
if _hard_failures(fp_neural_report) > _hard_failures(fp_baseline_report):
|
|
625
|
+
return False, "learned model adds structural failures or hard-constraint violations"
|
|
626
|
+
new_risk = _risk(privacy_report)
|
|
627
|
+
if new_risk is None:
|
|
628
|
+
if require_privacy:
|
|
629
|
+
return False, (f"sealed pass rate +{gain * 100:.1f} pp but no privacy report: "
|
|
630
|
+
"learned models can memorise; run the privacy suite")
|
|
631
|
+
privacy_note = "privacy not assessed"
|
|
632
|
+
else:
|
|
633
|
+
ref = _risk(baseline_privacy_report) or "low"
|
|
634
|
+
if _RISK_ORDER.index(new_risk) > _RISK_ORDER.index(ref):
|
|
635
|
+
return False, (f"privacy risk {new_risk!r} is worse than the baseline's {ref!r}")
|
|
636
|
+
privacy_note = f"privacy risk {new_risk!r} (baseline {ref!r})"
|
|
637
|
+
return True, (f"sealed pass rate {base_rate:.1%} -> {new_rate:.1%} "
|
|
638
|
+
f"(+{gain * 100:.1f} pp); {privacy_note}")
|