Source code for spflow.zoo.mc.leaves

"""Leaf p-values for Membership Circuits.

A leaf turns each observed value ``x`` into a univariate p-value. For every supported leaf family this
module computes three probabilities under the leaf distribution, ``lower = P(X < x)``,
``atom = P(X = x)`` and ``upper = P(X > x)``, and assembles the p-value of the requested test side from
them. Each of the three is computed directly (complementary error function, regularized incomplete
gamma functions, sums over the probability mass function) and never as one minus a probability near
1, so that p-values deep in a tail keep their relative accuracy.

The leaf modules of SPFlow offer no survival function and no tail-accurate cumulative distribution
function. The tail probabilities are therefore computed here from the public parameters of the leaves.
"""

from __future__ import annotations

import math
from dataclasses import dataclass
from typing import get_args

import torch
from einops import rearrange
from torch import Tensor
from torch.nn.functional import logsigmoid

from spflow.exceptions import (
    InvalidParameterCombinationError,
    InvalidParameterError,
    InvalidTypeError,
    ShapeError,
    UnsupportedOperationError,
)
from spflow.modules.leaves.bernoulli import Bernoulli
from spflow.modules.leaves.binomial import Binomial
from spflow.modules.leaves.categorical import Categorical
from spflow.modules.leaves.exponential import Exponential
from spflow.modules.leaves.gamma import Gamma
from spflow.modules.leaves.geometric import Geometric
from spflow.modules.leaves.histogram import Histogram
from spflow.modules.leaves.hypergeometric import Hypergeometric
from spflow.modules.leaves.laplace import Laplace
from spflow.modules.leaves.leaf import LeafModule
from spflow.modules.leaves.log_normal import LogNormal
from spflow.modules.leaves.normal import Normal
from spflow.modules.leaves.poisson import Poisson
from spflow.modules.leaves.uniform import Uniform
from spflow.zoo.mc.config import DiscreteMode, Side

_SUPPORTED_FAMILIES: tuple[type[LeafModule], ...] = (
    Normal,
    LogNormal,
    Exponential,
    Gamma,
    Laplace,
    Uniform,
    Histogram,
    Bernoulli,
    Categorical,
    Poisson,
    Geometric,
    Binomial,
    Hypergeometric,
)

# Smallest leaf p-value. It keeps log(p) and 1 / p finite in the combination rules.
_PVALUE_FLOOR = 1e-300
_SQRT_2 = math.sqrt(2.0)
# Largest first argument that is passed to the incomplete gamma functions: a larger count at a Poisson
# leaf is clamped to it, and a larger concentration of a Gamma leaf is refused. Poisson rates are limited
# to half of it, so that a clamped count lies so far above every rate that its tails are 0 and 1.
_MAX_GAMMA_SHAPE = 1e15
# torch.special.gammainc sums the power series of P(a, x) with at most 2000 terms. For a shape a above
# about 3e5 that is not enough where x lies more than 4.5 standard deviations (sqrt(a)) below a, and the
# result is too small; closer to a torch uses an asymptotic formula instead. A uniform asymptotic
# expansion replaces the series there. The region starts a little inside torch's own switch at 4.5,
# because the two tests of the boundary round differently.
_EXPANSION_MIN_SHAPE = 1e5
_EXPANSION_MIN_DEVIATIONS = 4.4
# Bound for counts and for the magnitude of log-probabilities. Products of bounded factors can
# overflow to -inf, which is harmless, but they cannot become 0 * inf = NaN.
_HUGE = 1e300


@dataclass(frozen=True)
class _Tails:
    """Probabilities of a leaf distribution around the observed values, each of shape ``(N, F, C, R)``.

    Attributes:
        lower: ``P(X < x)``.
        atom: ``P(X = x)``; ``None`` for continuous families.
        upper: ``P(X > x)``.
        ordered: ``False`` for a family whose values have no order (Categorical). Its values are then
            ranked by their probability, so that ``lower`` is the mass of all less likely values and
            ``upper`` the mass of all more likely ones, and every test side uses the lower p-value.
    """

    lower: Tensor
    atom: Tensor | None
    upper: Tensor
    ordered: bool = True


[docs] def leaf_pvalues( leaf: LeafModule, x: Tensor, *, side: Side = "both", discrete_mode: DiscreteMode = "exact", uniforms: Tensor | None = None, ) -> Tensor: """Compute the p-values of observed values under the distributions of a leaf module. With ``L = P(X < x)``, ``A = P(X = x)`` and ``R = P(X > x)`` under one leaf distribution, the left p-value is ``L + wl * A`` and the right p-value is ``R + wr * A``. Continuous families have no atom (``A = 0``) and ignore ``discrete_mode``. For discrete families the mode sets the weights: - ``"exact"``: ``wl = wr = 1``. The p-value is valid and conservative by up to one atom. The right p-value is ``P(X >= x)``: it includes the observed atom. - ``"midp"``: ``wl = wr = 0.5``. The mid-p value is **not** a valid p-value in general: for a Bernoulli leaf with success probability 0.5 and ``side="both"`` it equals 0.5 for both outcomes. - ``"randomized"``: ``wl = 1 - u`` and ``wr = u`` with the given ``u`` in ``[0, 1)``. For ``u`` uniform and independent of the row, the p-value is exactly uniform under the leaf distribution. The price is a decision that depends on the random number. The left and the right p-value of one observation use the same ``u`` and sum to 1. ``side="left"`` returns the left p-value, ``side="right"`` the right one and ``side="both"`` returns ``2 * min(left, right)``. The result is clamped to ``[1e-300, 1]``; the upper limit is necessary because a two-sided exact p-value of a discrete leaf can exceed 1. The values of a Categorical leaf have no order. Its p-value is the minimum-likelihood p-value, the same for every side: ``lt + w * eq`` with ``w = 1`` (exact), ``0.5`` (mid-p) or ``u`` (randomized), where ``lt`` is the probability of all categories that are less likely than the observed one and ``eq`` the probability of all categories that are exactly as likely (the observed one included). The comparison uses the model's own ``float64`` probabilities. A value that is not one of the categories ``0, ..., K - 1`` gets the smallest p-value ``1e-300``. No real value of ``x`` raises. For the ordered discrete families (Bernoulli, Poisson, Geometric, Binomial, Hypergeometric), a value that is not an integer or lies outside the support has no atom and uses ``L = P(X < x)`` and ``R = P(X > x)`` as they are: 2.5 at a Poisson leaf gives the left p-value ``P(X <= 2)`` and the right p-value ``P(X >= 3)``. Continuous families treat a value outside their support in the same way (``L = 0`` below the support, ``R = 0`` above it). Infinite values are accepted. Accuracy: all computations use ``float64``, whatever the dtype of the leaf. A leaf with ``float32`` parameters is evaluated at its rounded parameter values. Compared with the unrounded values, this limits the relative accuracy of its p-values to about 1e-6 near the centre of the distribution and to about 1e-4 in deep tails, where the rounding of the parameters is amplified. The incomplete gamma functions of torch (used by Gamma and Poisson) have a relative error of about 2e-9 where the shape argument is above 20 and the second argument lies within 30 percent of it (within 32 percent for shapes between 200 and 225). The shape argument is the concentration of a Gamma leaf, with ``rate * x`` as the second argument, and about ``x`` for a Poisson leaf, with the rate as the second argument. Where the power series of torch for the lower incomplete gamma function stops before it has converged (a shape above about 3e5 and a second argument more than 4.5 standard deviations below it), a uniform asymptotic expansion is used instead. For shape arguments above 1e7 the error grows with the shape: for a Gamma leaf to about 4e-10 at 1e10, 5e-9 at 1e12 and 7e-8 at 4e14; for a Poisson leaf, whose atom loses digits in addition, to about 2e-9 at 1e9, 1e-7 at 1e12 and 7e-6 at 4e14. Binomial and Hypergeometric leaves build a table of the probability mass function over their support in every call, with a size proportional to the largest support. The relative error of these two families is about 1e-15 times the largest count (the number of trials or the population size): about 4e-12 for a count of 1e4 and 6e-10 for a count of 1e6. In all other cases the relative error is well below 1e-9. A Histogram leaf stores its bin edges in ``float32``, so its p-values refer to the rounded edges; its bin probabilities are ``softmax(logits)``. Args: leaf: Leaf module of a supported family: Normal, LogNormal, Exponential, Gamma, Laplace, Uniform, Histogram, Bernoulli, Categorical, Poisson, Geometric (number of failures before the first success), Binomial or Hypergeometric. x: Observed values of shape ``(N, F)``: the columns of the leaf in the order of ``leaf.scope.query``, without NaN. The caller handles missing values and masks the result. The tensor is cast to ``float64`` and moved to the device of the leaf. side: Test side. ``"left"`` rejects small values, ``"right"`` rejects large values and ``"both"`` rejects values in either tail. discrete_mode: P-value definition at discrete leaves, see above. uniforms: Random numbers in ``[0, 1)`` of shape ``(N, F)``, one per row and feature, shared by all channels and repetitions. Required if and only if ``discrete_mode`` is ``"randomized"``. Returns: P-values of shape ``(N, F, C, R)`` with ``(F, C, R) = leaf.out_shape``, in ``float64`` on the device of the leaf, clamped to ``[1e-300, 1]`` and without gradients. Raises: InvalidTypeError: If ``leaf`` is not a leaf module or ``x`` is not a real-valued tensor. InvalidParameterCombinationError: If ``uniforms`` is missing in randomized mode or given in another mode. InvalidParameterError: If ``side`` or ``discrete_mode`` is unknown, if ``uniforms`` is not in ``[0, 1)``, if ``x`` contains NaN, if a parameter of the leaf lies outside the supported range (a Poisson rate above 5e14, a Gamma concentration above 1e15, a number of trials of a Binomial leaf that is negative, not finite or not an integer, a count of a Hypergeometric leaf that is not finite, a Uniform leaf whose ``high`` is not larger than ``low`` or whose width ``high - low`` is infinite), or if a tail probability is NaN because the parameters of the leaf are degenerate (NaN, or a rate, scale or width that is zero or infinite in ``float64``, which a ``float32`` leaf reaches when the exponential of its log-parameter underflows or overflows). ShapeError: If ``x`` is not ``(N, F)``, if ``uniforms`` does not have the shape of ``x``, or if the parameters of the leaf do not have the shape (features, channels, repetitions), so that the result would not have the shape ``(N, F, C, R)``. UnsupportedOperationError: If the leaf family is not supported, if the leaf is conditional or if its class overrides ``log_likelihood``. """ if side not in get_args(Side): raise InvalidParameterError(f"Unknown side '{side}'. Use one of {get_args(Side)}.") if discrete_mode not in get_args(DiscreteMode): raise InvalidParameterError( f"Unknown discrete_mode '{discrete_mode}'. Use one of {get_args(DiscreteMode)}." ) _require_supported(leaf) if not isinstance(x, Tensor): raise InvalidTypeError(f"x must be a torch.Tensor of shape (N, F), got {type(x).__name__}.") if x.is_complex() or x.dtype == torch.bool: raise InvalidTypeError(f"x must be a real-valued tensor, got dtype {x.dtype}.") if x.dim() != 2 or x.shape[1] != leaf.out_shape.features: raise ShapeError( f"x must have the shape (N, {leaf.out_shape.features}) for {type(leaf).__name__} with scope " f"{leaf.scope}, got {tuple(x.shape)}." ) x = x.detach().to(device=leaf.device, dtype=torch.float64) if torch.isnan(x).any(): raise InvalidParameterError("x must not contain NaN. The caller handles missing values.") weight_left, weight_right = _atom_weights(discrete_mode, uniforms, x) tails = _tail_probabilities(leaf, rearrange(x, "n f -> n f 1 1")) _require_no_nan(leaf, tails) exact = discrete_mode == "exact" if not tails.ordered: pvalues = _one_sided(tails.lower, tails.atom, tails.upper, weight_right, exact) else: left = _one_sided(tails.lower, tails.atom, tails.upper, weight_left, exact) right = _one_sided(tails.upper, tails.atom, tails.lower, weight_right, exact) if side == "left": pvalues = left elif side == "right": pvalues = right else: pvalues = 2.0 * torch.minimum(left, right) if tuple(pvalues.shape) != (x.shape[0], *leaf.out_shape): raise _shape_error( leaf, f"the leaf p-values have the shape {tuple(pvalues.shape)} instead of " f"{(x.shape[0], *leaf.out_shape)} = (N, features, channels, repetitions)", ) return pvalues.clamp(_PVALUE_FLOOR, 1.0)
def _require_supported(leaf: LeafModule) -> None: """Raise unless the leaf is an unconditional leaf of a supported family.""" if not isinstance(leaf, LeafModule): raise InvalidTypeError(f"leaf must be a LeafModule, got {type(leaf).__name__}.") name = type(leaf).__name__ supported = ", ".join(family.__name__ for family in _SUPPORTED_FAMILIES) if not isinstance(leaf, _SUPPORTED_FAMILIES): raise UnsupportedOperationError( f"Leaf p-values are not available for the leaf family {name}. Supported families: {supported}." ) if leaf.is_conditional: raise UnsupportedOperationError( f"Leaf p-values are not available for the conditional leaf {name} (parameter_fn is set). " f"Supported are unconditional leaves of the families: {supported}." ) # A subclass with its own log-likelihood does not have the distribution that its parameters say. if type(leaf).log_likelihood is not LeafModule.log_likelihood: raise UnsupportedOperationError( f"Leaf p-values are not available for {name}, because it overrides log_likelihood. " f"Supported are plain leaves of the families: {supported}." ) def _atom_weights( discrete_mode: DiscreteMode, uniforms: Tensor | None, x: Tensor ) -> tuple[Tensor | float, Tensor | float]: """Return the weights of the observed atom in the left and in the right p-value.""" if discrete_mode != "randomized": if uniforms is not None: raise InvalidParameterCombinationError( f"uniforms belong to discrete_mode='randomized' only, but discrete_mode is '{discrete_mode}'." ) return (1.0, 1.0) if discrete_mode == "exact" else (0.5, 0.5) if uniforms is None: raise InvalidParameterCombinationError( "discrete_mode='randomized' requires uniforms of shape (N, F)." ) if uniforms.shape != x.shape: raise ShapeError(f"uniforms must have the shape of x, {tuple(x.shape)}, got {tuple(uniforms.shape)}.") u = rearrange(uniforms.detach().to(device=x.device, dtype=torch.float64), "n f -> n f 1 1") if not ((u >= 0) & (u < 1)).all(): raise InvalidParameterError("uniforms must lie in [0, 1).") return 1.0 - u, u def _one_sided( tail: Tensor, atom: Tensor | None, opposite: Tensor, weight: Tensor | float, exact: bool ) -> Tensor: """Return the p-value ``tail + weight * atom`` of one test side.""" if atom is None: return tail pvalue = tail + weight * atom if exact: # tail + atom + opposite equals 1 only up to rounding. Where the opposite tail is exactly 0, the # p-value is 1 by definition, and the last bit of a sigmoid or softmax must not decide that. pvalue = torch.where(opposite == 0, 1.0, pvalue) return pvalue def _tail_probabilities(leaf: LeafModule, x: Tensor) -> _Tails: """Compute the tail probabilities of the leaf family at ``x`` of shape ``(N, F, 1, 1)``.""" if isinstance(leaf, Normal): return _normal_tails(_float64(leaf.loc), _float64(leaf.scale), x) if isinstance(leaf, LogNormal): # The clamp sends every x <= 0 to log(0) = -inf, which gives lower = 0 and upper = 1. return _normal_tails(_float64(leaf.loc), _float64(leaf.scale), torch.log(x.clamp_min(0.0))) if isinstance(leaf, Exponential): return _exponential_tails(leaf, x) if isinstance(leaf, Gamma): return _gamma_tails(leaf, x) if isinstance(leaf, Laplace): return _laplace_tails(leaf, x) if isinstance(leaf, Uniform): return _uniform_tails(leaf, x) if isinstance(leaf, Histogram): return _histogram_tails(leaf, x) if isinstance(leaf, Bernoulli): return _bernoulli_tails(leaf, x) if isinstance(leaf, Categorical): return _categorical_tails(leaf, x) if isinstance(leaf, Poisson): return _poisson_tails(leaf, x) if isinstance(leaf, Geometric): return _geometric_tails(leaf, x) if isinstance(leaf, Binomial): return _binomial_tails(leaf, x) if isinstance(leaf, Hypergeometric): return _hypergeometric_tails(leaf, x) raise UnsupportedOperationError( # pragma: no cover - _require_supported rejects these leaves first f"Leaf p-values are not implemented for the leaf family {type(leaf).__name__}." ) def _float64(parameter: Tensor) -> Tensor: """Detach a leaf parameter and cast it to ``float64``.""" return parameter.detach().to(dtype=torch.float64) def _is_integer(x: Tensor) -> Tensor: """Mark the finite integer values; an infinite value equals its own floor and must not count.""" return torch.isfinite(x) & (x == torch.floor(x)) def _shape_error(leaf: LeafModule, problem: str) -> ShapeError: """Build the error for a leaf whose parameters are not (features, channels, repetitions)-shaped.""" shapes = ", ".join(f"{name}: {tuple(value.shape)}" for name, value in leaf.params().items()) return ShapeError( f"{type(leaf).__name__} with out_shape {tuple(leaf.out_shape)}: {problem}. Its parameters have " f"the shapes ({shapes}). Pass (features, channels, repetitions)-shaped parameters when building " "the leaf (with one more last axis for the categories or bins)." ) def _require_rank(leaf: LeafModule, rank: int, **parameters: Tensor) -> None: """Raise if a parameter that a lookup table is built from does not have the expected rank.""" for name, value in parameters.items(): if value.dim() != rank: raise _shape_error(leaf, f"'{name}' must have {rank} dimensions, got {value.dim()}") def _require_no_nan(leaf: LeafModule, tails: _Tails) -> None: """Raise if a tail probability is NaN; ``x`` has no NaN, so the parameters of the leaf are degenerate. The check is on the tail probabilities and not on the p-values, because the exact mode replaces a p-value by 1 where the opposite tail is 0, which would hide a NaN for one test side. """ probabilities = [tails.lower, tails.upper] + ([] if tails.atom is None else [tails.atom]) if not any(torch.isnan(probability).any() for probability in probabilities): return raise InvalidParameterError( f"{type(leaf).__name__} with scope {leaf.scope}: a tail probability is NaN although x has no NaN. " "The parameters of the leaf are degenerate: NaN, or a rate, scale or width that is zero or " f"infinite in float64. Parameter ranges: {_parameter_ranges(leaf)}." ) def _parameter_ranges(leaf: LeafModule) -> str: """Describe the smallest and the largest value of every parameter of the leaf for an error message.""" return ", ".join( f"{name} in [{value.min().item():g}, {value.max().item():g}]" for name, value in leaf.params().items() ) def _require_parameters(leaf: LeafModule, valid: Tensor, requirement: str) -> None: """Raise if a parameter of the leaf lies outside the range for which its tails are computed.""" if bool(valid.all()): return raise InvalidParameterError( f"{type(leaf).__name__} with scope {leaf.scope}: {requirement}. Parameter ranges: " f"{_parameter_ranges(leaf)}." ) def _regularized_gamma(shape: Tensor, value: Tensor, *, upper: bool) -> Tensor: """Return the regularized incomplete gamma function ``P(shape, value)``, or ``Q = 1 - P`` if ``upper``. The functions of torch are used, except where the power series of ``P`` in torch stops before it has converged (see ``_EXPANSION_MIN_SHAPE``): there ``P`` comes from :func:`_lower_gamma_expansion`. Args: shape: First argument, already broadcast to the shape of ``value``. value: Second argument. upper: Whether to return ``Q`` instead of ``P``. """ result: Tensor = torch.special.gammaincc(shape, value) if upper else torch.special.gammainc(shape, value) truncated = (shape > _EXPANSION_MIN_SHAPE) & ( value < shape - _EXPANSION_MIN_DEVIATIONS * torch.sqrt(shape) ) if not bool(truncated.any()): return result # Entries outside the region get harmless arguments, so that the expansion has no inf - inf there. expansion = _lower_gamma_expansion( torch.where(truncated, shape, 2.0 * _EXPANSION_MIN_SHAPE), torch.where(truncated, value, _EXPANSION_MIN_SHAPE), ) return torch.where(truncated, 1.0 - expansion if upper else expansion, result) def _lower_gamma_expansion(shape: Tensor, value: Tensor) -> Tensor: """Return ``P(shape, value)`` for a large shape and a value below it. Uniform asymptotic expansion of Temme (NIST Digital Library of Mathematical Functions, 8.12.7) with its first two coefficients. With ``mu = value / shape - 1`` and ``eta = -sqrt(2 * (mu - log(1 + mu)))``:: P = erfc(-eta * sqrt(shape / 2)) / 2 - exp(-shape * eta^2 / 2) / sqrt(2 * pi * shape) * (c0 + c1 / shape) The neglected terms are of the relative order ``shape^-2``. """ mu = (value - shape) / shape half_eta_squared = mu - torch.log1p(mu) eta = -torch.sqrt(2.0 * half_eta_squared) c0 = 1.0 / mu - 1.0 / eta c1 = 1.0 / eta**3 - 1.0 / mu**3 - 1.0 / mu**2 - 1.0 / (12.0 * mu) leading = 0.5 * torch.special.erfc(-eta * torch.sqrt(shape / 2.0)) correction = torch.exp(-shape * half_eta_squared) / torch.sqrt(2.0 * math.pi * shape) * (c0 + c1 / shape) expansion: Tensor = (leading - correction).clamp(0.0, 1.0) return expansion def _partial_sums(mass: Tensor) -> tuple[Tensor, Tensor]: """Return ``below[..., i] = sum(mass[..., :i])`` and ``above[..., i] = sum(mass[..., i:])``, ``i = 0..S``. Both are sums of non-negative terms that start at their own end of the table, so neither loses accuracy in its tail, and ``below[..., 0]`` and ``above[..., S]`` are exactly 0. """ zero = torch.zeros_like(mass[..., :1]) below = torch.cat([zero, mass.cumsum(dim=-1)], dim=-1) above = torch.cat([mass.flip(-1).cumsum(dim=-1).flip(-1), zero], dim=-1) return below, above def _lookup(table: Tensor, index: Tensor) -> Tensor: """Read ``table[f, c, r, index[n, f, 0, 0]]`` for every row; the result has shape ``(N, F, C, R)``.""" return torch.take_along_dim(table.unsqueeze(0), index.unsqueeze(-1), dim=-1).squeeze(-1) def _log_choose(n: Tensor, k: Tensor) -> Tensor: """Logarithm of the binomial coefficient ``C(n, k)``; ``k`` is clamped into ``[0, n]`` to stay finite.""" k = torch.minimum(k.clamp_min(0.0), n) return torch.lgamma(n + 1.0) - torch.lgamma(k + 1.0) - torch.lgamma(n - k + 1.0) def _normal_tails(loc: Tensor, scale: Tensor, x: Tensor) -> _Tails: """Tails of a normal distribution; erfc keeps the relative accuracy of both tails.""" z = (x - loc) / (scale * _SQRT_2) return _Tails(lower=0.5 * torch.special.erfc(-z), atom=None, upper=0.5 * torch.special.erfc(z)) def _exponential_tails(leaf: Exponential, x: Tensor) -> _Tails: """Tails of an exponential distribution with support ``[0, inf)``.""" t = _float64(leaf.rate) * x.clamp_min(0.0) return _Tails(lower=-torch.expm1(-t), atom=None, upper=torch.exp(-t)) def _gamma_tails(leaf: Gamma, x: Tensor) -> _Tails: """Tails of a gamma distribution from the two regularized incomplete gamma functions.""" concentration = _float64(leaf.concentration) # A NaN concentration passes this check and is reported with the other degenerate parameters. _require_parameters( leaf, ~(concentration > _MAX_GAMMA_SHAPE), f"concentrations above {_MAX_GAMMA_SHAPE:g} are not supported", ) concentration, t = torch.broadcast_tensors(concentration, _float64(leaf.rate) * x.clamp_min(0.0)) return _Tails( lower=_regularized_gamma(concentration, t, upper=False), atom=None, upper=_regularized_gamma(concentration, t, upper=True), ) def _laplace_tails(leaf: Laplace, x: Tensor) -> _Tails: """Tails of a Laplace distribution; the tail on the far side of the location is the small one.""" u = (x - _float64(leaf.loc)) / _float64(leaf.scale) small = 0.5 * torch.exp(-u.abs()) # 1 - small is at least 0.5, so this subtraction loses no accuracy. large = 1.0 - small below_loc = u < 0 return _Tails( lower=torch.where(below_loc, small, large), atom=None, upper=torch.where(below_loc, large, small) ) def _uniform_tails(leaf: Uniform, x: Tensor) -> _Tails: """Tails of a uniform distribution on ``[low, high]``, each measured from its own end.""" low, high = _float64(leaf.low), _float64(leaf.high) # With high < low the two tails would change places without any NaN, and with equal bounds only a # value at the bounds would show one. NaN bounds are reported with the other degenerate parameters. _require_parameters(leaf, ~(high <= low), "'high' must be larger than 'low'") width = high - low # The width of a leaf with bounds near the largest numbers overflows; every value then got the tail 0. _require_parameters(leaf, ~torch.isinf(width), "the width 'high - low' must be finite in float64") return _Tails( lower=((x - low) / width).clamp(0.0, 1.0), atom=None, upper=((high - x) / width).clamp(0.0, 1.0) ) def _histogram_tails(leaf: Histogram, x: Tensor) -> _Tails: """Tails of a piecewise-constant density: the mass of the bins on one side plus a part of the own bin.""" logits = _float64(leaf.logits) _require_rank(leaf, 4, logits=logits) edges = leaf.bin_edges.detach().to(device=logits.device, dtype=torch.float64) probs = torch.softmax(logits, dim=-1) below, above = _partial_sums(probs) # bucketize warns about a column slice of the data, which is not contiguous. bin_index = (torch.bucketize(x.contiguous(), edges, right=True) - 1).clamp(0, probs.shape[-1] - 1) left_edge, right_edge = edges[bin_index], edges[bin_index + 1] width = right_edge - left_edge mass = _lookup(probs, bin_index) return _Tails( lower=_lookup(below, bin_index) + mass * ((x - left_edge) / width).clamp(0.0, 1.0), atom=None, upper=_lookup(above, bin_index + 1) + mass * ((right_edge - x) / width).clamp(0.0, 1.0), ) def _bernoulli_tails(leaf: Bernoulli, x: Tensor) -> _Tails: """Tails of a Bernoulli distribution on ``{0, 1}``.""" logits = _float64(leaf.logits) # sigmoid(-logits) instead of 1 - sigmoid(logits): no cancellation for probabilities near 1. p_one, p_zero = torch.sigmoid(logits), torch.sigmoid(-logits) return _Tails( lower=torch.where(x > 1, 1.0, torch.where(x > 0, p_zero, 0.0)), atom=torch.where(x == 0, p_zero, torch.where(x == 1, p_one, 0.0)), upper=torch.where(x < 0, 1.0, torch.where(x < 1, p_one, 0.0)), ) def _categorical_tails(leaf: Categorical, x: Tensor) -> _Tails: """Masses of the categories that are less likely than, as likely as and more likely than ``x``.""" logits = _float64(leaf.logits) _require_rank(leaf, 4, logits=logits) probs = torch.softmax(logits, dim=-1) num_categories = probs.shape[-1] # One table entry per category. Ties are exact equalities of the model's own float64 probabilities. ascending = torch.sort(probs, dim=-1).values below, above = _partial_sums(ascending) num_less = torch.searchsorted(ascending, probs, right=False) num_less_or_equal = torch.searchsorted(ascending, probs, right=True) less = torch.gather(below, -1, num_less) equal = (num_less_or_equal - num_less) * probs more = torch.gather(above, -1, num_less_or_equal) # A value that is not a category has probability 0: no mass below it, all mass above it. is_category = _is_integer(x) & (x >= 0) & (x <= num_categories - 1) category = x.clamp(0, num_categories - 1).long() return _Tails( lower=torch.where(is_category, _lookup(less, category), 0.0), atom=torch.where(is_category, _lookup(equal, category), 0.0), upper=torch.where(is_category, _lookup(more, category), 1.0), ordered=False, ) def _poisson_tails(leaf: Poisson, x: Tensor) -> _Tails: """Tails of a Poisson distribution from the regularized incomplete gamma functions.""" rate = _float64(leaf.rate) # A rate that is not finite gives a NaN atom and is reported with the other degenerate parameters. _require_parameters( leaf, ~(torch.isfinite(rate) & (rate > _MAX_GAMMA_SHAPE / 2.0)), f"rates above {_MAX_GAMMA_SHAPE / 2.0:g} are not supported", ) # P(X < x) = P(X <= first_not_below - 1) and P(X > x) = P(X >= first_above). first_not_below, first_above = torch.ceil(x), torch.floor(x) + 1.0 # For an integer k >= 1: P(X <= k - 1) = Q(k, rate) and P(X >= k) = P(k, rate). The incomplete gamma # functions return NaN for a negative first argument, so they only see clamped arguments. shape_lower, rate_lower = torch.broadcast_tensors(first_not_below.clamp(1.0, _MAX_GAMMA_SHAPE), rate) shape_upper, rate_upper = torch.broadcast_tensors(first_above.clamp(1.0, _MAX_GAMMA_SHAPE), rate) lower = torch.where(first_not_below >= 1, _regularized_gamma(shape_lower, rate_lower, upper=True), 0.0) upper = torch.where(first_above >= 1, _regularized_gamma(shape_upper, rate_upper, upper=False), 1.0) # The clamp keeps the log-pmf free of inf - inf for infinite and huge x; its value there is 0. count = x.clamp(0.0, _MAX_GAMMA_SHAPE) log_pmf = torch.special.xlogy(count, rate) - rate - torch.lgamma(count + 1.0) atom = torch.where(_is_integer(x) & (x >= 0), torch.exp(log_pmf), 0.0) return _Tails(lower=lower, atom=atom, upper=upper) def _geometric_tails(leaf: Geometric, x: Tensor) -> _Tails: """Tails of a geometric distribution on ``{0, 1, ...}`` (number of failures before the first success).""" logits = _float64(leaf.logits) log_p = logsigmoid(logits).clamp_min(-_HUGE) log_q = logsigmoid(-logits).clamp_min(-_HUGE) # P(X < x) = 1 - q^first_not_below and P(X > x) = q^first_above, with exponents of at least 0. first_not_below = torch.ceil(x).clamp(0.0, _HUGE) first_above = (torch.floor(x) + 1.0).clamp(0.0, _HUGE) atom = torch.where(_is_integer(x) & (x >= 0), torch.exp(x.clamp(0.0, _HUGE) * log_q + log_p), 0.0) return _Tails( lower=-torch.expm1(first_not_below * log_q), atom=atom, upper=torch.exp(first_above * log_q) ) def _binomial_tails(leaf: Binomial, x: Tensor) -> _Tails: """Tails of a binomial distribution from a table of its probability mass function.""" total_count, logits = _float64(leaf.total_count), _float64(leaf.logits) _require_rank(leaf, 3, total_count=total_count, logits=logits) _require_parameters( leaf, torch.isfinite(total_count) & (total_count >= 0) & (total_count == torch.floor(total_count)), "'total_count' must be a finite integer that is not negative", ) log_p = rearrange(logsigmoid(logits).clamp_min(-_HUGE), "f c r -> f c r 1") log_q = rearrange(logsigmoid(-logits).clamp_min(-_HUGE), "f c r -> f c r 1") n = rearrange(total_count, "f c r -> f c r 1") k = torch.arange(int(total_count.max().item()) + 1, dtype=torch.float64, device=logits.device) failures = (n - k).clamp_min(0.0) log_pmf = _log_choose(n, k) + k * log_p + failures * log_q return _table_tails(torch.where(k <= n, torch.exp(log_pmf), 0.0), x) def _hypergeometric_tails(leaf: Hypergeometric, x: Tensor) -> _Tails: """Tails of a hypergeometric distribution from a table of its probability mass function.""" successes, population, draws = _float64(leaf.K), _float64(leaf.N), _float64(leaf.n) _require_rank(leaf, 3, K=successes, N=population, n=draws) # A count that is not finite has no table: the size of the table would not be an integer. _require_parameters( leaf, torch.isfinite(successes) & torch.isfinite(population) & torch.isfinite(draws), "'K', 'N' and 'n' must be finite", ) num_successes = rearrange(successes, "f c r -> f c r 1") num_failures = rearrange(population - successes, "f c r -> f c r 1") n = rearrange(draws, "f c r -> f c r 1") largest = torch.minimum(n, num_successes) k = torch.arange(int(largest.max().item()) + 1, dtype=torch.float64, device=draws.device) log_pmf = ( _log_choose(num_successes, k) + _log_choose(num_failures, n - k) - _log_choose(num_successes + num_failures, n) ) in_support = (k >= n - num_failures) & (k <= largest) return _table_tails(torch.where(in_support, torch.exp(log_pmf), 0.0), x) def _table_tails(pmf: Tensor, x: Tensor) -> _Tails: """Tails of an integer-valued family from its pmf table over ``0..S-1`` of shape ``(F, C, R, S)``.""" size = pmf.shape[-1] below, above = _partial_sums(pmf) in_table = _is_integer(x) & (x >= 0) & (x <= size - 1) # Clamp before the cast: huge and infinite values have no int64 representation. return _Tails( lower=_lookup(below, torch.ceil(x).clamp(0, size).long()), atom=torch.where(in_table, _lookup(pmf, x.clamp(0, size - 1).long()), 0.0), upper=_lookup(above, (torch.floor(x) + 1.0).clamp(0, size).long()), )