Skip to content

Distributions (optix.distributions)

Gamma, Normal, Dirichlet and Categorical distributions with their sufficient statistics and conjugate updates. See Probability distributions for a guided tour.

Probability distributions for variational Bayes and conjugate updates.

Two layers:

  • [functional][optix.distributions.functional]: pure tensor functions (means, expectations, entropies, log-densities, KL divergences), one canonical signature per family, safe to inline into compiled kernels;
  • classes (Gamma, Dirichlet, Categorical, Normal) that accept several parameterisations, store the one they were given, derive the others on demand, and dispatch kl_divergence and posterior.

Accumulated sufficient statistics (SuffStats subclasses) are mergeable containers consumed by posterior and the fit classmethods.

Gamma

Gamma(shape, rate=None, *, scale=None, mean=None, validate=False, cache=False, dtype=None, device=None)

Bases: Distribution

Gamma distribution over x > 0, elementwise (event shape ()).

p(x) = b^a x^(a − 1) exp(−b x) / Γ(a) with shape a and rate b.

Note

Give shape with exactly one of rate, scale or mean; the given pair is stored, everything else is derived on access. The canonical parameters of [functional][optix.distributions.functional] are (shape, rate).

Exponential family: T(x) = (log x, x), η = (a − 1, −b), A = log Γ(a) − a log b, h(x) = 1.

Create a Gamma distribution from one of its parameterisations.

Parameters:

Name Type Description Default
shape Tensor or float

Shape a > 0.

required
rate Tensor or float

Rate b > 0.

None
scale Tensor or float

Scale 1 / b.

None
mean Tensor or float

Mean a / b (the "mean / shape" parameterisation (μ, ν)).

None
validate bool

Check the parameter values (synchronises). Default False.

False
cache bool

Cache derived parameters (see Distribution).

False
dtype dtype | None

Default: those of the tensors (see Distribution).

None
device dtype | None

Default: those of the tensors (see Distribution).

None

shape property

shape

Shape a, (*batch).

rate property

rate

Rate b, (*batch).

scale property

scale

Scale 1 / b, (*batch).

mean property

mean

E[x] = a / b.

variance property

variance

Var[x] = a / b².

mean_log property

mean_log

E[log x] = ψ(a) − log b.

In the mean / shape parameterisation it is computed as log μ − (log ν − ψ(ν)), without cancellation.

mean_inv property

mean_inv

E[1 / x] = b / (a − 1); inf where a ≤ 1.

from_mean_shape classmethod

from_mean_shape(mean, shape, **kwargs)

Gamma with mean μ and shape ν (rate ν / μ).

entropy

entropy()

H = a − log b + log Γ(a) + (1 − a) ψ(a).

log_prob

log_prob(value)

a log b − log Γ(a) + (a − 1) log x − b x.

natural_params

natural_params()

(a − 1, −b).

log_normalizer

log_normalizer()

A = log Γ(a) − a log b.

expected_stats

expected_stats()

(E[log x], E[x]).

from_natural classmethod

from_natural(eta_log_x, eta_x)

Gamma with natural parameters (a − 1, −b).

to_torch

to_torch()

torch.distributions.Gamma(shape, rate).

fit classmethod

fit(data, weight=None, *, dim=REQUIRED, mean=None, init=None, niter=16)

Maximum-likelihood Gamma from samples or accumulated statistics.

With n = ∑ₙ wₙ, x̄ = ∑ₙ wₙ xₙ / n and l̄ = ∑ₙ wₙ log xₙ / n, the shape ν solves log ν − ψ(ν) = c (see fit_gamma_shape) with

  • mean free: μ = x̄ and c = log x̄ − l̄;
  • mean fixed: μ = mean, ρ = x̄ / μ and c = (ρ − 1 − log ρ) + (log x̄ − l̄).

Parameters:

Name Type Description Default
data (GammaStats, Tensor or array - like)

Either accumulated statistics, or positive samples xₙ > 0. Samples are reduced with GammaStats.from_samples. A Tensor is reduced in one go. Other array-likes (numpy arrays, memory maps, zarr or h5py arrays, ...) are read in chunks along the first reduced dim, sized by the memory budget of config, and their statistics are merged in float64. Statistics are best accumulated in float64: in float32, the Jensen gap c ≈ 1 / (2ν) loses its digits for large ν.

required
weight Tensor

Non-negative frequency weights (or a boolean mask) of the samples, broadcastable to data. Samples only.

None
dim int or sequence of int or None

Reduced dims of the samples (None: all, (): none). Required with samples; not accepted with statistics.

REQUIRED
mean Tensor or float

Fixed mean; only the shape is fitted.

None
init Gamma

Returned where n = 0; otherwise those entries are NaN.

None
niter int

Newton iterations.

16

Returns:

Type Description
Gamma

Stored in the mean / shape parameterisation (μ, ν), with the batch shape of the statistics (broadcast with mean and init). Gradients stay finite where n = 0.

Raises:

Type Description
TypeError

If data is neither a GammaStats nor array-like, or if dim is missing with samples.

Normal

Normal(mean, var=None, *, std=None, precision=None, validate=False, cache=False, dtype=None, device=None)

Bases: Distribution

Normal distribution, elementwise (event shape ()).

Note

Give exactly one of var, std or precision. It is stored as given; the others are derived on access. The canonical parameters of [functional][optix.distributions.functional] are (mean, precision).

A "diagonal" multivariate Normal is this class with a trailing batch dim of size K; reduce it yourself, e.g. kl_divergence(q, p).sum(-1).

Exponential family: T(x) = (x, x²), η = (λμ, −λ/2), A = λμ² / 2 − ½ log λ, log h = −½ log(2π).

Create a Normal distribution from one of its parameterisations.

Parameters:

Name Type Description Default
mean Tensor or float

Mean μ.

required
var Tensor or float

Variance σ² (also the unnamed second argument: Normal(mu, sigma2)).

None
std Tensor or float

Standard deviation σ.

None
precision Tensor or float

Precision λ = 1 / σ². Zero is a flat (improper) direction: entropy and KL are infinite, conjugate updates stay valid.

None
validate bool

See Gamma.

False
cache bool

See Gamma.

False
dtype bool

See Gamma.

False
device bool

See Gamma.

False

mean property

mean

Mean μ = E[x], (*batch).

precision property

precision

Precision λ = 1 / σ².

var property

var

Variance σ².

variance property

variance

Variance Var[x] = σ².

Alias of var.

std property

std

Standard deviation σ = √σ².

mean_sq property

mean_sq

E[x²] = μ² + σ².

entropy

entropy()

H = (1 + log(2π) − log λ) / 2.

log_prob

log_prob(value)

(log λ − log(2π) − λ (x − μ)²) / 2.

natural_params

natural_params()

(λμ, −λ/2).

log_normalizer

log_normalizer()

A = λμ² / 2 − ½ log λ.

expected_stats

expected_stats()

(E[x], E[x²]) = (μ, μ² + σ²).

from_natural classmethod

from_natural(eta_x, eta_x_sq)

Normal with natural parameters (λμ, −λ/2).

to_torch

to_torch()

torch.distributions.Normal(mean, std).

Dirichlet

Dirichlet(concentration, *, validate=False, cache=False, dtype=None, device=None)

Bases: Distribution

Dirichlet distribution over the simplex (event shape (K,)).

p(π) = Γ(α₀) ∏ₖ πₖ^(αₖ − 1) / ∏ₖ Γ(αₖ) with α₀ = ∑ₖ αₖ.

Note

Exponential family: T(π) = log π, η = α − 1, A = ∑ₖ log Γ(αₖ) − log Γ(α₀), h = 1.

Create a Dirichlet distribution.

Parameters:

Name Type Description Default
concentration (*batch, K) Tensor

Concentration α > 0.

required
validate bool

See Gamma.

False
cache bool

See Gamma.

False
dtype bool

See Gamma.

False
device bool

See Gamma.

False

concentration property

concentration

Concentration α, (*batch, K).

mean property

mean

E[π] = α / α₀, (*batch, K).

variance property

variance

Var[πₖ] = αₖ (α₀ − αₖ) / (α₀² (α₀ + 1)).

mean_log property

mean_log

E[log π] = ψ(α) − ψ(α₀), (*batch, K).

entropy

entropy()

∑ₖ log Γ(αₖ) − log Γ(α₀) + (α₀ − K) ψ(α₀) − ∑ₖ (αₖ − 1) ψ(αₖ).

log_prob

log_prob(value)

log Γ(α₀) − ∑ₖ log Γ(αₖ) + ∑ₖ (αₖ − 1) log πₖ.

natural_params

natural_params()

(α − 1,).

log_normalizer

log_normalizer()

A = ∑ₖ log Γ(αₖ) − log Γ(α₀).

expected_stats

expected_stats()

(E[log π],).

from_natural classmethod

from_natural(eta_log_x)

Dirichlet with natural parameters (α − 1,).

to_torch

to_torch()

torch.distributions.Dirichlet(concentration).

fit classmethod

fit(data, init, weight=None, *, dim=REQUIRED, niter=16)

Maximum-likelihood Dirichlet from samples or accumulated statistics.

With n = ∑ₙ wₙ and sₖ = ∑ₙ wₙ log xₙₖ, maximises n (log Γ(α₀) − ∑ₖ log Γ(αₖ)) + ∑ₖ (αₖ − 1) sₖ with fit_dirichlet, started at init.

Parameters:

Name Type Description Default
data (DirichletStats, Tensor or array - like)

Either accumulated statistics, or points xₙ of the simplex with shape (..., K). Points are reduced with DirichletStats.from_samples. A Tensor is reduced in one go. Other array-likes (numpy arrays, memory maps, zarr or h5py arrays, ...) are read in chunks along the first reduced dim, sized by the memory budget of config, and their statistics are merged in float64.

required
init Dirichlet or (..., K) Tensor

Starting point (required: Newton's method only converges locally; pass the current estimate). Returned where n = 0.

required
weight Tensor

Non-negative frequency weights (or a boolean mask) of the points, broadcastable to data.shape[:-1]. Points only.

None
dim int or sequence of int or None

Reduced batch dims of the points (None: all, (): none; the last dim is the event). Required with points; not accepted with statistics.

REQUIRED
niter int

Iterations.

16

Returns:

Type Description
Dirichlet

Batch shape: that of the statistics, broadcast with init.

Raises:

Type Description
TypeError

If data is neither a DirichletStats nor array-like, or if dim is missing with points.

Categorical

Categorical(probs=None, *, logits=None, validate=False, cache=False, dtype=None, device=None)

Bases: Distribution

Categorical distribution over K categories (event shape ()).

Note

Give exactly one of probs or logits; it is stored as given (unnormalised, categories in the last dim) and the normalised forms are derived on access. Categorical(logits=elog_pi + elog_lik) is the variational update of responsibilities.

Values. The representation of a value is read from its dtype:

  • integer dtype: labels in [0, K), shape (*batch,);
  • floating or boolean dtype: one-hot or soft assignments r, shape (*batch, K); log_prob(r) = ∑ₖ rₖ log pₖ is the expected log-likelihood used by variational Bayes.

Integers always mean labels, including the int64 output of torch.nn.functional.one_hot: cast it with .float() or .bool() first. sample returns int64 labels, or float one-hot vectors with one_hot=True. Expectations (mean = probs), entropy and KL do not depend on the representation. There is no reparameterised sampling (as in torch, rsample raises).

Exponential family: T(z) = onehot(z), η = log p (up to an additive constant), A = logsumexp(η), E[T] = p.

Create a Categorical distribution.

Parameters:

Name Type Description Default
probs (*batch, K) Tensor

Non-negative weights, normalised by their sum.

None
logits (*batch, K) Tensor

Log-weights, normalised by log_softmax.

None
validate bool

See Gamma. validate=True also makes log_prob check that integer labels are in range (kept by expand, indexing, to and detach).

False
cache bool

See Gamma. validate=True also makes log_prob check that integer labels are in range (kept by expand, indexing, to and detach).

False
dtype bool

See Gamma. validate=True also makes log_prob check that integer labels are in range (kept by expand, indexing, to and detach).

False
device bool

See Gamma. validate=True also makes log_prob check that integer labels are in range (kept by expand, indexing, to and detach).

False

num_categories property

num_categories

Number of categories K.

logits property

logits

Normalised logits log p, (*batch, K).

probs property

probs

Normalised probabilities p, (*batch, K).

mean property

mean

E[onehot(z)] = p, (*batch, K).

variance property

variance

Var[zₖ] = pₖ (1 − pₖ) for one-hot z, (*batch, K).

params

params()

Normalised logits (log p,), unexpanded.

entropy

entropy()

H = −∑ₖ pₖ log pₖ (0 log 0 = 0, finite gradients).

log_prob

log_prob(value)

Log-probability of labels, or expected log-likelihood.

Note

Without validate=True, labels are not range-checked: an out-of-range label raises a RuntimeError on the CPU and a device-side assert on CUDA (which leaves the CUDA context unusable), so validate labels when their source is not trusted.

Parameters:

Name Type Description Default
value Tensor

Integer labels (*sample, *batch): log p[value]. Or floating / boolean one-hot or soft assignments (*sample, *batch, K): ∑ₖ rₖ log pₖ (with 0 log 0 = 0).

required

Returns:

Type Description
Tensor

Broadcast of the value's batch shape and batch_shape.

Raises:

Type Description
ValueError

If the last dim of an assignment is not K, or if a label is out of range and the object was built with validate=True (that check synchronises and is skipped while compiling).

sample

sample(sample_shape=(), *, one_hot=False)

Samples: int64 labels, or float one-hot vectors (one_hot).

Labels have shape (*sample_shape, *batch); one-hot vectors (*sample_shape, *batch, K) in the distribution's dtype.

natural_params

natural_params()

(η,): the stored log-weights, up to an additive constant.

For logits these are the given logits, for probs their logarithm (unnormalised), so that log_normalizer is logsumexp(η).

log_normalizer

log_normalizer()

A = logsumexp(η) (zero when normalised).

expected_stats

expected_stats()

(E[onehot(z)],) = (p,), whatever the view.

from_natural classmethod

from_natural(eta)

Distribution with logits eta (η), stored as given.

to_torch

to_torch()

torch.distributions.Categorical(logits=logits).

Distribution

Base of all distributions: parameterisations, shapes and dispatch.

Parameterisations. A family declares several parameterisations (_forms: tuples of parameter names). An object stores exactly the tensors of the one it was built with (form) and derives every other parameter on demand (_derive), e.g. the precision of a Normal given by its variance. params() returns the canonical parameterisation (_canonical), which is what the [functional][optix.distributions.functional] kernels take.

Later families declare their forms the same way, e.g. (sketch):

class MultivariateNormal(Distribution):
    _forms = {
        ("mean", "covariance"): (1, 2),
        ("mean", "precision"): (1, 2),
        ("mean", "scale_tril"): (1, 2),
        ("mean", "precision_tril"): (1, 2),
    }
    _canonical = ("mean", "precision_tril")
    _event_ndim = 1
    # _check_events: mean (K,) against matrices (K, K)
    # _derive("precision_tril"): cholesky / flip trick, ...


class Wishart(Distribution):
    _forms = {("df", "scale"): (0, 2), ("df", "rate"): (0, 2),
              ("df", "mean"): (0, 2)}   # mean = df * scale

and a conjugate update returns the form in which it is additive (a Wishart posterior in (df, rate)).

Caching. Derived quantities are recomputed on every access unless caching is switched on (cache=True at construction, or q.cache = True). An entry is reused only while the stored tensors keep the version counters they had when it was computed, so an in-place change of a parameter (s.mul_(2)) invalidates it. The cache is bypassed while compiling (traced functions have no side effects and never see it), when a stored tensor requires gradients (a cached graph would break a second backward pass) and for inference tensors (which have no version counter). A derived parameter has the broadcast shape of the stored tensors it is computed from (e.g. the rate of a Gamma given by a scalar shape and a per-pixel mean is per-pixel), and is cached with that shape.

Shapes. Parameters are stored with their own shapes (not expanded to the batch shape), so a scalar prior against per-pixel posteriors costs nothing; public parameter attributes and method results are expand views of shape batch_shape + event. Returned tensors must not be modified in place (clone() first).

dtype and device follow the parameter tensors (promoted between floating dtypes); the configuration is used only when no parameter is a floating-point tensor.

Objects are immutable by convention. Values are not checked unless validate=True is passed or validate is called (both synchronise with the host).

form property

form

Names of the stored parameters (the parameterisation given).

cache property writable

cache

Whether derived quantities are cached (off while compiling).

batch_shape property

batch_shape

Broadcast batch shape of the parameters.

event_shape property

event_shape

Shape of one sample.

dtype property

dtype

Floating dtype of the parameters.

device property

device

Device of the parameters.

mean property

mean

E[x].

variance property

variance

Var[x] (elementwise / marginal).

params

params()

Canonical parameters, unexpanded, for functional kernels.

stored

stored()

Stored parameters, unexpanded, in form order.

validate

validate()

Check parameter values (synchronises); return self.

Skipped while compiling.

Raises:

Type Description
ValueError

If a stored parameter violates its constraint.

expand

expand(batch_shape)

Same distribution with a larger batch shape (no copy).

Parameters:

Name Type Description Default
batch_shape sequence of int

Target batch shape, broadcast-compatible with batch_shape.

required

Returns:

Type Description
Distribution

A new object sharing the stored tensors.

__getitem__

__getitem__(index)

Index the batch dims (basic indexing only); event dims kept.

to

to(device=None, dtype=None)

Copy on another device and/or floating dtype (new object).

detach

detach()

Same distribution with detached parameters.

entropy

entropy()

Differential (or discrete) entropy, shape batch_shape.

log_prob

log_prob(value)

Log-density at value of shape (*sample, *batch, *event).

natural_params

natural_params()

Natural parameters, ordered like expected_stats.

log_normalizer

log_normalizer()

Log-normalizer A(η), shape batch_shape.

expected_stats

expected_stats()

E[T(x)], ordered like natural_params.

from_natural classmethod

from_natural(*eta)

Distribution with natural parameters eta (η).

to_torch

to_torch()

Equivalent torch.distributions object (no validation).

sample

sample(sample_shape=())

Samples (no gradient), delegated to to_torch.

rsample

rsample(sample_shape=())

Reparameterised samples, delegated to to_torch.

kl

kl(other)

kl_divergence(self, other).

posterior

posterior(stats, **known)

posterior(self, stats, **known).

GammaStats

GammaStats(n, sum_x, sum_log_x)

Bases: SuffStats

Statistics of a Gamma likelihood: (n, sum_x, sum_log_x).

Build the statistics from their fields.

Parameters:

Name Type Description Default
n Tensor

Total weight ∑ₙ wₙ.

required
sum_x Tensor

∑ₙ wₙ xₙ.

required
sum_log_x Tensor

∑ₙ wₙ log xₙ.

required

from_samples classmethod

from_samples(x, weight=None, *, dim, dtype=None)

Statistics of observed positive samples.

Parameters:

Name Type Description Default
x Tensor

Samples > 0.

required
weight Tensor

Non-negative frequency weights (or a boolean mask), broadcastable to x.

None
dim int or sequence of int or None

Reduced dims (None: all, (): none). Required.

required
dtype dtype

dtype of the result (the reduction runs in x's dtype).

None

Returns:

Type Description
GammaStats

log x uses max(x, tiny), so zero samples of zero weight contribute nothing.

from_expectations classmethod

from_expectations(log_x, x, weight=None, *, dim, dtype=None)

Statistics of latent samples given E[log x] and E[x].

The arguments are the fields of Gamma.expected_stats(); weight, dim and dtype as in from_samples.

NormalStats

NormalStats(n, mean, scatter)

Bases: SuffStats

Statistics of a Normal likelihood, central form (n, mean, scatter).

mean = ∑ₙ wₙ xₙ / n and scatter = ∑ₙ wₙ (xₙ − mean)², the same state as optix.stats.Moments(order=2). Raw power sums are never formed, so large offsets do not destroy the scatter in float32.

References

  1. Pébay P. Formulas for robust, one-pass parallel computation of covariances and arbitrary-order statistical moments. Sandia National Laboratories report SAND2008-6212, 2008. doi:10.2172/1028931
BibTeX
@techreport{pebay2008,
  author = {P{'e}bay, P.},
  title = {Formulas for robust, one-pass parallel
           computation of covariances and arbitrary-order
           statistical moments},
  institution = {Sandia National Laboratories},
  number = {SAND2008-6212},
  year = {2008},
  doi = {10.2172/1028931}
}

Build the statistics from their fields.

Parameters:

Name Type Description Default
n Tensor

Total weight.

required
mean Tensor

Weighted mean (any value where n = 0, conventionally 0).

required
scatter Tensor

Weighted sum of squared deviations from mean.

required

sum_x property

sum_x

∑ₙ wₙ xₙ = n · mean (in the fields' dtype).

sum_x_sq property

sum_x_sq

∑ₙ wₙ xₙ² = scatter + n · mean² (in the fields' dtype).

from_samples classmethod

from_samples(x, weight=None, *, dim, dtype=None)

Statistics of observed samples (two passes, central form).

See from_samples of GammaStats.

from_expectations classmethod

from_expectations(x, x_sq, weight=None, *, dim, dtype=None)

Statistics of latent samples given E[x] and E[x²].

scatter = ∑ₙ wₙ (E[x²] − E[x]²) + ∑ₙ wₙ (E[x] − mean)².

from_moments classmethod

from_moments(moments)

(count, mean, m2) of an optix.stats.Moments.

mean and m2 are not copied; the count is stored as a float64 (or int64) count.

Requires order >= 2 and at least one update.

DirichletStats

DirichletStats(n, sum_log_x)

Bases: SuffStats

Statistics of a Dirichlet likelihood: (n, sum_log_x).

Build the statistics from their fields.

Parameters:

Name Type Description Default
n Tensor

Total weight ∑ₙ wₙ, shape (*batch).

required
sum_log_x (*batch, K) Tensor

∑ₙ wₙ log xₙ.

required

from_samples classmethod

from_samples(x, weight=None, *, dim, dtype=None)

Statistics of observed points x of the simplex (..., K).

weight broadcasts against x.shape[:-1]; dim are batch dims (the last dim of x is the event); see GammaStats.from_samples.

from_expectations classmethod

from_expectations(log_x, weight=None, *, dim, dtype=None)

Statistics of latent probability vectors given E[log x].

log_x is Dirichlet.expected_stats().log_x (or Dirichlet.mean_log), shape (..., K).

CategoricalStats

CategoricalStats(counts)

Bases: SuffStats

Statistics of a categorical likelihood: counts (*batch, K).

Build the statistics from the counts.

Parameters:

Name Type Description Default
counts (*batch, K) Tensor

Weighted counts ∑ₙ wₙ onehot(zₙ) (or ∑ₙ wₙ pₙ for soft assignments). n = counts.sum(-1). Stored as int64 when integral (unweighted labels), else float64, whatever dtype= says (see SuffStats).

required

n property

n

Total weight counts.sum(-1).

from_samples classmethod

from_samples(x, weight=None, *, dim, dtype=None)

Statistics of one-hot or soft assignments x (..., K).

See from_samples of GammaStats; for integer labels use from_labels.

from_expectations classmethod

from_expectations(x, weight=None, *, dim, dtype=None)

Statistics of latent labels given their probabilities E[x].

x is Categorical.expected_stats().x (the responsibilities).

from_labels classmethod

from_labels(index, num_classes, weight=None, *, dim, dtype=None)

Statistics of integer labels in [0, num_classes).

Note

The labels are scattered into a (*kept, K) buffer: no one-hot tensor of the data's size is built. Weights are summed in their own floating dtype (integer or boolean weights in the configuration's), then stored in float64.

Parameters:

Name Type Description Default
index Tensor

Integer labels; all its dims are batch dims.

required
num_classes int

Number of categories K.

required
weight Tensor | None

As in from_samples of GammaStats (dtype is accepted for symmetry; counts are int64 without weights, float64 with).

None
dim Tensor | None

As in from_samples of GammaStats (dtype is accepted for symmetry; counts are int64 without weights, float64 with).

None
dtype Tensor | None

As in from_samples of GammaStats (dtype is accepted for symmetry; counts are int64 without weights, float64 with).

None

SuffStats

Weighted sufficient statistics of samples from one family.

Holds ∑ₙ wₙ T(xₙ) and the total weight n = ∑ₙ wₙ over a set of samples (observed values, or expectations of latent ones). This is what models accumulate over batches and what posterior and the fit classmethods consume.

Fields have shape (*batch, *field_event) and are broadcast against each other. dtype: the statistics of a batch are reduced in the data's own dtype (no data-sized upcast); dtype= in the constructors casts only the reduced result, which is how a float64 running state is obtained from float32 data. Counts (n, and the counts of CategoricalStats) are small and exact whatever the data dtype: int64 when unweighted, float64 when they are sums of weights (a float32 count stops counting past 2²⁴). Merging an int64 count with a float64 one gives a float64 count, and dtype, to and the constructors' dtype= apply to the other fields only.

Statistics merge with + (out of place), add_ (in place, also available as merge) and sum (over batch dims); zeros() is the identity of + and n = 0 entries are legal everywhere. Weights must be non-negative (not checked).

n property

n

Total weight ∑ₙ wₙ, shape broadcastable to the batch.

batch_shape property

batch_shape

Broadcast batch shape of the fields.

event_shape property

event_shape

Event shape of the statistics (that of the family).

dtype property

dtype

dtype of the fields other than the count (see the class notes).

For CategoricalStats, whose only field is a count, the dtype of the counts.

device property

device

Device of the fields.

astuple

astuple()

Fields, in declaration order (unexpanded).

__add__

__add__(other)

Merge, out of place, on broadcast batch shapes.

__radd__

__radd__(other)

0 + s, so that sum([s1, s2, ...]) works.

add_

add_(other)

Merge other into self, in place; return self.

self's fields must have the full batch shape and own their memory (build it with zeros or copy). other is cast to self's dtype and device first, so a float64 accumulator accepts float32 batch statistics. An int64 count that receives a float64 (weighted) count is replaced by a float64 tensor (the only field that is not updated in place).

merge

merge(other)

Alias of add_.

This is the Reducer.merge name.

scale

scale(factor)

Statistics with the total weight multiplied by factor.

Used for tempering, subsampling corrections and stochastic VB.

sum

sum(dim=None)

Merge along batch dims (None: all); event dims are kept.

Negative dims count from the last batch dim.

to

to(device=None, dtype=None)

Copy on another device and/or floating dtype.

Unlike optix.stats.Reducer.to, this returns a new object. The count keeps its int64 / float64 dtype.

copy

copy()

Independent copy with full-shape, owned fields (an accumulator).

state_dict

state_dict()

{"class", "args", "state"}, as Reducer.state_dict.

from_state_dict classmethod

from_state_dict(state)

Rebuild statistics saved with state_dict.

zeros classmethod

zeros(batch_shape=(), *, event_shape=(), dtype=None, device=None)

Empty accumulator (identity of +) with owned fields.

Parameters:

Name Type Description Default
batch_shape sequence of int

Batch shape.

()
event_shape sequence of int

Event shape of the family ((K,) for Dirichlet and Categorical statistics).

()
dtype dtype | None

Default: the configuration. Pass torch.float64 for a running state accumulated over many batches: float32 sums lose their low digits as they grow. The count is int64 (it becomes float64 when a weighted count is merged into it).

None
device dtype | None

Default: the configuration. Pass torch.float64 for a running state accumulated over many batches: float32 sums lose their low digits as they grow. The count is int64 (it becomes float64 when a weighted count is merged into it).

None

GammaExpectations

Bases: NamedTuple

E[T(x)] of a Gamma, ordered like its natural parameters.

NormalExpectations

Bases: NamedTuple

E[T(x)] of a Normal, ordered like its natural parameters.

DirichletExpectations

Bases: NamedTuple

E[T(x)] of a Dirichlet, ordered like its natural parameters.

CategoricalExpectations

Bases: NamedTuple

E[onehot(z)] (the probabilities), like the natural parameters.

kl_divergence

kl_divergence(q, p)

KL(q ‖ p), elementwise over the broadcast batch shape.

Parameters:

Name Type Description Default
q Distribution

Distributions with the same event shape and broadcastable batch shapes. Broadcasting is right-aligned: a prior with one value per class (nc,) matches a posterior (*batch, nc); with the class axis first, (nc, H, W), index the prior as p[:, None, None].

required
p Distribution

Distributions with the same event shape and broadcastable batch shapes. Broadcasting is right-aligned: a prior with one value per class (nc,) matches a posterior (*batch, nc); with the class axis first, (nc, H, W), index the prior as p[:, None, None].

required

Returns:

Type Description
Tensor

Shape broadcast(q.batch_shape, p.batch_shape); event dims are reduced, batch dims never are. Neither operand is expanded: the kernels run on each operand's own parameter shapes and only the final arithmetic broadcasts. The value is not clamped at zero.

Raises:

Type Description
NotImplementedError

If the pair of types has no registered divergence.

ValueError

If the event shapes differ, the batch shapes do not broadcast or the devices differ.

posterior

posterior(prior, stats, **known)

Conjugate posterior of prior given likelihood statistics.

Parameters:

Name Type Description Default
prior Distribution

Conjugate prior.

required
stats SuffStats

Weighted sufficient statistics of the observations (weights must be non-negative; this is not checked). Tempering is posterior(prior, stats.scale(c)).

required
**known Tensor

Fixed parameters of the likelihood, required by some pairs (e.g. shape for a Gamma likelihood, mean or precision for a Normal one).

{}

Returns:

Type Description
Distribution

Same type as prior, batch shape broadcast(prior.batch_shape, stats.batch_shape, known), stored in the parameterisation where the update is additive. No value is validated and nothing synchronises.

Raises:

Type Description
NotImplementedError

If the pair has no registered update.

ValueError

If the event shapes differ or the batch shapes do not broadcast.

TypeError

If a required known parameter is missing.