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,432 @@
|
|
|
1
|
+
"""Latent variational autoencoder (kind ``"latent_vae"``), pure NumPy.
|
|
2
|
+
|
|
3
|
+
A small VAE on the latent standard-normal scores ``z`` (n, d):
|
|
4
|
+
|
|
5
|
+
* **encoder** MLP ``d -> hidden (x n_layers, tanh/relu) -> (mu, log var)`` of a diagonal
|
|
6
|
+
Gaussian posterior over a ``latent_dim`` code ``c``;
|
|
7
|
+
* **decoder** MLP ``latent_dim -> hidden (x n_layers) -> mean`` with a learned, per-column
|
|
8
|
+
diagonal log variance (a Gaussian decoder);
|
|
9
|
+
* trained on the negative ELBO with the reparameterisation trick, hand-written backprop and a
|
|
10
|
+
hand-written Adam optimiser, in mini-batches with a KL warm-up. Early stopping uses the ELBO
|
|
11
|
+
of a held-out split (the best epoch's weights are kept). A wall-clock cap (default 60 s)
|
|
12
|
+
bounds training; if it triggers, the result depends on machine speed and ``params``
|
|
13
|
+
records ``stopped="time_cap"``. Every random draw comes from ``rng.stream`` children of
|
|
14
|
+
one seed taken from the supplied generator, so fits are deterministic otherwise.
|
|
15
|
+
|
|
16
|
+
Sampling draws ``c ~ N(0, I)``, decodes to ``mean + sigma * noise`` and then
|
|
17
|
+
**re-standardises** each column, like the mixture copula, through a stored empirical-CDF grid:
|
|
18
|
+
policy-coarsened quantiles of the raw decoder output, mapped to N(0, 1) by ``Phi^-1``
|
|
19
|
+
(interpolated in normal-score space). Output marginals are therefore N(0, 1) up to the grid
|
|
20
|
+
resolution, so the marginal models downstream are preserved exactly.
|
|
21
|
+
|
|
22
|
+
Storage: weights are float32 arrays in the ArrayStore, coarsened to the policy's significant
|
|
23
|
+
digits first; every array's SHA-256 is recorded in ``params["weight_hashes"]`` and verified by
|
|
24
|
+
:meth:`LatentVAE.from_spec`. Nothing is pickled.
|
|
25
|
+
|
|
26
|
+
Disclosure: a VAE can memorise training rows. Capacity is small by default (hidden width 32,
|
|
27
|
+
latent dim <= 4) and the spec carries the warning ``"learned model; run the privacy suite"``.
|
|
28
|
+
|
|
29
|
+
:meth:`LatentVAE.logpdf` is an **approximation**: an importance-weighted ELBO (IWAE bound,
|
|
30
|
+
``K`` samples) of the raw decoder density plus the log-Jacobian of the re-standardisation. It
|
|
31
|
+
is a lower bound in expectation and noisy; it is meant for ``recommend_joint``-style
|
|
32
|
+
comparisons only.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import math
|
|
38
|
+
import time
|
|
39
|
+
from typing import Any
|
|
40
|
+
|
|
41
|
+
import numpy as np
|
|
42
|
+
from scipy import special
|
|
43
|
+
|
|
44
|
+
from ectype.errors import FingerprintError
|
|
45
|
+
from ectype.fingerprint.core import ArrayStore
|
|
46
|
+
from ectype.fingerprint.disclosure import coarsen_array
|
|
47
|
+
from ectype.fingerprint.schema import DisclosurePolicySpec, ModelSpec
|
|
48
|
+
from ectype.models.base import JOINTS, JointModel
|
|
49
|
+
from ectype.models.copulas import _check_z
|
|
50
|
+
from ectype.models.neural.adapter import (
|
|
51
|
+
GRID_SAMPLES,
|
|
52
|
+
PRIVACY_WARNING,
|
|
53
|
+
from_normal,
|
|
54
|
+
get_verified,
|
|
55
|
+
make_grid,
|
|
56
|
+
put_hashed,
|
|
57
|
+
to_normal,
|
|
58
|
+
)
|
|
59
|
+
from ectype.rng import stream
|
|
60
|
+
|
|
61
|
+
LOG_2PI = math.log(2.0 * math.pi)
|
|
62
|
+
MAX_FIT_ROWS = 20_000
|
|
63
|
+
ACTIVATIONS = ("tanh", "relu")
|
|
64
|
+
LV_MIN, LV_MAX = -9.0, 5.0
|
|
65
|
+
|
|
66
|
+
Layers = list[tuple[np.ndarray, np.ndarray]]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ---------------------------------------------------------------------------------------------
|
|
70
|
+
# MLP forward / backward
|
|
71
|
+
# ---------------------------------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
def _act(a: np.ndarray, kind: str) -> np.ndarray:
|
|
74
|
+
return np.tanh(a) if kind == "tanh" else np.maximum(a, 0.0)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _act_grad(a: np.ndarray, h: np.ndarray, kind: str) -> np.ndarray:
|
|
78
|
+
return 1.0 - h * h if kind == "tanh" else (a > 0).astype(a.dtype)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _mlp_forward(layers: Layers, x: np.ndarray, act: str
|
|
82
|
+
) -> tuple[np.ndarray, list[tuple[np.ndarray, np.ndarray, np.ndarray]]]:
|
|
83
|
+
"""Hidden layers use ``act``; the last layer is linear. Cache: (input, pre, post)."""
|
|
84
|
+
cache = []
|
|
85
|
+
h = x
|
|
86
|
+
for i, (w, b) in enumerate(layers):
|
|
87
|
+
a = h @ w + b
|
|
88
|
+
post = _act(a, act) if i < len(layers) - 1 else a
|
|
89
|
+
cache.append((h, a, post))
|
|
90
|
+
h = post
|
|
91
|
+
return h, cache
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _mlp_backward(layers: Layers, cache: list[tuple[np.ndarray, np.ndarray, np.ndarray]],
|
|
95
|
+
dout: np.ndarray, act: str) -> tuple[Layers, np.ndarray]:
|
|
96
|
+
grads: Layers = [(np.empty(0), np.empty(0))] * len(layers)
|
|
97
|
+
g = dout
|
|
98
|
+
for i in range(len(layers) - 1, -1, -1):
|
|
99
|
+
h_in, a, post = cache[i]
|
|
100
|
+
if i < len(layers) - 1:
|
|
101
|
+
g = g * _act_grad(a, post, act)
|
|
102
|
+
grads[i] = (h_in.T @ g, g.sum(axis=0))
|
|
103
|
+
g = g @ layers[i][0].T
|
|
104
|
+
return grads, g
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _init_layers(sizes: list[int], rng: np.random.Generator) -> Layers:
|
|
108
|
+
return [(rng.normal(0.0, math.sqrt(1.0 / fin), size=(fin, fout)), np.zeros(fout))
|
|
109
|
+
for fin, fout in zip(sizes[:-1], sizes[1:])]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class _Adam:
|
|
113
|
+
def __init__(self, params: list[np.ndarray], lr: float, b1: float = 0.9,
|
|
114
|
+
b2: float = 0.999, eps: float = 1e-8) -> None:
|
|
115
|
+
self.lr, self.b1, self.b2, self.eps = lr, b1, b2, eps
|
|
116
|
+
self.m = [np.zeros_like(p) for p in params]
|
|
117
|
+
self.v = [np.zeros_like(p) for p in params]
|
|
118
|
+
self.t = 0
|
|
119
|
+
|
|
120
|
+
def step(self, params: list[np.ndarray], grads: list[np.ndarray]) -> None:
|
|
121
|
+
self.t += 1
|
|
122
|
+
c1 = 1.0 - self.b1 ** self.t
|
|
123
|
+
c2 = 1.0 - self.b2 ** self.t
|
|
124
|
+
for p, g, m, v in zip(params, grads, self.m, self.v):
|
|
125
|
+
m *= self.b1
|
|
126
|
+
m += (1.0 - self.b1) * g
|
|
127
|
+
v *= self.b2
|
|
128
|
+
v += (1.0 - self.b2) * g * g
|
|
129
|
+
p -= self.lr * (m / c1) / (np.sqrt(v / c2) + self.eps)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# ---------------------------------------------------------------------------------------------
|
|
133
|
+
# VAE core (float64 math)
|
|
134
|
+
# ---------------------------------------------------------------------------------------------
|
|
135
|
+
|
|
136
|
+
class _VAENet:
|
|
137
|
+
def __init__(self, enc: Layers, dec: Layers, dec_logvar: np.ndarray, act: str) -> None:
|
|
138
|
+
self.enc, self.dec, self.dec_logvar, self.act = enc, dec, dec_logvar, act
|
|
139
|
+
self.latent_dim = dec[0][0].shape[0]
|
|
140
|
+
|
|
141
|
+
def flat(self) -> list[np.ndarray]:
|
|
142
|
+
out: list[np.ndarray] = []
|
|
143
|
+
for w, b in self.enc + self.dec:
|
|
144
|
+
out += [w, b]
|
|
145
|
+
return out + [self.dec_logvar]
|
|
146
|
+
|
|
147
|
+
def encode(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray, Any]:
|
|
148
|
+
out, cache = _mlp_forward(self.enc, x, self.act)
|
|
149
|
+
k = self.latent_dim
|
|
150
|
+
return out[:, :k], np.clip(out[:, k:], LV_MIN, LV_MAX), cache
|
|
151
|
+
|
|
152
|
+
def decode(self, c: np.ndarray) -> tuple[np.ndarray, Any]:
|
|
153
|
+
return _mlp_forward(self.dec, c, self.act)
|
|
154
|
+
|
|
155
|
+
def dec_lv(self) -> np.ndarray:
|
|
156
|
+
return np.clip(self.dec_logvar, LV_MIN, LV_MAX)
|
|
157
|
+
|
|
158
|
+
def neg_elbo(self, x: np.ndarray, eps: np.ndarray, beta: float = 1.0) -> np.ndarray:
|
|
159
|
+
mu, lv, _ = self.encode(x)
|
|
160
|
+
c = mu + np.exp(0.5 * lv) * eps
|
|
161
|
+
xm, _ = self.decode(c)
|
|
162
|
+
dlv = self.dec_lv()
|
|
163
|
+
rec = 0.5 * np.sum((x - xm) ** 2 * np.exp(-dlv) + dlv + LOG_2PI, axis=1)
|
|
164
|
+
kl = 0.5 * np.sum(mu * mu + np.exp(lv) - lv - 1.0, axis=1)
|
|
165
|
+
return rec + beta * kl
|
|
166
|
+
|
|
167
|
+
def loss_and_grads(self, x: np.ndarray, eps: np.ndarray, beta: float
|
|
168
|
+
) -> tuple[float, list[np.ndarray]]:
|
|
169
|
+
bsz = len(x)
|
|
170
|
+
k = self.latent_dim
|
|
171
|
+
enc_out, enc_cache = _mlp_forward(self.enc, x, self.act)
|
|
172
|
+
mu, lv_raw = enc_out[:, :k], enc_out[:, k:]
|
|
173
|
+
lv = np.clip(lv_raw, LV_MIN, LV_MAX)
|
|
174
|
+
s = np.exp(0.5 * lv)
|
|
175
|
+
c = mu + s * eps
|
|
176
|
+
xm, dec_cache = self.decode(c)
|
|
177
|
+
dlv = self.dec_lv()
|
|
178
|
+
prec = np.exp(-dlv)
|
|
179
|
+
r = x - xm
|
|
180
|
+
rec = 0.5 * np.sum(r * r * prec + dlv + LOG_2PI, axis=1)
|
|
181
|
+
kl = 0.5 * np.sum(mu * mu + np.exp(lv) - lv - 1.0, axis=1)
|
|
182
|
+
loss = float(np.mean(rec + beta * kl))
|
|
183
|
+
# backward
|
|
184
|
+
dxm = -r * prec / bsz
|
|
185
|
+
g_dlv = 0.5 * np.sum(1.0 - r * r * prec, axis=0) / bsz
|
|
186
|
+
g_dlv = g_dlv * ((self.dec_logvar > LV_MIN) & (self.dec_logvar < LV_MAX))
|
|
187
|
+
dec_grads, dc = _mlp_backward(self.dec, dec_cache, dxm, self.act)
|
|
188
|
+
dmu = dc + beta * mu / bsz
|
|
189
|
+
dlv_enc = dc * eps * 0.5 * s + beta * 0.5 * (np.exp(lv) - 1.0) / bsz
|
|
190
|
+
dlv_enc = dlv_enc * ((lv_raw > LV_MIN) & (lv_raw < LV_MAX))
|
|
191
|
+
enc_grads, _ = _mlp_backward(self.enc, enc_cache, np.hstack([dmu, dlv_enc]),
|
|
192
|
+
self.act)
|
|
193
|
+
grads: list[np.ndarray] = []
|
|
194
|
+
for gw, gb in enc_grads + dec_grads:
|
|
195
|
+
grads += [gw, gb]
|
|
196
|
+
return loss, grads + [g_dlv]
|
|
197
|
+
|
|
198
|
+
def sample_raw(self, n: int, rng: np.random.Generator) -> np.ndarray:
|
|
199
|
+
c = rng.standard_normal((n, self.latent_dim))
|
|
200
|
+
xm, _ = self.decode(c)
|
|
201
|
+
noise = rng.standard_normal(xm.shape)
|
|
202
|
+
return xm + np.exp(0.5 * self.dec_lv()) * noise
|
|
203
|
+
|
|
204
|
+
def iwae_logpdf(self, x: np.ndarray, k: int, rng: np.random.Generator,
|
|
205
|
+
chunk: int = 2048) -> np.ndarray:
|
|
206
|
+
out = np.empty(len(x))
|
|
207
|
+
d, kd = x.shape[1], self.latent_dim
|
|
208
|
+
dlv = self.dec_lv()
|
|
209
|
+
for s in range(0, len(x), chunk):
|
|
210
|
+
xb = x[s:s + chunk]
|
|
211
|
+
nb = len(xb)
|
|
212
|
+
mu, lv, _ = self.encode(xb)
|
|
213
|
+
eps = rng.standard_normal((nb, k, kd))
|
|
214
|
+
c = mu[:, None, :] + np.exp(0.5 * lv)[:, None, :] * eps
|
|
215
|
+
log_q = np.sum(-0.5 * eps * eps - 0.5 * lv[:, None, :] - 0.5 * LOG_2PI, axis=2)
|
|
216
|
+
log_p = np.sum(-0.5 * c * c - 0.5 * LOG_2PI, axis=2)
|
|
217
|
+
xm, _ = self.decode(c.reshape(nb * k, kd))
|
|
218
|
+
r = xb[:, None, :] - xm.reshape(nb, k, d)
|
|
219
|
+
log_px = np.sum(-0.5 * (r * r * np.exp(-dlv) + dlv + LOG_2PI), axis=2)
|
|
220
|
+
out[s:s + chunk] = special.logsumexp(log_px + log_p - log_q, axis=1) - math.log(k)
|
|
221
|
+
return out
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# ---------------------------------------------------------------------------------------------
|
|
225
|
+
# The joint model
|
|
226
|
+
# ---------------------------------------------------------------------------------------------
|
|
227
|
+
|
|
228
|
+
def _layer_names(prefix: str, n: int) -> list[tuple[str, str]]:
|
|
229
|
+
return [(f"{prefix}.{i}.weight", f"{prefix}.{i}.bias") for i in range(n)]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@JOINTS.register()
|
|
233
|
+
class LatentVAE(JointModel):
|
|
234
|
+
"""Small VAE copula: decoder samples re-standardised to N(0, 1) margins."""
|
|
235
|
+
|
|
236
|
+
kind = "latent_vae"
|
|
237
|
+
|
|
238
|
+
def __init__(self, columns: list[str], net: _VAENet, grid: np.ndarray, *,
|
|
239
|
+
hidden: int, n_layers: int, training: dict[str, Any] | None = None) -> None:
|
|
240
|
+
self.columns = list(columns)
|
|
241
|
+
self.net = net
|
|
242
|
+
self.grid = np.asarray(grid, dtype=np.float64)
|
|
243
|
+
self.hidden = int(hidden)
|
|
244
|
+
self.n_layers = int(n_layers)
|
|
245
|
+
self.training = dict(training or {})
|
|
246
|
+
d = len(self.columns)
|
|
247
|
+
if self.grid.ndim != 2 or self.grid.shape[1] != d or len(self.grid) < 2 or \
|
|
248
|
+
np.any(np.diff(self.grid, axis=0) <= 0):
|
|
249
|
+
raise FingerprintError("quantile grid must be (m >= 2, d) and strictly increasing")
|
|
250
|
+
|
|
251
|
+
@property
|
|
252
|
+
def latent_dim(self) -> int:
|
|
253
|
+
return self.net.latent_dim
|
|
254
|
+
|
|
255
|
+
@property
|
|
256
|
+
def activation(self) -> str:
|
|
257
|
+
return self.net.act
|
|
258
|
+
|
|
259
|
+
# -- fitting ------------------------------------------------------------------------------
|
|
260
|
+
@classmethod
|
|
261
|
+
def fit(cls, z: np.ndarray, columns: list[str], *, policy: DisclosurePolicySpec,
|
|
262
|
+
rng: np.random.Generator | None = None, latent_dim: int | None = None,
|
|
263
|
+
hidden: int = 32, n_layers: int = 2, activation: str = "tanh",
|
|
264
|
+
max_epochs: int = 500, batch_size: int = 128, lr: float = 3e-3,
|
|
265
|
+
patience: int = 50, kl_warmup: int = 10, holdout_frac: float = 0.15,
|
|
266
|
+
time_limit: float = 60.0, **kwargs: Any) -> LatentVAE:
|
|
267
|
+
"""Fit to latent normal scores ``z`` (n, d).
|
|
268
|
+
|
|
269
|
+
Defaults keep capacity small (hidden width 32, ``latent_dim = min(d, 4)``). Extra
|
|
270
|
+
keywords (e.g. ``attenuation``) are accepted for interface compatibility and ignored.
|
|
271
|
+
"""
|
|
272
|
+
z = _check_z(z, columns)
|
|
273
|
+
if activation not in ACTIVATIONS:
|
|
274
|
+
raise ValueError(f"activation must be one of {ACTIVATIONS}")
|
|
275
|
+
if n_layers not in (1, 2):
|
|
276
|
+
raise ValueError("n_layers must be 1 or 2")
|
|
277
|
+
rng = rng if rng is not None else np.random.default_rng(0)
|
|
278
|
+
seed = int(rng.integers(2**63 - 1))
|
|
279
|
+
n, d = z.shape
|
|
280
|
+
if d == 0:
|
|
281
|
+
raise ValueError("latent_vae needs at least one column")
|
|
282
|
+
k = int(latent_dim or min(d, 4))
|
|
283
|
+
if n > MAX_FIT_ROWS:
|
|
284
|
+
z = z[np.sort(stream(seed, "latent_vae", "subsample").choice(
|
|
285
|
+
n, MAX_FIT_ROWS, replace=False))]
|
|
286
|
+
n = MAX_FIT_ROWS
|
|
287
|
+
init = stream(seed, "latent_vae", "init")
|
|
288
|
+
hid = [hidden] * n_layers
|
|
289
|
+
net = _VAENet(_init_layers([d, *hid, 2 * k], init), _init_layers([k, *hid, d], init),
|
|
290
|
+
np.zeros(d), activation)
|
|
291
|
+
# the encoder's log-variance head starts small so codes are informative early
|
|
292
|
+
net.enc[-1][1][k:] = -2.0
|
|
293
|
+
|
|
294
|
+
split = stream(seed, "latent_vae", "split").permutation(n)
|
|
295
|
+
n_val = max(1, int(round(n * holdout_frac))) if n >= 20 else 0
|
|
296
|
+
val, train = z[split[:n_val]], z[split[n_val:]]
|
|
297
|
+
val_eps = stream(seed, "latent_vae", "val_eps").standard_normal((len(val), k))
|
|
298
|
+
batch_rng = stream(seed, "latent_vae", "batches")
|
|
299
|
+
params = net.flat()
|
|
300
|
+
opt = _Adam(params, lr)
|
|
301
|
+
bs = max(1, min(batch_size, len(train)))
|
|
302
|
+
best = (math.inf, [p.copy() for p in params], 0)
|
|
303
|
+
since_best, stopped, epoch = 0, "max_epochs", 0
|
|
304
|
+
t0 = time.monotonic()
|
|
305
|
+
for epoch in range(1, max_epochs + 1):
|
|
306
|
+
beta = min(1.0, epoch / max(kl_warmup, 1))
|
|
307
|
+
perm = batch_rng.permutation(len(train))
|
|
308
|
+
for s in range(0, len(train), bs):
|
|
309
|
+
xb = train[perm[s:s + bs]]
|
|
310
|
+
eps = batch_rng.standard_normal((len(xb), k))
|
|
311
|
+
_, grads = net.loss_and_grads(xb, eps, beta)
|
|
312
|
+
opt.step(params, grads)
|
|
313
|
+
if n_val:
|
|
314
|
+
score = float(np.mean(net.neg_elbo(val, val_eps)))
|
|
315
|
+
if not math.isfinite(score):
|
|
316
|
+
stopped = "diverged"
|
|
317
|
+
break
|
|
318
|
+
if epoch >= kl_warmup:
|
|
319
|
+
if score < best[0] - 1e-4:
|
|
320
|
+
best, since_best = (score, [p.copy() for p in params], epoch), 0
|
|
321
|
+
else:
|
|
322
|
+
since_best += 1
|
|
323
|
+
if since_best >= patience:
|
|
324
|
+
stopped = "early_stop"
|
|
325
|
+
break
|
|
326
|
+
if time.monotonic() - t0 >= time_limit:
|
|
327
|
+
stopped = "time_cap"
|
|
328
|
+
break
|
|
329
|
+
if n_val and best[0] < math.inf:
|
|
330
|
+
for p, b in zip(params, best[1]):
|
|
331
|
+
p[...] = b
|
|
332
|
+
# quantise exactly as stored so in-memory and reloaded models are identical
|
|
333
|
+
for p in params:
|
|
334
|
+
p[...] = coarsen_array(p, policy).astype(np.float32)
|
|
335
|
+
training = {"seed": seed, "epochs": epoch, "best_epoch": best[2], "stopped": stopped,
|
|
336
|
+
"heldout_neg_elbo": None if best[0] == math.inf else float(best[0]),
|
|
337
|
+
"n_train": len(train), "n_heldout": n_val}
|
|
338
|
+
grid = make_grid(net.sample_raw(GRID_SAMPLES, stream(seed, "latent_vae", "grid")),
|
|
339
|
+
policy)
|
|
340
|
+
return cls(columns, net, grid, hidden=hidden, n_layers=n_layers, training=training)
|
|
341
|
+
|
|
342
|
+
# -- sampling / density -------------------------------------------------------------------
|
|
343
|
+
def sample_raw(self, n: int, rng: np.random.Generator) -> np.ndarray:
|
|
344
|
+
"""Decoder draws before re-standardisation."""
|
|
345
|
+
return self.net.sample_raw(n, rng)
|
|
346
|
+
|
|
347
|
+
def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
|
|
348
|
+
return to_normal(self.net.sample_raw(n, rng), self.grid)
|
|
349
|
+
|
|
350
|
+
def logpdf(self, z: np.ndarray, n_importance: int = 64, seed: int = 0) -> np.ndarray:
|
|
351
|
+
"""**Approximate** log density of latent scores under the sampled distribution.
|
|
352
|
+
|
|
353
|
+
Importance-weighted ELBO (``n_importance`` posterior samples, fixed ``seed``) of the
|
|
354
|
+
raw decoder density at the inverse-re-standardised point, plus the log-Jacobian of the
|
|
355
|
+
piecewise-linear re-standardisation. A stochastic lower bound; use for model
|
|
356
|
+
comparison only.
|
|
357
|
+
"""
|
|
358
|
+
z = _check_z(z, self.columns)
|
|
359
|
+
x, logjac = from_normal(z, self.grid)
|
|
360
|
+
return self.net.iwae_logpdf(x, int(n_importance), stream(seed, "latent_vae", "iwae")
|
|
361
|
+
) + logjac
|
|
362
|
+
|
|
363
|
+
@property
|
|
364
|
+
def n_parameters(self) -> int:
|
|
365
|
+
return int(sum(p.size for p in self.net.flat())) + self.grid.size
|
|
366
|
+
|
|
367
|
+
# -- serialisation ------------------------------------------------------------------------
|
|
368
|
+
def _named_arrays(self) -> dict[str, np.ndarray]:
|
|
369
|
+
out: dict[str, np.ndarray] = {}
|
|
370
|
+
for (wn, bn), (w, b) in zip(_layer_names("enc", len(self.net.enc)), self.net.enc):
|
|
371
|
+
out[wn], out[bn] = w, b
|
|
372
|
+
for (wn, bn), (w, b) in zip(_layer_names("dec", len(self.net.dec)), self.net.dec):
|
|
373
|
+
out[wn], out[bn] = w, b
|
|
374
|
+
out["dec_logvar"] = self.net.dec_logvar
|
|
375
|
+
return out
|
|
376
|
+
|
|
377
|
+
def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
|
|
378
|
+
arrays: dict[str, str] = {}
|
|
379
|
+
hashes: dict[str, str] = {}
|
|
380
|
+
for name, a in self._named_arrays().items():
|
|
381
|
+
put_hashed(store, prefix, name, a, "<f4", arrays, hashes)
|
|
382
|
+
put_hashed(store, prefix, "grid", self.grid, "<f8", arrays, hashes)
|
|
383
|
+
params: dict[str, Any] = {
|
|
384
|
+
"columns": list(self.columns),
|
|
385
|
+
"architecture": {"latent_dim": self.latent_dim, "hidden": self.hidden,
|
|
386
|
+
"n_layers": self.n_layers, "activation": self.activation,
|
|
387
|
+
"weight_layout": "x @ W + b, W shape (in, out)"},
|
|
388
|
+
"weight_dtype": "float32",
|
|
389
|
+
"weight_hashes": hashes,
|
|
390
|
+
"training": self.training,
|
|
391
|
+
"warnings": [PRIVACY_WARNING],
|
|
392
|
+
"logpdf": "approximate (importance-weighted ELBO)",
|
|
393
|
+
}
|
|
394
|
+
return ModelSpec(kind=self.kind, params=params, arrays=arrays)
|
|
395
|
+
|
|
396
|
+
@classmethod
|
|
397
|
+
def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> LatentVAE:
|
|
398
|
+
cols = [str(c) for c in spec.params.get("columns", [])] # type: ignore[union-attr]
|
|
399
|
+
arch = spec.params.get("architecture")
|
|
400
|
+
if not isinstance(arch, dict):
|
|
401
|
+
raise FingerprintError("latent_vae spec has no architecture")
|
|
402
|
+
k, hidden, nl, act = (arch.get("latent_dim"), arch.get("hidden"),
|
|
403
|
+
arch.get("n_layers"), arch.get("activation"))
|
|
404
|
+
for v, what in ((k, "latent_dim"), (hidden, "hidden")):
|
|
405
|
+
if isinstance(v, bool) or not isinstance(v, int) or not 1 <= v <= 4096:
|
|
406
|
+
raise FingerprintError(f"latent_vae: invalid {what} {v!r}")
|
|
407
|
+
if nl not in (1, 2) or act not in ACTIVATIONS:
|
|
408
|
+
raise FingerprintError("latent_vae: n_layers must be 1 or 2 and activation "
|
|
409
|
+
f"one of {ACTIVATIONS}")
|
|
410
|
+
assert isinstance(k, int) and isinstance(hidden, int) and isinstance(nl, int)
|
|
411
|
+
d = len(cols)
|
|
412
|
+
enc_sizes = [d, *([hidden] * nl), 2 * k]
|
|
413
|
+
dec_sizes = [k, *([hidden] * nl), d]
|
|
414
|
+
|
|
415
|
+
def load(prefix: str, sizes: list[int]) -> Layers:
|
|
416
|
+
layers: Layers = []
|
|
417
|
+
for i, (wn, bn) in enumerate(_layer_names(prefix, len(sizes) - 1)):
|
|
418
|
+
w = get_verified(spec, store, wn, "<f4").astype(np.float64)
|
|
419
|
+
b = get_verified(spec, store, bn, "<f4").astype(np.float64)
|
|
420
|
+
if w.shape != (sizes[i], sizes[i + 1]) or b.shape != (sizes[i + 1],):
|
|
421
|
+
raise FingerprintError(f"latent_vae: {wn} has the wrong shape")
|
|
422
|
+
layers.append((w, b))
|
|
423
|
+
return layers
|
|
424
|
+
|
|
425
|
+
enc, dec = load("enc", enc_sizes), load("dec", dec_sizes)
|
|
426
|
+
dlv = get_verified(spec, store, "dec_logvar", "<f4").astype(np.float64)
|
|
427
|
+
if dlv.shape != (d,):
|
|
428
|
+
raise FingerprintError("latent_vae: dec_logvar has the wrong shape")
|
|
429
|
+
grid = get_verified(spec, store, "grid", "<f8")
|
|
430
|
+
training = spec.params.get("training")
|
|
431
|
+
return cls(cols, _VAENet(enc, dec, dlv, act), grid, hidden=hidden, n_layers=nl,
|
|
432
|
+
training=training if isinstance(training, dict) else None)
|