Skip to main content

pysemi

Sequential Membership Inference (SeMI) attacks for auditing models that go through multiple updates. Library companion to Sequential Membership Inference Attacks (Michel, Basu, Kaufmann, NeurIPS 2026).

Naming follows the paper:

Class Statistic NP-optimal against
SeMIStar log LR_τ at known τ H_0 vs H_1^τ
SeMIMax max_t log LR_t (GLR) H_0 vs ⋃_t H_1^t
SeMIUnif log (1/T) Σ_t LR_t H_0 vs τ ~ Unif([T])
SeMIStarDP SeMI* under Laplace-DP cumulative-mean release DP audits
FinalObservation snapshot LR from the final cumulative mean snapshot baseline
SeMISGD / Max / Unif plug-in log LR variants for (DP-)SGD-trained models Gaussian-gradient NP

Installation

pip install pysemi              # core (numpy + scipy)
pip install pysemi[torch]       # + arbitrary-NN audits (PyTorch)
pip install pysemi[analysis]    # + matplotlib for example plots

Quick start — empirical-mean SeMI variants

import pysemi
import numpy as np

rng = np.random.default_rng(0)

# Known τ (NP-optimal): SeMI*
test = pysemi.SeMIStar(mu=0.0, sigma=1.0, z_star=4.0, n=50)
means = test.simulate(T=10, tau_star=3, rng=rng)
test.log_lr(means, tau=3)
test.power(alpha=0.05, T=10, tau=3)

# Unknown τ
pysemi.SeMIMax(mu=0.0, sigma=1.0, z_star=4.0, n=50).log_lr(means)
pysemi.SeMIUnif(mu=0.0, sigma=1.0, z_star=4.0, n=50).log_lr(means)

# Laplace-DP release of the running mean
dp = pysemi.SeMIStarDP(mu=0.0, sigma=1.0, z_star=4.0, n=50, epsilon=1.0)
noisy_means = dp.simulate(T=10, tau_star=3, rng=rng)
dp.log_lr(noisy_means, tau=3)        # SeMI*
dp.log_lr_max(noisy_means)           # SeMI^max
dp.log_lr_unif(noisy_means)          # SeMI^unif

# Snapshot baseline
pysemi.FinalObservation(0.0, 1.0, 4.0, n=50, T=10).log_lr(noisy_means[-1])

SeMI^SGD — auditing arbitrary parametric models

SeMISGD, SeMISGDMax and SeMISGDUnif all consume a trajectory of flat parameter snapshots (θ_0, …, θ_T) saved at phase boundaries, plus a GradientOracle that exposes the per-sample gradient at the target.

Three oracles ship with the library:

  • SoftmaxOracle — numpy last-layer multinomial-logistic oracle. Used for the Fashion-MNIST and Purchase-100 audits of the paper.
  • LinearRegressionOracle — analytic ½(θᵀx − y)² gradient. The SGD-linear baseline of the paper is just SeMISGD with this oracle (no separate code path).
  • pysemi.torch.TorchOracle / TorchLastLayerOracle — wraps an nn.Module for arbitrary-NN audits (see below).
from pysemi import SeMISGD, SeMISGDMax, SeMISGDUnif
from pysemi.sgd import SoftmaxOracle, estimate_gradient_stats, phase_effective_lr

oracle = SoftmaxOracle(input_dim=784, num_classes=10)

# 1) Pre-estimate background gradient statistics
mu_g, sigma = estimate_gradient_stats(background_gradient_matrix)
sigma_inv = np.linalg.inv(sigma)

# 2) Each variant takes the same arguments
common = dict(theta_trajectory=thetas, oracle=oracle, mu_g=mu_g, sigma_inv=sigma_inv,
              eta=phase_effective_lr(lr, K, batch_size, pool_size), n_batch=batch_size)
SeMISGD(**common).log_lr(tau, x_star, y_star)        # known τ
SeMISGDMax(**common).log_lr(x_star, y_star)          # max_t log LR_t
SeMISGDUnif(**common).log_lr(x_star, y_star)         # log mean exp(log LR_t)

Auditing an arbitrary PyTorch model

pysemi.torch provides the glue for end-to-end audits of any nn.Module:

from pysemi.torch import TorchOracle, TorchLastLayerOracle, TrajectoryRecorder, estimate_gradient_stats_from_loader
import pysemi

# Audit only the last nn.Linear (as the paper does), or audit any parameter subset
oracle = TorchLastLayerOracle(model)
# or:  TorchOracle(model, param_names=["classifier.weight", "classifier.bias"])

# 1) Record θ at each phase boundary during training
recorder = TrajectoryRecorder(oracle)
recorder.record()                                 # θ_0
for phase in range(1, T + 1):
    for _ in range(K):
        # one SGD step on a batch
        ...
    recorder.record()                             # θ_phase

# 2) Pre-compute background gradient stats from a DataLoader at θ_{τ-1}
mu_g, sigma = estimate_gradient_stats_from_loader(
    oracle, background_loader, theta=recorder.trajectory[tau - 1], n_samples=2000,
)
sigma_inv = np.linalg.inv(sigma)

# 3) Run the attack
score = pysemi.SeMISGD(
    recorder.trajectory, oracle, mu_g, sigma_inv,
    eta=pysemi.sgd.phase_effective_lr(lr, K, batch_size, pool_size),
    n_batch=batch_size,
).log_lr(tau, x_star, y_star)

See examples/example_torch_nn_audit.py for a complete pipeline: a small MLP audited via TorchLastLayerOracle over 6 phases of training.

Metrics

  • pysemi.metrics.compute_empirical_roc, compute_auc, compute_tpr_at_low_fpr, compute_balanced_accuracy.
  • compute_epsilon_lower_bound_cp / _dkw (and _stratified variants for τ-informed adversaries) — Clopper-Pearson and DKW lower bounds on ε for (ε, δ)-DP audits, matching the estimators used in the paper.
  • bootstrap_epsilon_ci and subsample_epsilon_ci for CIs.

Examples (miniature paper reproductions)

Script What it shows
example_semi_star_power_curve.py Power vs T at fixed n·T: SeMI* stays flat, FinalObservation decays
example_glr_unknown_tau.py SeMI^max vs SeMI^unif vs FinalObservation under random τ
example_dp_audit.py DP SeMI* empirical ε lower bounds vs. the true budget
example_semi_sgd_softmax.py SeMI^SGD on a numpy softmax last-layer audit
example_torch_nn_audit.py SeMI^SGD on a PyTorch MLP, full pipeline
example_torch_dpsgd_audit.py DP-SGD training with per-method ε lower bounds

Development

pip install -e ".[dev,torch,analysis]"
pytest             # 89 tests, ~6 s with torch
ruff check pysemi  # lint
mypy pysemi        # type-check

Release notes are in CHANGELOG.md.

Stability

pysemi is pre-1.0. The public API is everything exported from pysemi, pysemi.core, pysemi.sgd, pysemi.metrics, and pysemi.torch. Underscored symbols are internal. pysemi.torch is not imported by import pysemi, since torch is an optional dependency, so import it explicitly. We follow semantic versioning, so breaking changes happen on minor bumps before 1.0, with migration notes in the changelog.

Not everything here is in the paper. The paper covers the noiseless empirical-mean mechanism, the SeMI^SGD extension and the DP-SGD audits. The Laplace-noised empirical-mean mechanism behind SeMIStarDP and pysemi.core.dp is a library extension, documented in the module docstring of pysemi/core/dp.py.

Citing

@inproceedings{michel2026semi,
  author    = {Michel, Thomas and Basu, Debabrota and Kaufmann, Emilie},
  title     = {Sequential Membership Inference Attacks},
  booktitle = {Advances in Neural Information Processing Systems},
  year      = {2026},
}

License

MIT.

Metadata

Release files for pysemi 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pysemi 0.4.0
File Size Uploaded Provenance Actions
pysemi-0.4.0.tar.gz 43.9 kB With provenance Details for pysemi-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pysemi 0.4.0
File Interpreter ABI Platform Actions
pysemi-0.4.0-py3-none-any.whl Python 3 none any Details for pysemi-0.4.0-py3-none-any.whl

Total release size: 71.9 kB

Release files / pysemi-0.4.0.tar.gz

Download URL pysemi-0.4.0.tar.gz
Size 43.9 kB
Tags Source
SHA-256 checksum
How to use checksums
513ec388df2aeab8fa72c95f133a86230f4dde73577d92741297681369692671
BLAKE2b-256 checksum
How to use checksums
9e1ca62f15a209587a9d08ca27cec61091c13804488d96275146c148c756fa7e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 28, 2026.

Transparency log

Release files / pysemi-0.4.0-py3-none-any.whl

Download URL pysemi-0.4.0-py3-none-any.whl
Size 28.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
531a68bfef5f66c4b84b3056ec5df28863a84b4a5f71749a2da3e0015882f4b5
BLAKE2b-256 checksum
How to use checksums
8f26b85e793b22fae0b07a0c293626e4858abfe9a7178d4f40f58531eb42c8ad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 28, 2026.

Transparency log

Security for pysemi 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pysemi-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 28, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.4.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page