Membership Circuits¶
A Membership Circuit (MC) turns a probabilistic circuit into a statistical test. For an observation \(\mathbf{x}\) it tests the membership hypothesis
that is, whether \(\mathbf{x}\) is a sample of the distribution \(P_\mathcal{C}\) that the circuit \(\mathcal{C}\) encodes. The result is a multivariate p-value \(\hat{p}_\mathcal{C}(\mathbf{x})\). The hypothesis is rejected if \(\hat{p}_\mathcal{C}(\mathbf{x}) \le \alpha\) for a test niveau \(\alpha\) that you choose.
The test has a guarantee: if the circuit models the data, the probability of a false rejection, the false positive rate (FPR), is at most \(\alpha\). It needs no samples, no calibration data and no asymptotic argument, only one bottom-up pass through the circuit.
Membership Circuits were introduced in the paper Membership Circuits: Tractable Membership Testing via Probabilistic Circuits by Bennet Wittelsbach, Arseny Skryagin, Jonas Seng, Moritz Willig and Kristian Kersting (ICML 2026 Workshop on Hypothesis Testing).
This guide covers
a first membership test on a small circuit,
how the p-value is computed,
the p-value combination functions,
the bound on the false positive rate,
outlier detection with a learned circuit,
missing values,
the goodness-of-fit test that tells whether the circuit fits the data,
one-sided tests.
Imports¶
Membership Circuits live in spflow.zoo.mc. The wrapper MembershipCircuit takes any smooth and decomposable circuit and a MembershipTestConfig with one combination function for the sum nodes and one for the product nodes.
[1]:
import contextlib
import io
import math
import matplotlib.pyplot as plt
import torch
from scipy import stats
from spflow.learn.learn_spn import learn_spn
from spflow.meta import Scope
from spflow.modules.leaves import Normal
from spflow.modules.products import Product
from spflow.modules.sums import Sum
from spflow.zoo.mc import (
ArithmeticMeanK,
Bonferroni,
Fisher,
HarmonicMean,
MaxP,
MembershipCircuit,
MembershipTestConfig,
Simes,
gof_report,
)
torch.manual_seed(0)
ALPHA = 0.05
NAN = float("nan")
1. A First Membership Test¶
The circuit below is a mixture of two components over the variables \(X_0\) and \(X_1\). One component lies around \((-2, -2)\), the other around \((2, 2)\). Each variable alone is therefore bimodal, and the two variables are dependent: small values of \(X_0\) go with small values of \(X_1\).
[2]:
def normal(variable: int, loc: float, scale: float) -> Normal:
return Normal(scope=Scope([variable]), loc=torch.tensor([[[loc]]]), scale=torch.tensor([[[scale]]]))
circuit = Sum(
inputs=[
Product(inputs=[normal(0, -2.0, 1.0), normal(1, -2.0, 1.0)]),
Product(inputs=[normal(0, 2.0, 1.0), normal(1, 2.0, 1.0)]),
],
weights=[0.5, 0.5],
)
config = MembershipTestConfig(sum_rule=ArithmeticMeanK(), product_rule=Fisher())
mc = MembershipCircuit(circuit, config)
Calling the Membership Circuit on data returns one p-value per row. We test four observations: one near each component, one that mixes the two components, and one far away from both.
[3]:
labels = ["near the first component", "near the second component", "mix of the two components", "far away"]
x = torch.tensor([[-2.3, -1.6], [1.8, 2.5], [-2.0, 2.0], [7.0, 7.0]])
p = mc(x)
for label, row, value in zip(labels, x.tolist(), p.tolist()):
decision = "reject" if value <= ALPHA else "keep"
print(f"{label:28s} x = ({row[0]:4.1f}, {row[1]:4.1f}) p = {value:8.2e} -> {decision} H0")
near the first component x = (-2.3, -1.6) p = 8.64e-01 -> keep H0
near the second component x = ( 1.8, 2.5) p = 8.60e-01 -> keep H0
mix of the two components x = (-2.0, 2.0) p = 1.35e-03 -> reject H0
far away x = ( 7.0, 7.0) p = 9.78e-12 -> reject H0
The third observation shows why the test must be multivariate. Each of its values is perfectly ordinary: \(x_0 = -2\) is the centre of the first component and \(x_1 = 2\) is the centre of the second. Only the combination does not occur under the circuit.
We can check this with the circuit itself. A missing value (NaN) removes a variable from the test, so the next cell tests each variable of this observation alone.
[4]:
only_first = torch.tensor([[-2.0, NAN]])
only_second = torch.tensor([[NAN, 2.0]])
print(f"x0 = -2 alone: p = {mc(only_first).item():.3f}")
print(f"x1 = 2 alone: p = {mc(only_second).item():.3f}")
print(f"both values together: p = {mc(torch.tensor([[-2.0, 2.0]])).item():.2e}")
x0 = -2 alone: p = 1.000
x1 = 2 alone: p = 1.000
both values together: p = 1.35e-03
[5]:
samples = circuit.sample(num_samples=2000).detach()
fig, ax = plt.subplots(figsize=(4.5, 4.5))
ax.scatter(samples[:, 0], samples[:, 1], s=4, color="0.75", label="samples of the circuit")
for row, value in zip(x.tolist(), p.tolist()):
rejected = value <= ALPHA
ax.scatter(*row, s=70, marker="X" if rejected else "o", color="tab:red" if rejected else "tab:blue")
ax.annotate(f"p = {value:.1e}", row, textcoords="offset points", xytext=(8, 6), fontsize=8)
ax.set_xlabel("$x_0$")
ax.set_ylabel("$x_1$")
ax.set_title(r"Membership test at $\alpha = 0.05$ (crosses are rejected)")
ax.legend(loc="lower right", fontsize=8)
plt.show()
2. How the P-Value Is Computed¶
The p-value is computed in one bottom-up pass, in the same order as a density.
Leaves turn an observed value into a univariate p-value with their cumulative distribution function \(F\). With \(l = F(x)\) and \(r = 1 - F(x^-)\) the p-value is \(l\) for a left-sided test, \(r\) for a right-sided test and \(2 \cdot \min(l, r)\) for a two-sided test. The term \(F(x^-)\) is the probability of all values below \(x\); it differs from \(F(x)\) only at discrete leaves.
Product nodes merge the p-values of their children, which belong to independent groups of variables. The configuration above uses Fisher’s method,
Sum nodes merge the p-values of the components of a mixture. An observation comes from one component only, and only the p-value of that component is known to be valid. A plain weighted average is therefore not a valid p-value. The \(k\)-corrected arithmetic mean (AM-\(k\)) repairs this with the number of children \(k\):
Every inner node clips its result to \([0, 1]\). The next cell repeats the pass by hand for the observation \((-2, 2)\).
[6]:
def leaf_pvalue(value: float, loc: float, scale: float) -> float:
return 2.0 * min(stats.norm.cdf(value, loc, scale), stats.norm.sf(value, loc, scale))
def fisher(pvalues: list[float]) -> float:
statistic = -2.0 * sum(math.log(value) for value in pvalues)
return float(stats.chi2.sf(statistic, df=2 * len(pvalues)))
x0, x1 = -2.0, 2.0
first_component = fisher([leaf_pvalue(x0, -2.0, 1.0), leaf_pvalue(x1, -2.0, 1.0)])
second_component = fisher([leaf_pvalue(x0, 2.0, 1.0), leaf_pvalue(x1, 2.0, 1.0)])
root = min(1.0, 2 * (0.5 * first_component + 0.5 * second_component))
print(f"product nodes: {first_component:.6e} and {second_component:.6e}")
print(f"root by hand: {root:.6e}")
print(f"mc(x): {mc(torch.tensor([[x0, x1]])).item():.6e}")
product nodes: 6.756714e-04 and 6.756714e-04
root by hand: 1.351343e-03
mc(x): 1.351343e-03
3. Combination Functions¶
Different combination functions give different tests. They either aggregate the evidence of all children or select the most striking child, and at product nodes they come in a version for independent children and a version that stays valid if the children are dependent.
Sum nodes |
Product nodes, independent children |
Product nodes, dependent children |
|
|---|---|---|---|
Aggregate |
|
|
|
Select |
|
|
|
MaxPat a sum node takes the largest p-value of the children: the hypothesis is rejected only if no component explains the observation.SimesandBonferronilook for evidence in any child of a product node;FisherandHarmonicMeanadd up the evidence of all children.The children of a product node are independent under the circuit, so
FisherandSimesare valid. If you do not trust the independence that the circuit learned,HarmonicMeanandBonferroniare valid under any dependence, at the price of power.
Any combination of a sum rule and a product rule from the table gives a valid test. The cell below evaluates the four observations of the first section with all eight combinations.
[7]:
sum_rules = {"AM-k": ArithmeticMeanK(), "maxP": MaxP()}
product_rules = {"Fisher": Fisher(), "Simes": Simes(), "harmonic mean": HarmonicMean(), "Bonferroni": Bonferroni()}
header = "".join(f"{f'({row[0]:.1f}, {row[1]:.1f})':>14s}" for row in x.tolist())
print(f"{'sum rule':8s} {'product rule':14s}{header}")
for sum_name, sum_rule in sum_rules.items():
for product_name, product_rule in product_rules.items():
test = MembershipCircuit(circuit, MembershipTestConfig(sum_rule=sum_rule, product_rule=product_rule))
print(f"{sum_name:8s} {product_name:14s}" + "".join(f"{value:14.2e}" for value in test(x).tolist()))
sum rule product rule (-2.3, -1.6) (1.8, 2.5) (-2.0, 2.0) (7.0, 7.0)
AM-k Fisher 8.64e-01 8.60e-01 1.35e-03 9.78e-12
AM-k Simes 7.64e-01 8.41e-01 2.53e-04 5.73e-07
AM-k harmonic mean 1.00e+00 1.00e+00 5.07e-04 1.15e-06
AM-k Bonferroni 1.00e+00 1.00e+00 2.53e-04 1.15e-06
maxP Fisher 8.64e-01 8.60e-01 6.76e-04 9.78e-12
maxP Simes 7.64e-01 8.41e-01 1.27e-04 5.73e-07
maxP harmonic mean 1.00e+00 1.00e+00 2.53e-04 1.15e-06
maxP Bonferroni 1.00e+00 1.00e+00 1.27e-04 1.15e-06
4. The Bound on the False Positive Rate¶
If every sum node uses a function that is valid for mixtures and every product node a function that is valid for its children, every node of the Membership Circuit computes a valid p-value for its own distribution. For the root this means
We can observe the bound on samples of the circuit: for every test niveau, the share of rejected samples must not exceed the niveau. In the plot, a valid test stays on or below the dashed diagonal. A test below the diagonal is conservative: it rejects less often than it may.
[8]:
samples = circuit.sample(num_samples=50_000).detach()
levels = torch.logspace(-3, 0, 31, dtype=torch.float64)
fig, ax = plt.subplots(figsize=(5, 4.5))
ax.plot(levels, levels, "k--", label="bound")
for sum_name, product_name in [("AM-k", "Fisher"), ("AM-k", "harmonic mean"), ("maxP", "Simes"), ("maxP", "Bonferroni")]:
test = MembershipCircuit(
circuit, MembershipTestConfig(sum_rule=sum_rules[sum_name], product_rule=product_rules[product_name])
)
pvalues = test(samples)
rates = [(pvalues <= level).double().mean().item() for level in levels]
ax.plot(levels, rates, label=f"{sum_name} + {product_name}")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlabel(r"test niveau $\alpha$")
ax.set_ylabel("empirical FPR")
ax.legend(fontsize=8)
plt.show()
5. Outlier Detection with a Learned Circuit¶
In practice the circuit is learned from data. We draw 1000 training rows from a bimodal Gaussian distribution over ten variables and learn a circuit with LearnSPN (Gaussian leaves, at least 50 rows per leaf, and the default threshold 0.3 of the independence test).
[9]:
NUM_VARIABLES = 10
def draw(num_rows: int) -> torch.Tensor:
# Every row belongs to one of two clusters with the means -1 and +1 in all variables.
sign = torch.where(torch.rand(num_rows, 1) < 0.5, -1.0, 1.0)
return sign + torch.randn(num_rows, NUM_VARIABLES)
train, test_rows = draw(1000), draw(5000)
with contextlib.redirect_stdout(io.StringIO()): # the clustering step prints its progress
learned = learn_spn(train, leaf_modules=Normal(scope=Scope(list(range(NUM_VARIABLES)))), min_instances_slice=50)
aggregate = MembershipCircuit(learned, MembershipTestConfig(sum_rule=ArithmeticMeanK(), product_rule=Fisher()))
select = MembershipCircuit(learned, MembershipTestConfig(sum_rule=MaxP(), product_rule=Simes()))
for name, test in (("aggregate (AM-k + Fisher)", aggregate), ("select (maxP + Simes)", select)):
rate = (test(test_rows) <= ALPHA).double().mean().item()
print(f"{name:27s} rejects {100 * rate:4.1f} % of the held-out rows at alpha = {ALPHA}")
aggregate (AM-k + Fisher) rejects 4.5 % of the held-out rows at alpha = 0.05
select (maxP + Simes) rejects 4.3 % of the held-out rows at alpha = 0.05
The 5000 held-out rows come from the same distribution as the training rows, and both tests reject about 5 % of them or less: the bound carries over to the learned circuit, because it fits the data. (With 5000 rows, a rate of 5 % has a standard error of 0.3 percentage points.)
Now we turn held-out rows into outliers by shifting one of the ten variables by a signal of strength \(\sigma\). The power of a test is the share of these outliers that it rejects.
[10]:
strengths = torch.linspace(0.0, 5.0, 11)
power = {"aggregate (AM-k + Fisher)": [], "select (maxP + Simes)": []}
for strength in strengths:
outliers = test_rows.clone()
outliers[:, 0] += strength
power["aggregate (AM-k + Fisher)"].append((aggregate(outliers) <= ALPHA).double().mean().item())
power["select (maxP + Simes)"].append((select(outliers) <= ALPHA).double().mean().item())
fig, ax = plt.subplots(figsize=(5, 3.5))
for name, values in power.items():
ax.plot(strengths, values, marker="o", markersize=3, label=name)
ax.axhline(ALPHA, color="k", linestyle=":", linewidth=1)
ax.set_xlabel(r"signal strength $\sigma$ in one of ten variables")
ax.set_ylabel(f"power at alpha = {ALPHA}")
ax.legend(fontsize=8)
plt.show()
A single strong signal is found best by the functions that select: they look for one striking variable. Functions that aggregate dilute one signal with the nine ordinary variables. They are the better choice when many variables deviate a little at the same time.
6. Missing Values¶
A probabilistic circuit can marginalize variables out exactly, and a Membership Circuit inherits this. A missing value is marked with NaN. The row is then tested on its observed variables only, with the marginal distribution of the circuit over these variables. No imputation is necessary.
The guarantee holds for the observed part of a row if the values are missing completely at random, that is, if the fact that a value is missing does not depend on the values. A row without any observed value gets the p-value 1.
[11]:
def with_missing_values(rows: torch.Tensor, share: float) -> torch.Tensor:
rows = rows.clone()
rows[torch.rand(rows.shape) < share] = NAN
return rows
outliers = test_rows.clone()
outliers[:, 0] += 4.0
print(f"{'missing values':>15s} {'FPR on held-out rows':>22s} {'power on outliers':>19s}")
for share in (0.0, 0.3, 0.5, 0.7):
fpr = (select(with_missing_values(test_rows, share)) <= ALPHA).double().mean().item()
detected = (select(with_missing_values(outliers, share)) <= ALPHA).double().mean().item()
print(f"{100 * share:13.0f} % {100 * fpr:20.1f} % {100 * detected:17.1f} %")
print("row without any observed value:", select(torch.full((1, NUM_VARIABLES), NAN)).item())
missing values FPR on held-out rows power on outliers
0 % 4.3 % 88.6 %
30 % 3.9 % 63.2 %
50 % 3.8 % 46.2 %
70 % 3.5 % 27.7 %
row without any observed value: 1.0
The false positive rate stays at or below the niveau, up to the noise of the estimate, for every share of missing values. The power decreases, because the shifted variable is missing in a growing share of the outliers.
7. Does the Circuit Fit the Data?¶
The bound on the false positive rate holds if the circuit models the data. This can be turned around: if the test rejects clearly more than a share \(\alpha\) of rows that should be ordinary, the circuit does not fit them.
Given the p-values of \(n\) held-out rows, the Binomial goodness-of-fit test asks whether the number of rejections \(B_\alpha\) is larger than the bound permits,
and a one-sided Kolmogorov-Smirnov test does the same for all niveaus at once. A small result signals misfit. gof_report computes both from the p-values.
We compare held-out rows of the training distribution with rows of a distribution that the circuit has not seen: the same two clusters, but twice as wide.
[12]:
def report(name: str, rows: torch.Tensor) -> None:
result = gof_report(aggregate(rows))
print(
f"{name:34s} rejected at 0.05: {100 * result['rate_at_0.05']:5.1f} % "
f"Binomial test: {result['binomial_gof_at_0.05']:.2e} Kolmogorov-Smirnov test: {result['ks_gof']:.2e}"
)
sign = torch.where(torch.rand(5000, 1) < 0.5, -1.0, 1.0)
wider = sign + 2.0 * torch.randn(5000, NUM_VARIABLES)
report("held-out rows, same distribution", test_rows)
report("rows of a wider distribution", wider)
held-out rows, same distribution rejected at 0.05: 4.5 % Binomial test: 9.65e-01 Kolmogorov-Smirnov test: 9.99e-01
rows of a wider distribution rejected at 0.05: 90.5 % Binomial test: 0.00e+00 Kolmogorov-Smirnov test: 0.00e+00
For the held-out rows the number of rejections is compatible with the bound. For the wider data both tests are far below any usual niveau: the circuit does not describe these rows, and its p-values must not be read as a statement about single rows.
Use rows that were not used to fit the circuit. The circuit is adapted to its training rows, so their p-values look better than those of new rows.
8. One-Sided Tests¶
By default every leaf is tested on both sides: \(2 \cdot \min(l, r)\). With side="left" only values that are too small count as evidence against the hypothesis, and with side="right" only values that are too large. A one-sided test is the right choice if only one direction of a deviation matters.
The cell uses the small circuit of the first section and two observations that lie beyond its components, one above and one below.
[13]:
beyond = torch.tensor([[5.0, 5.0], [-5.0, -5.0]])
print(f"{'side':8s}" + "".join(f"{f'x = ({row[0]:.0f}, {row[1]:.0f})':>16s}" for row in beyond.tolist()))
for side in ("both", "right", "left"):
test = MembershipCircuit(
circuit, MembershipTestConfig(sum_rule=ArithmeticMeanK(), product_rule=Fisher(), side=side)
)
print(f"{side:8s}" + "".join(f"{value:16.2e}" for value in test(beyond).tolist()))
side x = (5, 5) x = (-5, -5)
both 9.35e-05 9.35e-05
right 2.59e-05 1.00e+00
left 1.00e+00 2.59e-05
The two-sided test rejects both observations. The right-sided test rejects only the observation whose values are too large, and the left-sided test only the one whose values are too small.
Summary¶
MembershipCircuit(circuit, config)wraps a smooth and decomposable circuit; calling it on data returns one p-value per row.membership_pvaluescomputes the same without a wrapper.MembershipTestConfigholds the combination functions:ArithmeticMeanKorMaxPat sum nodes, andFisher,Simes,HarmonicMeanorBonferroniat product nodes.If the circuit fits the data, the false positive rate is at most the test niveau.
NaN marks a missing value; the row is tested on its observed variables.
gof_report,binomial_gofandks_goftest on held-out rows whether the circuit fits the data.
The API reference with all options and the supported modules and leaf distributions is on the Membership Circuits page of the Paper Zoo.