The distributions package contains parameterizable probability distributions
and sampling functions. This allows the construction of stochastic computation
graphs and stochastic gradient estimators for optimization. This package
generally follows the design of the TensorFlow Distributions package.
It is not possible to directly backpropagate through random samples. However,
there are two main methods for creating surrogate functions that can be
backpropagated through. These are the score function estimator/likelihood ratio
estimator/REINFORCE and the pathwise derivative estimator. REINFORCE is commonly
seen as the basis for policy gradient methods in reinforcement learning, and the
pathwise derivative estimator is commonly seen in the reparameterization trick
in variational autoencoders. Whilst the score function only requires the value
of samples f(x), the pathwise derivative requires the derivative
f′(x). The next sections discuss these two in a reinforcement learning
example. For more details see
.
When the probability density function is differentiable with respect to its
parameters, we only need sample() and
log_prob() to implement REINFORCE:
Δθ=αr∇θlogπθ(a∣s)
where θ are the parameters, α is the learning rate,
r is the reward and πθ(a∣s) is the probability of
taking action in state given policy .
In practice we would sample an action from the output of a network, apply this
action in an environment, and then use log_prob to construct an equivalent
loss function. Note that we use a negative because optimizers use gradient
descent, whilst the rule above assumes gradient ascent. With a categorical
policy, the code for implementing REINFORCE would be as follows:
probs=policy_network(state)# Note that this is equivalent to what used to be called multinomialm=Categorical(probs)action=m.sample()next_state,reward=env.step(action)loss=-m.log_prob(
Pathwise derivative
The other way to implement these stochastic/policy gradients would be to use the
reparameterization trick from the
rsample() method, where the
parameterized random variable can be constructed via a parameterized
deterministic function of a parameter-free random variable. The reparameterized
sample therefore becomes differentiable. The code for implementing the pathwise
derivative would be as follows:
params=policy_network(state)m=Normal(*params)# Any distribution with .has_rsample == True could work based on the applicationaction=m.rsample()next_state,reward=env.step(action)# Assuming that reward is differentiableloss=-rewardloss.backward()
Returns a dictionary from argument names to
Constraint objects that
should be satisfied by each argument of this distribution. Args that
are not tensors need not appear in this dict.
Returns tensor containing all values supported by a discrete
distribution. The result will enumerate over dimension 0, so the shape
of the result will be (cardinality,) + batch_shape + event_shape
(where event_shape = () for univariate distributions).
Note that this enumerates over all batched tensors in lock-step
[[0, 0], [1, 1], …]. With expand=False, enumeration happens
along dim 0, but with the remaining batch dimensions being
singleton dimensions, [[0], [1], ...
To iterate over the full Cartesian product use
itertools.product(m.enumerate_support()).
Parameters:
expand (bool) – whether to expand the support over the
batch dims to match the distribution’s batch_shape.
Returns the shape of a single sample (without batching).
expand(batch_shape, _instance=None)
Returns a new distribution instance (or populates an existing instance
provided by a derived class) with batch dimensions expanded to
batch_shape. This method calls expand on
the distribution’s parameters. As such, this does not allocate new
memory for the expanded distribution instance. Additionally,
this does not repeat any args checking or parameter broadcasting in
__init__.py, when an instance is first created.
Parameters:
batch_shape (torch.Size) – the desired expanded size.
icdf(value)
Returns the inverse cumulative density/mass function evaluated at
value.
Generates a sample_shape shaped reparameterized sample or sample_shape
shaped batch of reparameterized samples if the distribution parameters
are batched.
The default behavior mimics Python’s assert statement: validation
is on by default, but is disabled if Python is run in optimized mode
(via python-O). Validation may be expensive, so you may want to
disable it once a model is working.
ExponentialFamily is the abstract base class for probability distributions belonging to an
exponential family, whose probability mass/density function is defined below
pF(x;θ)=exp(⟨t(x),θ⟩−F(θ)+k(x))
where θ denotes the natural parameters, t(x) denotes the sufficient statistic,
F(θ) is the log normalizer function for a given family and k(x) is the carrier
measure.
entropy()
Method to compute the entropy using Bregman divergence of the log normalizer.
Creates a Binomial distribution parameterized by total_count and
either probs or logits (but not both). total_count must be
broadcastable with probs/logits.
Samples from a Cauchy (Lorentz) distribution. The distribution of the ratio of
independent normally distributed random variables with means 0 follows a
Cauchy distribution.
Example:
>>> m=Cauchy(torch.tensor([0.0]),torch.tensor([1.0]))>>> m.sample()# sample from a Cauchy distribution with loc=0 and scale=1tensor([ 2.3214])
Parameters:
loc (float or Tensor) – mode or median of the distribution.
scale (float or Tensor) – half width at half maximum.
Creates a continuous Bernoulli distribution parameterized by probs
or logits (but not both).
The distribution is supported in [0, 1] and parameterized by ‘probs’ (in
(0,1)) or ‘logits’ (real-valued). Note that, unlike the Bernoulli, ‘probs’
does not correspond to a probability and ‘logits’ does not correspond to
log-odds, but the same names are used due to the similarity with the
Bernoulli. See [1] for more details.
[1] The continuous Bernoulli: fixing a pervasive error in variational
autoencoders, Loaiza-Ganem G and Cunningham JP, NeurIPS 2019.
https://arxiv.org/abs/1907.06845
Creates a Generalized Pareto distribution parameterized by loc, scale, and concentration.
The Generalized Pareto distribution is a family of continuous probability distributions on the real line.
Special cases include Exponential (when loc = 0, concentration = 0), Pareto (when concentration > 0,
loc = scale / concentration), and Uniform (when concentration = -1).
This distribution is often used to model the tails of other distributions. This implementation is based on the
implementation in TensorFlow Probability.
Example:
>>> m=GeneralizedPareto(torch.tensor([0.1]),torch.tensor([2.0]),torch.tensor([0.4]))>>> m.sample()# sample from a Generalized Pareto distribution with loc=0.1, scale=2.0, and concentration=0.4tensor([ 1.5623])
Parameters:
loc (float or Tensor) – Location parameter of the distribution
scale (float or Tensor) – Scale parameter of the distribution
concentration (float or Tensor) – Concentration parameter of the distribution
Reinterprets some of the batch dims of a distribution as event dims.
This is mainly useful for changing the shape of the result of
log_prob(). For example to create a diagonal Normal distribution with
the same shape as a Multivariate Normal distribution (so they are
interchangeable), you can:
>>> m=Kumaraswamy(torch.tensor([1.0]),torch.tensor([1.0]))>>> m.sample()# sample from a Kumaraswamy distribution with concentration alpha=1 and beta=1tensor([ 0.1729])
Parameters:
concentration1 (float or Tensor) – 1st concentration parameter of the distribution
(often referred to as alpha)
concentration0 (float or Tensor) – 2nd concentration parameter of the distribution
(often referred to as beta)
LKJ distribution for lower Cholesky factor of correlation matrices.
The distribution is controlled by concentration parameter η
to make the probability of the correlation matrix M generated from
a Cholesky factor proportional to det(M)η−1. Because of that,
when concentration==1, we have a uniform distribution over Cholesky
factors of correlation matrices:
Note that this distribution samples the
Cholesky factor of correlation matrices and not the correlation matrices
themselves and thereby differs slightly from the derivations in [1] for
the LKJCorr distribution. For sampling, this uses the Onion method from
[1] Section 3.
Example:
>>> l=LKJCholesky(3,0.5)>>> l.sample()# l @ l.T is a sample of a correlation 3x3 matrixtensor([[ 1.0000, 0.0000, 0.0000], [ 0.3516, 0.9361, 0.0000], [-0.1899, 0.4748, 0.8593]])
Parameters:
dimension (dim) – dimension of the matrices
concentration (float or Tensor) – concentration/shape parameter of the
distribution (often referred to as eta)
References
[1] Generating random correlation matrices based on vines and extended onion method (2009),
Daniel Lewandowski, Dorota Kurowicka, Harry Joe.
Journal of Multivariate Analysis. 100. 10.1016/j.jmva.2009.04.008
The MixtureSameFamily distribution implements a (batch of) mixture
distribution where all components are from different parameterizations of
the same distribution type. It is parameterized by a Categorical
“selecting distribution” (over k components) and a component
distribution, i.e., a Distribution with a rightmost batch shape
(equal to [k]) which indexes each (batch of) component.
Examples:
>>> # Construct Gaussian Mixture Model in 1D consisting of 5 equally>>> # weighted normal distributions>>> mix=D.Categorical(torch.ones(5,))>>> comp=D.Normal(torch.randn(5,),torch.rand(5,))
Parameters:
mixture_distribution (Categorical) – torch.distributions.Categorical-like
instance. Manages the probability of selecting components.
The number of categories must match the rightmost batch
dimension of the component_distribution. Must have either
scalar batch_shape or batch_shape matching
component_distribution.batch_shape[:-1]
Creates a Multinomial distribution parameterized by total_count and
either probs or logits (but not both). The innermost dimension of
probs indexes over categories. All other dimensions index over batches.
Note that total_count need not be specified if only log_prob() is
called (see example below)
sample() requires a single shared total_count for all
parameters and samples.
log_prob() allows different total_count for each parameter and
sample.
Example:
>>> m=Multinomial(100,torch.tensor([1.,1.,1.,1.]))>>> x=m.sample()# equal probability of 0, 1, 2, 3tensor([ 21., 24., 30., 25.])>>> Multinomial(probs=torch
Creates a multivariate normal (also called Gaussian) distribution
parameterized by a mean vector and a covariance matrix.
The multivariate normal distribution can be parameterized either
in terms of a positive definite covariance matrix Σ
or a positive definite precision matrix Σ−1
or a lower-triangular matrix L with positive-valued
diagonal entries, such that
Σ=LL⊤. This triangular matrix
can be obtained via e.g. Cholesky decomposition of the covariance.
Example
>>> m=MultivariateNormal(torch.zeros(2),torch.eye(2))>>> m.sample()# normally distributed with mean=`[0,0]` and covariance_matrix=`I`tensor([-0.2102, -0.5429])
Creates a Negative Binomial distribution, i.e. distribution
of the number of successful independent and identical Bernoulli trials
before total_count failures are achieved. The probability
of success of each Bernoulli trial is probs.
Parameters:
total_count (float or Tensor) – non-negative number of negative Bernoulli
trials to stop, although the distribution is still valid for real
valued count
probs (Tensor) – Event probabilities of success in the half open interval [0, 1)
logits (Tensor) – Event log-odds for probabilities of success
Creates a RelaxedBernoulli distribution, parametrized by
temperature, and either probs or logits
(but not both). This is a relaxed version of the Bernoulli distribution,
so the values are in (0, 1), and has reparametrizable samples.
Creates a RelaxedOneHotCategorical distribution parametrized by
temperature, and either probs or logits.
This is a relaxed version of the OneHotCategorical distribution, so
its samples are on simplex, and are reparametrizable.
Note that the .event_shape of a TransformedDistribution is the
maximum shape of its base distribution and its transforms, since transforms
can introduce correlations among events.
# Building a Logistic Distribution# X ~ Uniform(0, 1)# f = a + b * logit(X)# Y ~ f(X) ~ Logistic(a, b)base_distribution=Uniform(0,1)transforms=[SigmoidTransform().inv,AffineTransform(loc=a,scale=b)]logistic=TransformedDistribution
Computes the inverse cumulative distribution function using
transform(s) and computing the score of the base distribution.
log_prob(value)
Scores the sample by inverting the transform(s) and computing the score
using the score of the base distribution and the log abs det jacobian.
rsample(sample_shape=())
Generates a sample_shape shaped reparameterized sample or sample_shape
shaped batch of reparameterized samples if the distribution parameters
are batched. Samples first from base distribution and applies
transform() for every transform in the list.
Generates a sample_shape shaped sample or sample_shape shaped batch of
samples if the distribution parameters are batched. Samples first from
base distribution and applies transform() for every transform in the
list.
This implementation uses polar coordinates. The loc and value args
can be any real number (to facilitate unconstrained optimization), but are
interpreted as angles modulo 2 pi.
Example::
>>> m=VonMises(torch.tensor([1.0]),torch.tensor([1.0]))>>> m.sample()# von Mises distributed with loc=1 and concentration=1tensor([1.9777])
The sampling algorithm for the von Mises distribution is based on the
following paper: D.J. Best and N.I. Fisher, “Efficient simulation of the
von Mises distribution.” Applied Statistics (1979): 152-157.
Sampling is always done in double precision internally to avoid a hang
in _rejection_sample() for small values of the concentration, which
starts to happen for single precision around 1e-4 (see issue #88443).
Samples from a two-parameter Weibull distribution.
Example
>>> m=Weibull(torch.tensor([1.0]),torch.tensor([1.0]))>>> m.sample()# sample from a Weibull distribution with scale=1, concentration=1tensor([ 0.4784])
Parameters:
scale (float or Tensor) – Scale parameter of distribution (lambda).
concentration (float or Tensor) – Concentration parameter of distribution (k/shape).
validate_args (bool, optional) – Whether to validate arguments. Default: None.
Creates a Wishart distribution parameterized by a symmetric positive definite matrix Σ,
or its Cholesky decomposition Σ=LL⊤
Example
>>> m=Wishart(torch.Tensor([2]),covariance_matrix=torch.eye(2))>>> m.sample()# Wishart distributed with mean=`df * I` and>>> # variance(x_ij)=`df` for i != j and variance(x_ij)=`2 * df` for i == j
Parameters:
df (float or Tensor) – real-valued parameter larger than the (dimension of Square matrix) - 1
scale_tril (Tensor) – lower-triangular factor of covariance, with positive-valued diagonal
References
[1] Wang, Z., Wu, Y. and Chu, H., 2018. On equivalence of the LKJ distribution and the restricted Wishart distribution.
[2] Sawyer, S., 2007. Wishart Distributions and Inverse-Wishart Sampling.
[3] Anderson, T. W., 2003. An Introduction to Multivariate Statistical Analysis (3rd ed.).
[4] Odell, P. L. & Feiveson, A. H., 1966. A Numerical Procedure to Generate a Sample Covariance Matrix. JASA, 61(313):199-203.
[5] Ku, Y.-C. & Bloomfield, P., 2010. Generating Random Wishart Matrices with Fractional Degrees of Freedom in OX.
Transform functor that applies a sequence of transforms tseq
component-wise to each submatrix at dim, of length lengths[dim],
in a way compatible with torch.cat().
Transforms an unconstrained real vector x with length D∗(D−1)/2 into the
Cholesky factor of a D-dimension correlation matrix. This Cholesky factor is a lower
triangular matrix with positive diagonals and unit Euclidean norm for each row.
The transform is processed as follows:
Wrapper around another transform to treat
reinterpreted_batch_ndims-many extra of the right most dimensions as
dependent. This has no effect on the forward or backward transforms, but
does sum out reinterpreted_batch_ndims-many of the rightmost dimensions
in log_abs_det_jacobian().
Transform from unconstrained space to the simplex via y=exp(x) then
normalizing.
This is not bijective and cannot be used for HMC. However this acts mostly
coordinate-wise (except for the final normalization), and thus is
appropriate for coordinate-wise optimization algorithms.
Transform from unconstrained space to the simplex of one additional
dimension via a stick-breaking process.
This transform arises as an iterated sigmoid transform in a stick-breaking
construction of the Dirichlet distribution: the first logit is
transformed via sigmoid to the first probability and the probability of
everything else, and then the process recurses.
This is bijective and appropriate for use in HMC; however it mixes
coordinates together and is less appropriate for optimization.
Abstract class for invertible transformations with computable log
det jacobians. They are primarily used in
torch.distributions.TransformedDistribution.
Caching is useful for transforms whose inverses are either expensive or
numerically unstable. Note that care must be taken with memoized values
since the autograd graph may be reversed. For example while the following
works with or without caching:
A constraint object represents a region over which a variable is valid,
e.g. within which a variable can be optimized.
Variables:
is_discrete (bool) – Whether constrained space is discrete.
Defaults to False.
event_dim (int) – Number of rightmost dimensions that together define
an event. The check() method will remove this many dimensions
when computing validity.
check(value)
Returns a byte tensor of sample_shape+batch_shape indicating
whether each event in value satisfies this constraint.
Constraint for the MixtureSameFamily
distribution that adds back the rightmost batch dimension before
performing the validity check with the component distribution
constraint.
Parameters:
base_constraint – The Constraint object of
the component distribution of
the MixtureSameFamily distribution.
Placeholder for variables whose support depends on other variables.
ConstraintRegistry
PyTorch provides two global ConstraintRegistry objects that link
Constraint objects to
Transform objects. These objects both
input constraints and return transforms, but they have different guarantees on
bijectivity.
biject_to(constraint) looks up a bijective
Transform from constraints.real
to the given constraint. The returned transform is guaranteed to have
.bijective=True and should implement .log_abs_det_jacobian().
transform_to(constraint) looks up a not-necessarily bijective
Transform from constraints.real
to the given constraint. The returned transform is not guaranteed to
implement .log_abs_det_jacobian().
The transform_to() registry is useful for performing unconstrained
optimization on constrained parameters of probability distributions, which are
indicated by each distribution’s .arg_constraints dict. These transforms often
overparameterize a space in order to avoid rotation; they are thus more
suitable for coordinate-wise optimization algorithms like Adam:
The biject_to() registry is useful for Hamiltonian Monte Carlo, where
samples from a probability distribution with constrained .support are
propagated in an unconstrained space, and algorithms are typically rotation
invariant.:
The biject_to and transform_to objects can be extended by user-defined
constraints and transforms using their .register() method either as a
function on singleton constraints:
LowRankMultivariateNormal and LowRankMultivariateNormal
LowRankMultivariateNormal and MultivariateNormal
MultivariateNormal and LowRankMultivariateNormal
MultivariateNormal and MultivariateNormal
Normal and Beta
Normal and ContinuousBernoulli
Normal and Exponential
Normal and Gamma
Normal and Gumbel
Normal and Laplace
Normal and Normal
Normal and Pareto
Normal and Uniform
OneHotCategorical and OneHotCategorical
Pareto and Beta
Pareto and ContinuousBernoulli
Pareto and Exponential
Pareto and Gamma
Pareto and Normal
Pareto and Pareto
Pareto and Uniform
Poisson and Bernoulli
Poisson and Binomial
Poisson and Poisson
TransformedDistribution and TransformedDistribution
Uniform and Beta
Uniform and ContinuousBernoulli
Uniform and Exponential
Uniform and Gamma
Uniform and Gumbel
Uniform and Normal
Uniform and Pareto
Uniform and Uniform
Lookup returns the most specific (type,type) match ordered by subclass. If
the match is ambiguous, a RuntimeWarning is raised. For example to
resolve the ambiguous situation:
event_dim (int) – Optional size of event_shape. This should be zero
for univariate random variables, 1 for distributions over vectors,
2 for distributions over matrices, etc.
First we convert x into a lower triangular matrix in row order.
For each row Xi of the lower triangular part, we apply a signed version of
class StickBreakingTransform to transform Xi into a
unit Euclidean length vector using the following steps:
- Scales into the interval (−1,1) domain: ri=tanh(Xi).
- Transforms into an unsigned domain: zi=ri2.
- Applies si=StickBreakingTransform(zi).
- Transforms back into signed domain: yi=sign(ri)∗si.
cache_size (int) – Size of cache. If zero, no caching is done. If one,
the latest single value is cached. Only 0 and 1 are supported. (Default 0.)
x=logit(y)
AffineTransform
(
0.0
,
2.0
),
SigmoidTransform
(),
AffineTransform
(
-
1.0
,
2.0
),
]
)
However this might not be numerically stable, thus it is recommended to use TanhTransform
instead.
Note that one should use cache_size=1 when it comes to NaN/Inf values.
.
stack
([
torch
.
range
(
1
,
10
),
torch
.
range
(
1
,
10
)],
dim
=
1
)
t
=
StackTransform
([
ExpTransform
(),
identity_transform
],
dim
=
1
)
y
=
t
(
x
)
(
x
,
y
)
.
backward
()
# x will receive gradients.
However the following will error when caching due to dependency reversal:
y=t(x)z=t.inv(y)grad(z.sum(),[y])# error because z is x
Derived classes should implement one or both of _call() or
_inverse(). Derived classes that set bijective=True should also
implement log_abs_det_jacobian().
Parameters:
cache_size (int) – Size of cache. If zero, no caching is done. If one,
the latest single value is cached. Only 0 and 1 are supported.
Variables:
domain (Constraint) – The constraint representing valid inputs to this transform.
codomain (Constraint) – The constraint representing valid outputs to this transform
which are inputs to the inverse transform.
bijective (bool) – Whether this transform is bijective. A transform
t is bijective iff t.inv(t(x))==x and
t(t.inv(y))==y for every x in the domain and y in
the codomain. Transforms that are not bijective should at least
maintain the weaker pseudoinverse properties
t(t.inv(t(x))==t(x) and t.inv(t(t.inv(y)))==t.inv(y).
sign (int or Tensor) – For bijective univariate transforms, this
should be +1 or -1 depending on whether transform is monotone
increasing or decreasing.