"""Membership Circuit: a probabilistic circuit wrapped as a hypothesis test."""
from __future__ import annotations
import math
import torch
from torch import Tensor
from spflow.exceptions import InvalidTypeError
from spflow.modules.module import Module
from spflow.modules.wrapper.base import Wrapper
from spflow.utils.cache import Cache, cached
from spflow.utils.sampling_context import LeafParamRecord
from spflow.zoo.mc.config import MembershipTestConfig
from spflow.zoo.mc.inference import _MISSING_VALUE, membership_pvalues
# Number of node values (rows times the nodes of all modules of the circuit) that the validation
# evaluates in one pass. It bounds the memory of the validation.
_PROBE_VALUES = 2**22
[docs]
class MembershipCircuit(Wrapper):
"""Wrap a probabilistic circuit as a test of the membership hypothesis.
The null hypothesis of a row is that it is a sample of the distribution of the wrapped circuit.
Calling the wrapper on data returns one p-value per row; a small p-value is evidence against the
hypothesis, for example because the row is an anomaly. The p-values are computed by
:func:`spflow.zoo.mc.membership_pvalues`, where the supported modules, the treatment of missing
values and the accuracy are described.
``forward`` returns p-values and not log-likelihoods, unlike every other SPFlow module:
``mc(data)`` is ``mc.pvalues(data)``. The log-likelihood of the wrapped circuit stays available as
``mc.log_likelihood(data)``. Sampling, expectation-maximization and structural marginalization
are delegated to the wrapped circuit, so the wrapper can be trained like the circuit itself.
Attributes:
module: The wrapped circuit.
config: Test configuration: sum rule, product rule, test side and discrete mode.
"""
[docs]
def __init__(self, module: Module, config: MembershipTestConfig, *, validate: bool = True) -> None:
"""Initialize the wrapper.
Args:
module: Circuit with a single root node. It is not copied: later changes of its
parameters change the p-values.
config: Test configuration.
validate: If ``True``, the p-value pass runs on a small probe (one complete row, and one
row per variable in which only that variable is observed), so that an unsupported
module or leaf, a root that is not a single node, a sum node whose children have
different scopes and invalid sum-rule coefficients raise here and not at the first
use. The time is that of a pass over as many rows as the circuit has variables, plus
one. The rows are evaluated in several passes, so that the memory does not grow with
the square of the number of variables.
Raises:
InvalidTypeError: If ``module`` is not a module or ``config`` is not a
:class:`MembershipTestConfig`.
ShapeError: With ``validate``, if the circuit does not have a single root node.
StructureError: With ``validate``, if the children of a sum node have different scopes.
UnsupportedOperationError: With ``validate``, if the circuit contains a module or a leaf
that is not supported.
InvalidWeightsError: With ``validate``, if the weights of a sum module are not finite.
InvalidParameterError: With ``validate``, if the coefficients of the sum rule are not
valid. Degenerate leaf parameters are found only if they show at the probe value 0.
"""
if not isinstance(module, Module):
raise InvalidTypeError(f"module must be an SPFlow Module, got {type(module).__name__}.")
if not isinstance(config, MembershipTestConfig):
raise InvalidTypeError(f"config must be a MembershipTestConfig, got {type(config).__name__}.")
super().__init__(module)
self.config = config
self._validate_on_wrap = bool(validate)
if validate:
self._validate()
def _validate(self) -> None:
"""Run the pass on probe rows that reach every check that does not depend on the data.
For two children of a sum node with different scopes there is a variable in the scope of
only one of them. The row in which only this variable is observed makes the two children
disagree on missingness, which the pass rejects. Every observed probe value is 0.
"""
query = torch.tensor(list(self.scope.query), dtype=torch.long, device=self.device)
num_columns = int(query.max()) + 1
def evaluate(observed_columns: list[Tensor]) -> None:
probe = torch.full(
(len(observed_columns), num_columns), _MISSING_VALUE, dtype=torch.float64, device=self.device
)
for row, columns in enumerate(observed_columns):
probe[row, columns] = 0.0
# A fixed seed keeps the probe away from the global random number generator.
membership_pvalues(self.module, probe, self.config, seed=0)
# The complete row comes first: an unsupported module is then reported by the pass, before the
# sizes of the modules are read for the number of rows per pass.
evaluate([query])
values_per_row = sum(
math.prod(module.out_shape)
for module in self.module.modules()
if isinstance(module, Module) and module.out_shape is not None
)
rows_per_pass = max(1, _PROBE_VALUES // max(1, values_per_row))
for variables in query.split(rows_per_pass):
evaluate(list(variables.unbind()))
[docs]
def pvalues(self, data: Tensor, *, seed: int | None = None) -> Tensor:
"""Compute the membership p-value of every row of ``data``.
Args:
data: Rows to test, of shape ``(N, D)``; column ``j`` holds variable ``j``. NaN marks a
missing value: the row is then tested on its observed variables only. The
missingness must be independent of the values.
seed: Seed of the random numbers of ``discrete_mode="randomized"``; ``None`` uses the
global random number generator of torch. Two calls with the same seed use the same
numbers: evaluate a data set in one call, or use another seed for every batch.
Ignored in the other modes, apart from the check of its type and range.
Returns:
P-values of shape ``(N,)`` in ``float64``, without gradients. See
:func:`spflow.zoo.mc.membership_pvalues` for the details and the exceptions.
"""
return membership_pvalues(self.module, data, self.config, seed=seed)
[docs]
def forward(self, data: Tensor, *, seed: int | None = None) -> Tensor: # type: ignore[override]
"""Return the membership p-values of the rows of ``data``, see :meth:`pvalues`.
This differs from the other SPFlow modules, whose forward pass is the log-likelihood.
"""
return self.pvalues(data, seed=seed)
[docs]
@cached
def log_likelihood(self, data: Tensor, cache: Cache | None = None) -> Tensor:
"""Compute the log-likelihood of the wrapped circuit.
Args:
data: Input data of shape ``(N, D)``; NaN values are marginalized.
cache: Optional cache for intermediate results.
Returns:
Log-likelihood tensor of the wrapped circuit.
"""
return self.module.log_likelihood(data, cache=cache)
[docs]
def sample(
self,
num_samples: int | None = None,
data: Tensor | None = None,
is_mpe: bool = False,
cache: Cache | None = None,
return_leaf_params: bool = False,
) -> Tensor | tuple[Tensor, list[LeafParamRecord]]:
"""Sample from the wrapped circuit.
The call goes to the public ``sample`` of the wrapped circuit and not to its ``_sample``
hook, because a circuit such as ``RatSPN`` prepares the sampling context in ``sample``.
Args:
num_samples: Number of samples to generate.
data: Tensor with NaN at the entries to sample; other entries are evidence.
is_mpe: If ``True``, return the most probable values instead of random samples.
cache: Optional cache for intermediate results.
return_leaf_params: If ``True``, also return the leaf parameters of the samples.
Returns:
Samples of shape ``(N, D)``, with the leaf-parameter records if requested.
"""
return self.module.sample(
num_samples=num_samples,
data=data,
is_mpe=is_mpe,
cache=cache,
return_leaf_params=return_leaf_params,
)
[docs]
def marginalize(
self,
marg_rvs: list[int],
prune: bool = True,
cache: Cache | None = None,
) -> MembershipCircuit | None:
"""Marginalize variables out of the wrapped circuit and wrap the result with the same test.
The structural marginalization is that of the wrapped circuit and has its limits: several
layer modules do not implement it. Missing values in the data (NaN) need no structural
marginalization and work for every supported circuit.
Args:
marg_rvs: Indices of the variables to marginalize out.
prune: Whether to prune modules that become unnecessary.
cache: Optional cache for intermediate results.
Returns:
Membership circuit over the remaining variables, or ``None`` if no variable remains. It
is validated when it is built if and only if this wrapper was.
"""
marginal = self.module.marginalize(marg_rvs, prune=prune, cache=cache)
if marginal is None:
return None
return MembershipCircuit(marginal, self.config, validate=self._validate_on_wrap)
def _expectation_maximization_step(
self,
data: Tensor,
bias_correction: bool = True,
*,
cache: Cache,
) -> None:
"""Perform an expectation-maximization step of the wrapped circuit.
Args:
data: Input data tensor.
bias_correction: Whether to apply the bias correction in leaf updates.
cache: Cache that a preceding log-likelihood pass has filled.
"""
self.module._expectation_maximization_step(data, bias_correction=bias_correction, cache=cache)
def extra_repr(self) -> str:
"""Return the shape of the wrapped circuit and the name of the test configuration."""
return f"{super().extra_repr()}, test={self.config.name()}"