"""Membership p-values: the bottom-up pass over a probabilistic circuit.
:func:`membership_pvalues` computes one p-value per row for the membership hypothesis "this row is a
sample of the circuit". Leaves turn their observed values into univariate p-values, product nodes
merge the p-values of their children with the product rule of the configuration and sum nodes merge
them with its sum rule. Every inner node clips its result to ``[0, 1]``.
The pass is a free function with one branch per supported module type. It does not use the
``log_likelihood`` methods of the modules, because a p-value is not a density, but it follows their
indexing: a node is one entry ``(feature, channel, repetition)`` of a module, and each branch brings
the children of every node of its module to the last axis of a tensor before it calls a rule.
Missing values (NaN) have marginal semantics. A node is missing if and only if every variable of its
scope is missing. A product node merges its observed children only and is missing if it has none. A
sum node is either missing or merges all its children; the root gives 1 for a row without any
observed value. The result for a row with missing values therefore equals the result of the circuit
in which the missing variables are marginalized out. This is a valid test of the observed part of a
row only if the missingness does not depend on the values of the row.
"""
from __future__ import annotations
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from numbers import Integral
from typing import Any, NamedTuple, TypeGuard, TypeVar, cast
import torch
from einops import rearrange
from torch import Tensor
from spflow.exceptions import (
InvalidParameterError,
InvalidTypeError,
InvalidWeightsError,
ShapeError,
StructureError,
UnsupportedOperationError,
)
from spflow.modules.leaves.leaf import LeafModule
from spflow.modules.module import Module
from spflow.modules.ops.cat import Cat
from spflow.modules.ops.split import Split
from spflow.modules.ops.split_by_index import SplitByIndex
from spflow.modules.ops.split_consecutive import SplitConsecutive
from spflow.modules.ops.split_interleaved import SplitInterleaved
from spflow.modules.products.elementwise_product import ElementwiseProduct
from spflow.modules.products.outer_product import OuterProduct
from spflow.modules.products.product import Product
from spflow.modules.rat.factorize import Factorize
from spflow.modules.sums.elementwise_sum import ElementwiseSum
from spflow.modules.sums.repetition_mixing_layer import RepetitionMixingLayer
from spflow.modules.sums.sum import Sum
from spflow.modules.wrapper.base import Wrapper
from spflow.utils.cache import Cache
from spflow.zoo.mc.combination import SumNodeContext
from spflow.zoo.mc.config import MembershipTestConfig
from spflow.zoo.mc.leaves import leaf_pvalues
from spflow.zoo.rat.rat_spn import RatSPN
_ModuleT = TypeVar("_ModuleT", bound=Module)
# Marker of a missing value in the data. _split_missing reads it and the validation probe of
# MembershipCircuit writes it; nothing else in the package knows it.
_MISSING_VALUE = float("nan")
# Key of the per-call memo in the cache. Each module is evaluated once per call, also if several
# parents share it.
_CACHE_KEY = "membership_pvalues"
_SUPPORTED_MODULES = (
"Sum, RepetitionMixingLayer, ElementwiseSum, Product, ElementwiseProduct, OuterProduct, Factorize, "
"Cat, SplitConsecutive / SplitInterleaved / SplitByIndex (as the direct input of ElementwiseProduct "
"or OuterProduct), RatSPN and the leaf families of spflow.zoo.mc.leaf_pvalues"
)
class _NodeValues(NamedTuple):
"""P-values of all nodes of one module for all rows.
Attributes:
p: P-values in ``float64`` of shape ``(N, features, channels, repetitions)``, in ``[0, 1]``;
1.0 where the node is missing.
observed: Boolean tensor of the same shape; ``False`` if every variable of the scope of the
node is missing in the row.
"""
p: Tensor
observed: Tensor
@dataclass(frozen=True)
class _PassContext:
"""State of one call of :func:`membership_pvalues`.
Attributes:
config: Test configuration.
data: Data of shape ``(N, D)`` in ``float64`` on the device of the model; missing entries
hold a placeholder.
observed: Boolean tensor of shape ``(N, D)``; ``False`` for a missing entry.
uniforms: Random numbers in ``[0, 1)`` of shape ``(N, D)`` in randomized mode, else ``None``.
cache: Memo of the module results of this call.
"""
config: MembershipTestConfig
data: Tensor
observed: Tensor
uniforms: Tensor | None
cache: Cache
# A branch of the pass: evaluates all nodes of one module of its type.
_Branch = Callable[[Any, _PassContext], _NodeValues]
[docs]
def membership_pvalues(
model: Module,
data: Tensor,
config: MembershipTestConfig,
*,
seed: int | None = None,
) -> Tensor:
"""Compute the membership p-value of every row of ``data`` under a circuit.
The null hypothesis of a row is that it is a sample of the distribution of ``model``. A small
p-value is evidence against it. The p-value is valid (its probability to fall below a level is at
most that level under the null hypothesis) if the rules of ``config`` are valid for their node
type; all rules of this package are, except that ``discrete_mode="midp"`` gives no guarantee.
The pass runs in ``float64`` and without gradients, whatever the dtype of the model. The model
is not moved, cast or modified. The parameters are read as they are: the accuracy of the
p-values of a ``float32`` model is limited by its rounded parameters, see
:func:`spflow.zoo.mc.leaf_pvalues`.
Supported modules: ``Sum``, ``RepetitionMixingLayer``, ``ElementwiseSum``, ``Product``,
``ElementwiseProduct``, ``OuterProduct``, ``Factorize``, ``Cat``, the three split modules as the
direct input of ``ElementwiseProduct`` or ``OuterProduct``, ``RatSPN`` and the leaf families of
:func:`spflow.zoo.mc.leaf_pvalues`. The circuit must be smooth and decomposable. A
``RepetitionMixingLayer`` over an input with a single repetition counts one child per weight; its
p-value is valid, but up to K times larger than that of the input.
Args:
model: Circuit with a single root node, that is with output shape ``(1, 1, 1)``.
data: Rows to test, of shape ``(N, D)`` with one column per variable; column ``j`` holds
variable ``j`` of the scope of the model. NaN marks a missing value: the row is then
tested on its observed variables only (marginal semantics). The missingness must be
independent of the values. A row without any observed value gets the p-value 1.
config: Test configuration: sum rule, product rule, test side and discrete mode.
seed: Seed of the random numbers of ``discrete_mode="randomized"``. One number is drawn per
row and column of ``data`` (also for columns outside the scope of the model), on the CPU,
so that the result does not depend on the device or on the structure of the circuit. It
does depend on the position of a row in ``data`` and on the number of columns. Two calls
with the same seed use the same numbers: evaluate a data set in one call, or use another
seed for every batch. ``None`` uses the global random number generator of torch. Ignored
in the other modes, apart from the check of its type and range.
Returns:
P-values of shape ``(N,)`` in ``float64``, in ``[0, 1]``, on the device of the model and
without gradients.
Raises:
InvalidTypeError: If ``model`` is not a module, ``config`` is not a
:class:`~spflow.zoo.mc.MembershipTestConfig`, ``data`` is not a real-valued tensor (for
example interval evidence), ``seed`` is not an integer, or a combination rule returns
something else than a ``float64`` tensor.
ShapeError: If ``data`` is not two-dimensional or has fewer columns than the scope of the
model needs, if the model does not have a single root node, if the shapes of the inputs
of a module do not fit together, or if a combination rule does not return one p-value
per node.
StructureError: If the children of a sum node do not have the same scope, so that a row
with missing values is missing for some children only (the sum is not smooth).
UnsupportedOperationError: If the circuit contains a module or a leaf that is not supported.
InvalidWeightsError: If the weights of a sum module are not finite.
InvalidParameterError: If ``seed`` lies outside ``[-2**63, 2**64 - 1]``, if a leaf has
degenerate parameters, if the coefficients of the sum rule fail their validity check or
if a p-value is NaN.
"""
_validate_arguments(model, data, config, seed)
with torch.no_grad():
device = _model_device(model, data)
data = data.detach().to(device=device, dtype=torch.float64)
filled, observed = _split_missing(data)
uniforms = None
if config.discrete_mode == "randomized":
uniforms = _draw_uniforms(data.shape, seed).to(device)
ctx = _PassContext(config=config, data=filled, observed=observed, uniforms=uniforms, cache=Cache())
root = _evaluate(model, ctx)
if tuple(root.p.shape) != (data.shape[0], 1, 1, 1):
raise ShapeError(
"The model must have a single root node, but its p-values have the shape "
f"{tuple(root.p.shape)} = (N, features, channels, repetitions). Put a Product over the "
"features, a Sum over the channels and a RepetitionMixingLayer over the repetitions."
)
pvalues = root.p.reshape(data.shape[0])
if bool(torch.isnan(pvalues).any()):
raise InvalidParameterError(
"A membership p-value is NaN. Check the coefficients of the sum rule and the parameters "
"of the model."
)
return pvalues
def _validate_arguments(model: Module, data: Tensor, config: MembershipTestConfig, seed: int | None) -> None:
"""Raise if an argument of :func:`membership_pvalues` has a wrong type or shape."""
if not isinstance(model, Module):
raise InvalidTypeError(f"model must be an SPFlow Module, got {type(model).__name__}.")
if not isinstance(config, MembershipTestConfig):
raise InvalidTypeError(f"config must be a MembershipTestConfig, got {type(config).__name__}.")
if not isinstance(data, Tensor):
raise InvalidTypeError(
f"data must be a torch.Tensor of shape (N, D), got {type(data).__name__}. Interval evidence is "
"not supported."
)
if data.is_complex() or data.dtype == torch.bool:
raise InvalidTypeError(f"data must be a real-valued tensor, got dtype {data.dtype}.")
if seed is not None:
# A bool is an Integral, but as a seed it is a mistake of the caller.
if isinstance(seed, bool) or not isinstance(seed, Integral):
raise InvalidTypeError(f"seed must be an integer or None, got {type(seed).__name__}.")
if not -(2**63) <= int(seed) < 2**64:
raise InvalidParameterError(
f"seed must lie in [-2**63, 2**64 - 1], the range of a torch generator, got {int(seed)}."
)
if data.dim() != 2:
raise ShapeError(f"data must have the shape (N, D), got {tuple(data.shape)}.")
num_columns = max(model.scope.query) + 1
if data.shape[1] < num_columns:
raise ShapeError(
f"data has {data.shape[1]} columns, but the scope of the model needs at least {num_columns}."
)
def _model_device(model: Module, data: Tensor) -> torch.device:
"""Return the device of the first parameter or buffer of the model, else that of the data."""
for parameter in model.parameters():
return parameter.device
for buffer in model.buffers():
return buffer.device
return data.device
def _split_missing(data: Tensor) -> tuple[Tensor, Tensor]:
"""Separate the values from the missing-value marker.
This is the only place of the pass that reads the marker ``_MISSING_VALUE`` (NaN).
Args:
data: Data of shape ``(N, D)`` in ``float64``.
Returns:
The data with every missing entry replaced by the placeholder 0.0, and the boolean tensor of
the observed entries. The pass never uses a p-value of a placeholder.
"""
observed = ~torch.isnan(data) # NaN is the only value that differs from itself: the test for the marker.
return torch.where(observed, data, 0.0), observed
def _draw_uniforms(shape: torch.Size, seed: int | None) -> Tensor:
"""Draw one uniform random number per row and data column on the CPU."""
generator = None
if seed is not None:
generator = torch.Generator(device="cpu")
generator.manual_seed(int(seed))
return torch.rand(tuple(shape), generator=generator, dtype=torch.float64, device="cpu")
def _child(module: Module) -> Module:
"""Return the single input module of ``module``."""
return cast(Module, module.inputs)
def _children(module: Module) -> list[Module]:
"""Return the input modules of a module that stores them in a module list."""
return list(cast(Iterable[Module], module.inputs))
def _is_plain(module: Module, cls: type[_ModuleT]) -> TypeGuard[_ModuleT]:
"""Return whether ``module`` is an instance of ``cls`` that computes the log-likelihood of ``cls``.
A subclass with its own ``log_likelihood`` connects its children in another way, which the pass
cannot know.
Raises:
UnsupportedOperationError: If ``module`` is an instance of a subclass of ``cls`` that
overrides ``log_likelihood``.
"""
if not isinstance(module, cls):
return False
if type(module).log_likelihood is not cls.log_likelihood:
raise UnsupportedOperationError(
f"Membership circuits do not support modules of type '{type(module).__name__}': it overrides "
f"the log_likelihood of {cls.__name__}. Supported: {_SUPPORTED_MODULES}."
)
return True
def _evaluate(module: Module, ctx: _PassContext) -> _NodeValues:
"""Return the p-values of all nodes of ``module``; the result is computed once per call.
The branch is called from here and not inside :func:`_branch`: the pass then needs two Python
frames per nested module, as ``log_likelihood`` does, and reaches the same nesting depth.
"""
values = ctx.cache.get(_CACHE_KEY, module)
if values is None:
values = _branch(module)(module, ctx)
ctx.cache.set(_CACHE_KEY, module, values)
return values
def _branch(module: Module) -> _Branch:
"""Return the function that evaluates modules of the type of ``module``.
The order matters where one supported type is a subclass of another one: leaves come first
(their ``inputs`` raises), ``RepetitionMixingLayer`` comes before ``Sum``.
Raises:
UnsupportedOperationError: If the type of ``module`` is not supported.
"""
if isinstance(module, LeafModule):
return _leaf
if _is_plain(module, RatSPN):
return _rat_spn
if _is_plain(module, Cat):
return _cat
if _is_plain(module, RepetitionMixingLayer):
return _repetition_mixing_layer
if _is_plain(module, Sum):
return _sum
if _is_plain(module, ElementwiseSum):
return _elementwise_sum
if _is_plain(module, Product):
return _product
if _is_plain(module, Factorize):
return _factorize
if _is_plain(module, ElementwiseProduct):
return _elementwise_product
if _is_plain(module, OuterProduct):
return _outer_product
name = type(module).__name__
if isinstance(module, Split):
raise UnsupportedOperationError(
f"Membership circuits support the split module '{name}' only as the direct input of an "
"ElementwiseProduct or an OuterProduct."
)
if isinstance(module, Wrapper):
raise UnsupportedOperationError(
f"Membership circuits do not look into the wrapper module '{name}'. Pass the wrapped circuit "
"(its attribute 'module') if it consists of supported modules."
)
raise UnsupportedOperationError(
f"Membership circuits do not support modules of type '{name}'. Supported: {_SUPPORTED_MODULES}."
)
def _rule_result(rule: object, merged: object, *shapes: tuple[int, ...]) -> Tensor:
"""Return the result of a combination rule; raise if it breaks the contract of ``combine``.
The check matters for user-defined rules. A result of another shape could broadcast against the
mask of the nodes and give every row the same p-value, and a result in another dtype has already
lost the accuracy that the pass promises.
Args:
rule: The rule that returned ``merged``.
merged: Return value of its ``combine``.
*shapes: The shapes that fit the nodes of the module.
"""
name = type(rule).__name__
if not isinstance(merged, Tensor):
raise InvalidTypeError(f"The rule {name} must return a torch.Tensor, got {type(merged).__name__}.")
if merged.dtype != torch.float64:
raise InvalidTypeError(f"The rule {name} must return float64 p-values, got dtype {merged.dtype}.")
if tuple(merged.shape) not in shapes:
expected = " or ".join(str(shape) for shape in dict.fromkeys(shapes))
raise ShapeError(
f"The rule {name} must return one p-value per node, that is the shape {expected} (its "
f"input without the children axis), got {tuple(merged.shape)}."
)
return merged
def _product_node(p: Tensor, observed: Tensor, ctx: _PassContext) -> _NodeValues:
"""Merge the children of product nodes.
Args:
p: P-values of the children with the children on the last axis, shape ``(..., K)``.
observed: Boolean tensor of the same shape. ``False`` marks a missing child and also a
padding slot that is no child at all.
ctx: State of the pass.
Returns:
Values of shape ``(...)``. A node without an observed child is missing.
"""
rule = ctx.config.product_rule
merged = _rule_result(rule, rule.combine(p, observed=observed), tuple(p.shape[:-1]))
node_observed = observed.any(-1)
return _NodeValues(torch.where(node_observed, merged.clamp(0.0, 1.0), 1.0), node_observed)
def _sum_node(module: Module, p: Tensor, observed: Tensor, weights: Tensor, ctx: _PassContext) -> _NodeValues:
"""Merge the children of sum nodes.
Args:
module: Sum module that holds the nodes.
p: P-values of the children with the children on the last axis, shape ``(N, ..., K)``.
observed: Boolean tensor of the same shape.
weights: Normalized weights of shape ``(..., K)`` without the row axis. Its leading axes
broadcast against those of ``p``.
ctx: State of the pass.
Returns:
Values with the leading axes of ``p`` broadcast against those of ``weights``.
Raises:
StructureError: If a sum node has both observed and missing children in one row.
"""
any_observed = observed.any(-1)
if bool((any_observed != observed.all(-1)).any()):
raise StructureError(
f"{type(module).__name__} with scope {module.scope}: the children of a sum node are not "
"missing together in a row with missing values. All children of a sum node must have the "
"same scope (the circuit must be smooth)."
)
context = SumNodeContext(num_children=weights.shape[-1], module=module, scope=module.scope)
try:
shape = torch.broadcast_shapes(p.shape[:-1], weights.shape[:-1])
except RuntimeError as error:
raise ShapeError(
f"{type(module).__name__} with scope {module.scope}: the p-values of the children with the "
f"shape {tuple(p.shape)} do not fit the weights with the shape {tuple(weights.shape)} (children "
"on the last axis)."
) from error
rule = ctx.config.sum_rule
merged = _rule_result(
rule,
rule.combine(p, weights=weights, observed=observed, context=context),
tuple(shape),
tuple(p.shape[:-1]),
)
node_observed = any_observed.expand(shape)
return _NodeValues(torch.where(node_observed, merged.expand(shape).clamp(0.0, 1.0), 1.0), node_observed)
def _normalized_weights(module: Module, ndim: int) -> Tensor:
"""Return the normalized weights of a sum module in ``float64``.
The weights are normalized here, in ``float64``, and not read from the ``weights`` property: for
a ``float32`` model that property is normalized only up to ``float32`` rounding.
"""
logits = module.logits
if logits.dim() != ndim:
raise ShapeError(
f"{type(module).__name__} with scope {module.scope}: the logits must have {ndim} dimensions, "
f"got the shape {tuple(logits.shape)}."
)
weights = torch.softmax(logits.detach().to(torch.float64), dim=module.sum_dim)
if not bool(torch.isfinite(weights).all()):
raise InvalidWeightsError(
f"{type(module).__name__} with scope {module.scope}: the weights are not finite."
)
return weights
def _require_children(module: Module, name: str, found: int, expected: int) -> None:
"""Raise if the number of children of the nodes of a module does not fit its weights or table."""
if found != expected:
raise ShapeError(
f"{type(module).__name__} with scope {module.scope}: expected {expected} {name}, got {found}."
)
def _leaf(module: LeafModule, ctx: _PassContext) -> _NodeValues:
"""Leaf nodes: univariate p-values of the columns of the leaf; a missing value gives a missing node."""
columns = list(module.scope.query)
uniforms = None if ctx.uniforms is None else ctx.uniforms[:, columns]
p = leaf_pvalues(
module,
ctx.data[:, columns],
side=ctx.config.side,
discrete_mode=ctx.config.discrete_mode,
uniforms=uniforms,
)
observed = rearrange(ctx.observed[:, columns], "n f -> n f 1 1").to(p.device).expand(p.shape)
return _NodeValues(torch.where(observed, p, 1.0), observed)
def _rat_spn(module: RatSPN, ctx: _PassContext) -> _NodeValues:
"""RAT-SPN: the nodes of the model are those of its root module."""
return _evaluate(module.root_node, ctx)
def _cat(module: Cat, ctx: _PassContext) -> _NodeValues:
"""Concatenation along the features or the channels: no node is merged."""
if module.dim not in (1, 2):
raise StructureError(f"Cat with scope {module.scope}: dim must be 1 or 2, got {module.dim}.")
parts = []
for child in _children(module): # A comprehension is a call of its own before Python 3.12.
parts.append(_evaluate(child, ctx))
other_axes = {tuple(n for axis, n in enumerate(part.p.shape) if axis != module.dim) for part in parts}
if len(other_axes) != 1:
raise ShapeError(
f"Cat with scope {module.scope}: the inputs must have the same shape except along "
f"dim={module.dim}, got the shapes {[tuple(part.p.shape) for part in parts]} = "
"(N, features, channels, repetitions)."
)
return _NodeValues(
torch.cat([part.p for part in parts], dim=module.dim),
torch.cat([part.observed for part in parts], dim=module.dim),
)
def _product(module: Product, ctx: _PassContext) -> _NodeValues:
"""Product: the children of the node ``(c, r)`` are the features of its input at ``(c, r)``."""
values = _evaluate(_child(module), ctx)
merged = _product_node(
rearrange(values.p, "n f c r -> n c r f"), rearrange(values.observed, "n f c r -> n c r f"), ctx
)
return _NodeValues(
rearrange(merged.p, "n c r -> n 1 c r"), rearrange(merged.observed, "n c r -> n 1 c r")
)
def _sum(module: Sum, ctx: _PassContext) -> _NodeValues:
"""Sum: the children of the node ``(f, co, r)`` are the input channels at ``(f, r)``."""
values = _evaluate(_child(module), ctx)
weights = _normalized_weights(module, 4) # (F, Ci, Co, R)
_require_children(module, "input channels", values.p.shape[2], weights.shape[1])
return _sum_node(
module,
rearrange(values.p, "n f ci r -> n f 1 r ci"),
rearrange(values.observed, "n f ci r -> n f 1 r ci"),
rearrange(weights, "f ci co r -> f co r ci"),
ctx,
)
def _repetition_mixing_layer(module: RepetitionMixingLayer, ctx: _PassContext) -> _NodeValues:
"""Mixture over the repetitions: the children of the node ``(f, c)`` are its input at ``(f, c, r)``.
An input with one repetition is read by every weight, as in the log-likelihood of the layer: the
node then has one child per weight, all with the same p-value.
"""
values = _evaluate(_child(module), ctx)
weights = _normalized_weights(module, 3) # (F, C, R)
num_repetitions = weights.shape[2]
if values.p.shape[3] not in (1, num_repetitions):
_require_children(module, "repetitions", values.p.shape[3], num_repetitions)
merged = _sum_node(
module,
values.p.expand(-1, -1, -1, num_repetitions),
values.observed.expand(-1, -1, -1, num_repetitions),
weights,
ctx,
)
return _NodeValues(merged.p.unsqueeze(-1), merged.observed.unsqueeze(-1))
def _elementwise_sum(module: ElementwiseSum, ctx: _PassContext) -> _NodeValues:
"""Elementwise sum: the children of the node ``(f, ci, co, r)`` are its inputs at ``(f, ci, r)``."""
weights = _normalized_weights(module, 5) # (F, Ci, Co, I, R)
inputs = []
for child in _children(module): # A comprehension is a call of its own before Python 3.12.
inputs.append(_evaluate(child, ctx))
parts = _stack_children(module, inputs, weights.shape[1])
_require_children(module, "input modules", parts.p.shape[-1], weights.shape[3])
merged = _sum_node(
module,
rearrange(parts.p, "n f ci r i -> n f ci 1 r i"),
rearrange(parts.observed, "n f ci r i -> n f ci 1 r i"),
rearrange(weights, "f ci co i r -> f ci co r i"),
ctx,
)
return _NodeValues(
rearrange(merged.p, "n f ci co r -> n f (ci co) r"),
rearrange(merged.observed, "n f ci co r -> n f (ci co) r"),
)
def _elementwise_product(module: ElementwiseProduct, ctx: _PassContext) -> _NodeValues:
"""Elementwise product: the children of the node ``(f, c, r)`` are its inputs at ``(f, c, r)``."""
parts = _stack_children(module, _product_inputs(module, ctx), module.out_shape.channels)
return _product_node(parts.p, parts.observed, ctx)
def _outer_product(module: OuterProduct, ctx: _PassContext) -> _NodeValues:
"""Outer product: the output channel ``c`` takes the channel ``table[c, i]`` of its ``i``-th input."""
inputs = _product_inputs(module, ctx)
table = module.unraveled_channel_indices # (output channels, inputs)
if table.dim() != 2 or table.shape[1] != len(inputs):
raise StructureError(
f"OuterProduct with scope {module.scope}: the channel table has the shape {tuple(table.shape)}, "
f"but the module has {len(inputs)} inputs."
)
selected = []
for position, part in enumerate(inputs):
channels = table[:, position].to(part.p.device)
if int(channels.max()) >= part.p.shape[2]:
raise ShapeError(
f"OuterProduct with scope {module.scope}: input {position} has {part.p.shape[2]} channels, "
f"but the channel table refers to channel {int(channels.max())}."
)
selected.append(_NodeValues(part.p[:, :, channels, :], part.observed[:, :, channels, :]))
parts = _stack_children(module, selected, table.shape[0])
return _product_node(parts.p, parts.observed, ctx)
def _factorize(module: Factorize, ctx: _PassContext) -> _NodeValues:
"""Factorize: the children of the node ``(o, c, r)`` are the input features of group ``o`` in ``r``."""
values = _evaluate(_children(module)[0], ctx)
member = module.indices > 0 # (input features, output features, repetitions)
if member.dim() != 3 or member.shape[0] != values.p.shape[1]:
raise ShapeError(
f"Factorize with scope {module.scope}: the factorization matrix has the shape "
f"{tuple(member.shape)}, but its input has {values.p.shape[1]} features."
)
if not bool((member.sum(1) == 1).all()) or not bool(member.any(0).all()):
raise StructureError(
f"Factorize with scope {module.scope}: every input feature must belong to exactly one output "
"feature in every repetition, and no output feature may be empty."
)
num_repetitions = max(values.p.shape[3], member.shape[2])
if values.p.shape[3] not in (1, num_repetitions) or member.shape[2] not in (1, num_repetitions):
_require_children(module, "repetitions", values.p.shape[3], member.shape[2])
p = values.p.expand(-1, -1, -1, num_repetitions)
observed = values.observed.expand(-1, -1, -1, num_repetitions)
member = member.to(p.device).expand(-1, -1, num_repetitions)
# The groups differ in size. slot[k, o, r] is the k-th input feature of group o; a group with fewer
# than K features is padded with features of other groups, which the mask removes again.
num_slots = int(member.sum(0).max())
order = torch.argsort(member.to(torch.int8), dim=0, descending=True, stable=True)
slot = order[:num_slots] # (K, O, R)
is_child = torch.gather(member, 0, slot)
index = rearrange(slot, "k o r -> 1 (o k) 1 r").expand(p.shape[0], -1, p.shape[2], -1)
children_p = rearrange(torch.gather(p, 1, index), "n (o k) c r -> n o c r k", k=num_slots)
children_observed = rearrange(torch.gather(observed, 1, index), "n (o k) c r -> n o c r k", k=num_slots)
return _product_node(children_p, children_observed & rearrange(is_child, "k o r -> 1 o 1 r k"), ctx)
def _product_inputs(module: ElementwiseProduct | OuterProduct, ctx: _PassContext) -> list[_NodeValues]:
"""Return the values of the inputs of a product layer; a split input gives one entry per part."""
children = _children(module)
if module.input_is_split:
return _split_parts(cast(Split, children[0]), ctx)
values = []
for child in children: # A comprehension is a call of its own before Python 3.12.
values.append(_evaluate(child, ctx))
return values
def _split_parts(split: Split, ctx: _PassContext) -> list[_NodeValues]:
"""Cut the values of the input of a split module into the parts that the split module returns.
The split modules return lists of tensors from ``log_likelihood`` and have no method that cuts a
given tensor, so their indexing is repeated here.
"""
name = type(split).__name__
if split.dim != 1:
raise UnsupportedOperationError(
f"Membership circuits support {name} along the features only (dim=1), got dim={split.dim}."
)
num_splits = split.num_splits
if _is_plain(split, SplitConsecutive) or _is_plain(split, SplitInterleaved):
values = _evaluate(_child(split), ctx)
num_features = values.p.shape[1]
if num_splits is None or num_splits < 1 or num_features % num_splits != 0:
raise ShapeError(
f"{name} with scope {split.scope}: {num_features} features cannot be split into "
f"{num_splits} parts of equal size."
)
if isinstance(split, SplitConsecutive):
size = num_features // num_splits
slices = [slice(i * size, (i + 1) * size) for i in range(num_splits)]
else:
slices = [slice(i, None, num_splits) for i in range(num_splits)]
return [_NodeValues(values.p[:, part], values.observed[:, part]) for part in slices]
if _is_plain(split, SplitByIndex):
values = _evaluate(_child(split), ctx)
parts = []
for group in split.indices:
index = torch.tensor(list(group), dtype=torch.long, device=values.p.device)
parts.append(_NodeValues(values.p.index_select(1, index), values.observed.index_select(1, index)))
return parts
raise UnsupportedOperationError(
f"Membership circuits do not support the split module '{name}'. Supported: SplitConsecutive, "
"SplitInterleaved and SplitByIndex."
)
def _stack_children(module: Module, parts: list[_NodeValues], num_channels: int) -> _NodeValues:
"""Stack the values of several inputs on a new last axis.
An input with one channel is used by every channel, as in the log-likelihood of the layers.
Raises:
ShapeError: If the inputs do not have the same shape after that.
"""
expanded = []
for part in parts:
if part.p.shape[2] == 1 and num_channels > 1:
part = _NodeValues(
part.p.expand(-1, -1, num_channels, -1), part.observed.expand(-1, -1, num_channels, -1)
)
expanded.append(part)
shapes = {tuple(part.p.shape) for part in expanded}
if len(shapes) != 1:
raise ShapeError(
f"{type(module).__name__} with scope {module.scope}: the inputs must have the same number of "
"features, channels (or one channel) and repetitions, got the shapes "
f"{sorted(shapes)} = (N, features, channels, repetitions)."
)
return _NodeValues(
torch.stack([part.p for part in expanded], dim=-1),
torch.stack([part.observed for part in expanded], dim=-1),
)