laplace.likelihoods
#
Likelihood objects that bundle everything a Laplace approximation needs to know about the observation model: the loss, the output-space Hessian, the normalizer, and how to sample targets.
HeteroscedasticGaussianNLLLoss
#
Bases: Module
nn.GaussianNLLLoss of the pair (mean, var) or of the joined outputs.
The pair is what the network returns, e.g. while marglik_training trains it.
The joined outputs (batch, ..., 2 * K) are what Laplace sees. They carry the
variance at the MAP, which Laplace detaches, so their loss has no gradient
w.r.t. the variance.
Parameters:
-
eps(float) –lower bound of the variance.
-
full(bool) –whether the loss includes the constant.
-
reduction(str, default:'sum') –reduction of the loss, as in
nn.GaussianNLLLoss.
Source code in laplace/utils/heteroscedastic_utils.py
forward
#
forward(
input: Tensor | tuple[Tensor, Tensor], target: Tensor
) -> Tensor
Compute the loss of the outputs input w.r.t. the targets target.
This is nn.functional.gaussian_nll_loss without its check for negative
variances, which is data-dependent control flow that torch.func.vmap can't
trace, e.g. for the per-sample gradients of the empirical Fisher. Negative
variances are clamped at eps like small ones.
Source code in laplace/utils/heteroscedastic_utils.py
_LikelihoodMeta
#
Likelihood
#
Base class for likelihoods.
A likelihood compares the model output f with the targets y. All leading
dims of f but the last are batch dims, so f has shape (batch, ..., outputs).
To add a new likelihood, subclass this, set name, and implement
distribution(f), which returns the model's predictive distribution over the
targets as a torch.distributions.Distribution. Its batch_shape + event_shape
is the shape of the targets. All other members have defaults built on it, and
you can override any of them:
loss_fn: the negative log-probability of the targets, summed or averaged.loss_factor: \(1\), since the loss is already the negative log likelihood.log_normalizer: zero.loss: callscheck_targets, thenloss_fn.check_targets: raises aValueErrorunless the targets have the distribution's shape.n_observations: the number of entries in the batch dims of the targets, i.e. their leading dims that match the batch dims off.inverse_link: the mean of the distribution, or the class probabilities of aCategorical.sample: a draw from the distribution.output_gradient: the gradient of the negative log likelihood, by autograd.output_hessian: the Fisher of the distribution w.r.t.f, see below.is_gaussian:False.fit_likelihoodandpredictive_likelihood:self.
The default output_hessian returns the Fisher
in place of the Hessian of the negative log likelihood. The two agree for
exponential families in their natural parameters, such as the Gaussian mean and
the categorical logits. Elsewhere the Hessian can be indefinite, and the GGN
needs the positive semidefinite \(F\). The Fisher is exact when the
distribution has a finite support to enumerate, such as categorical, Bernoulli,
or binomial. Otherwise it is a Monte Carlo estimate from fisher_samples draws,
taken fisher_chunk_size at a time, and a UserWarning says so. If you know the
Fisher in closed form, override output_hessian to make it exact and cheap.
output_hessian also gets the targets y when the caller has them, for
likelihoods whose curvature depends on them, e.g. through class weights or
ignored positions. It is None when the caller has no targets.
The built-in likelihoods override all of these with closed forms and the exact
torch losses. Their distribution is the model's predictive, so it does not
change with options that only reweight or smooth the loss.
Two likelihoods are equal if they have the same name and the same
hyperparameters(), the options that differ from their defaults. A string equals
a likelihood with that name. Internally, the library dispatches on name, so a
subclass of CategoricalLikelihood that keeps its name and carries options still
takes the classification code paths, even though it does not equal
Likelihood.CLASSIFICATION.
Weight-space Laplace fits a custom likelihood with the diag or full
structure and a GGN or EF backend, which use its output_hessian and loss_fn.
The kron structure and the Hessian backends raise a ValueError for it. The
GLM predictive of a likelihood that is neither Gaussian nor categorical is the
Monte Carlo average of inverse_link over the GLM predictive of the outputs.
FunctionalLaplace, ELLA, and VaLLA only accept the names of the regression,
classification, and reward-modeling likelihoods, but a subclass that keeps one of
them may override members such as output_hessian.
fisher_samples
#
fisher_samples: int = 100
Number of samples for the Monte Carlo Fisher in the default output_hessian.
With 1000 data and 10 outputs, 100 samples give about 1.5% error in the summed
GGN and 25% per datum.
fisher_chunk_size
#
fisher_chunk_size: int = 10
Number of Monte Carlo samples drawn at once, to bound memory.
loss_factor
#
loss_factor: float
Factor that turns the loss into the negative log likelihood, up to a constant. It is \(1\) by default.
is_gaussian
#
is_gaussian: bool
Whether the likelihood is Gaussian, i.e. has a closed-form predictive and
allows sigma_noise.
predictive_likelihood
#
predictive_likelihood: Likelihood
Likelihood of the predictive distribution.
__init_subclass__
#
__init_subclass__(**kwargs: object) -> None
Require a name on every concrete subclass.
Raises:
-
TypeError–if a subclass with no abstract members left has no
name.
Source code in laplace/likelihoods.py
hyperparameters
#
Options of the likelihood that differ from their defaults, by name.
They are part of the likelihood's identity: two likelihoods are equal only if their names and hyperparameters match, and checkpoints store them. Override this in a subclass that takes options. Values are plain Python objects or tensors.
Returns:
-
hyperparameters(dict) –empty by default.
Source code in laplace/likelihoods.py
distribution
#
Predictive distribution of the targets given the outputs f.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs)
Returns:
-
dist(Distribution) –a distribution whose
batch_shape + event_shapeis the shape of the targets.
Source code in laplace/likelihoods.py
loss_fn
#
loss_fn(reduction: str = 'sum') -> Module
Build the loss module. By default, it computes the negative
log-probability of the targets under distribution.
Parameters:
-
reduction(str, default:'sum') –reduction of the loss, as in
torch.nn.
Returns:
-
loss_fn(Module) –a new module on every call.
Source code in laplace/likelihoods.py
check_targets
#
Raise a ValueError if the targets y do not fit the outputs f. By
default, y must have the shape batch_shape + event_shape of
distribution(f).
Source code in laplace/likelihoods.py
output_hessian
#
Curvature of the negative log likelihood w.r.t. the outputs f.
By default, this is the Fisher \(F(f)\) of distribution(f), exact for a
distribution with enumerable support and a Monte Carlo estimate otherwise.
For the built-in likelihoods, it equals the Hessian.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
y(Tensor, default:None) –targets, for likelihoods whose curvature depends on them. The default ignores them.
Returns:
-
H(Tensor) –(batch, ..., outputs, outputs), with the dtype off.
Source code in laplace/likelihoods.py
_enumerated_fisher
#
Exact Fisher of a distribution with enumerable support.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs) -
dist(Distribution) –distribution(f)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
_monte_carlo_fisher
#
Monte Carlo estimate of the Fisher from fisher_samples draws.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
inverse_link
#
Map the outputs f to the mean of the targets: by default the mean of
distribution(f), or its class probabilities for a Categorical.
Source code in laplace/likelihoods.py
sample
#
Sample targets from the likelihood given the outputs f.
By default, this draws from distribution(f). Since distributions take no
generator, a given generator seeds the global one inside
torch.random.fork_rng, which leaves the global state as it was.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
generator(Generator, default:None) –source of randomness. The global generator is used if
None.
Returns:
-
y(Tensor) –samples with the shape of the targets.
Source code in laplace/likelihoods.py
output_gradient
#
Gradient of the negative log likelihood w.r.t. the outputs f. By
default, it comes from autograd through distribution(f).
Source code in laplace/likelihoods.py
loss
#
Summed loss of the outputs f w.r.t. the targets y, after checking
the targets with check_targets.
n_observations
#
n_observations(f: Tensor, y: Tensor) -> int
Number of observations in a batch.
By default, every leading dim of the outputs but the last is a batch dim,
and the targets share them. So this counts the leading dims of y, e.g.
B * L for outputs (B, L, K) and targets (B, L) or (B, L, K). The
batch size comes from the targets, so f may come from fewer data, as long
as it has the same number of dims.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs), possibly of a single datum. -
y(Tensor) –targets of the batch.
Returns:
-
n_obs(int) –
Source code in laplace/likelihoods.py
log_normalizer
#
Constant that turns the negative loss into the log likelihood. It is zero by default.
Parameters:
-
n_obs(int) –number of observations
-
n_outputs(int) –number of outputs
-
sigma_noise(Tensor) –observation noise, ignored if the likelihood has none.
Returns:
-
c(Tensor) –a 0-dim zero with the dtype and device of
sigma_noise.
Source code in laplace/likelihoods.py
GaussianLikelihood
#
Bases: Likelihood
Gaussian likelihood, i.e. regression.
With observation noise \(\sigma\), a target \(y \in \mathbb{R}^K\) given the outputs \(f\) has the likelihood
The loss is the summed MSE, so for \(N\) observations the negative log likelihood is
which gives the loss factor \(\tfrac{1}{2}\) and the normalizer \(N K \log(\sigma \sqrt{2\pi})\). The targets have as many dims as the outputs, and every entry of the targets but the last dim is an observation.
By default, the noise enters through sigma_noise of the Laplace approximation, so
the other quantities assume \(\sigma = 1\): the output Hessian is \(I\), the
inverse link is the identity, samples are \(y \sim \mathcal{N}(f, I)\), and the
output gradient is \(f - y\). A float sigma_noise gives a normalizer with the
default dtype.
For a known noise std per output, \(\sigma \in \mathbb{R}^K\), pass a 1-D tensor
as sigma_noise. The likelihood is then
\(\mathcal{N}(y \mid f, \operatorname{diag}(\sigma^2))\) with the loss
the output Hessian \(\operatorname{diag}(\sigma^{-2})\), and the normalizer
\(N \sum_k \log(\sigma_k \sqrt{2\pi})\). The samples and the output gradient
use it too. The vector is fixed when a Laplace approximation is fit, and the
sigma_noise of the Laplace approximation must then stay 1. It is a hyperparameter
of the likelihood, so checkpoints store it.
Parameters:
-
sigma_noise(Tensor, default:None) –known noise std per output
(outputs,). All entries must be positive and finite.Noneleaves the noise to the Laplace approximation.
Raises:
-
ValueError–if
sigma_noiseis not a floating 1-D tensor with positive, finite entries.
Source code in laplace/likelihoods.py
fisher_samples
#
fisher_samples: int = 100
Number of samples for the Monte Carlo Fisher in the default output_hessian.
With 1000 data and 10 outputs, 100 samples give about 1.5% error in the summed
GGN and 25% per datum.
fisher_chunk_size
#
fisher_chunk_size: int = 10
Number of Monte Carlo samples drawn at once, to bound memory.
predictive_likelihood
#
predictive_likelihood: Likelihood
Likelihood of the predictive distribution.
sigma_noise
#
Noise std per output (outputs,), or None for the scalar noise of the Laplace
approximation.
loss_factor
#
loss_factor: float
Factor that turns the loss into the negative log likelihood, up to a constant. It is \(1\) by default.
is_gaussian
#
is_gaussian: bool
Whether the likelihood is Gaussian, i.e. has a closed-form predictive and
allows sigma_noise.
__init_subclass__
#
__init_subclass__(**kwargs: object) -> None
Require a name on every concrete subclass.
Raises:
-
TypeError–if a subclass with no abstract members left has no
name.
Source code in laplace/likelihoods.py
_enumerated_fisher
#
Exact Fisher of a distribution with enumerable support.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs) -
dist(Distribution) –distribution(f)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
_monte_carlo_fisher
#
Monte Carlo estimate of the Fisher from fisher_samples draws.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
loss
#
Summed loss of the outputs f w.r.t. the targets y, after checking
the targets with check_targets.
hyperparameters
#
Options of the likelihood that differ from their defaults, by name.
They are part of the likelihood's identity: two likelihoods are equal only if their names and hyperparameters match, and checkpoints store them. Override this in a subclass that takes options. Values are plain Python objects or tensors.
Returns:
-
hyperparameters(dict) –empty by default.
distribution
#
Predictive distribution of the targets given the outputs f.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs)
Returns:
-
dist(Distribution) –a distribution whose
batch_shape + event_shapeis the shape of the targets.
loss_fn
#
loss_fn(reduction: str = 'sum') -> Module
Build the loss module. By default, it computes the negative
log-probability of the targets under distribution.
Parameters:
-
reduction(str, default:'sum') –reduction of the loss, as in
torch.nn.
Returns:
-
loss_fn(Module) –a new module on every call.
check_targets
#
Raise a ValueError if the targets y do not fit the outputs f. By
default, y must have the shape batch_shape + event_shape of
distribution(f).
Source code in laplace/likelihoods.py
n_observations
#
n_observations(f: Tensor, y: Tensor) -> int
Number of observations in a batch.
By default, every leading dim of the outputs but the last is a batch dim,
and the targets share them. So this counts the leading dims of y, e.g.
B * L for outputs (B, L, K) and targets (B, L) or (B, L, K). The
batch size comes from the targets, so f may come from fewer data, as long
as it has the same number of dims.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs), possibly of a single datum. -
y(Tensor) –targets of the batch.
Returns:
-
n_obs(int) –
log_normalizer
#
Constant that turns the negative loss into the log likelihood. It is zero by default.
Parameters:
-
n_obs(int) –number of observations
-
n_outputs(int) –number of outputs
-
sigma_noise(Tensor) –observation noise, ignored if the likelihood has none.
Returns:
-
c(Tensor) –a 0-dim zero with the dtype and device of
sigma_noise.
Source code in laplace/likelihoods.py
output_hessian
#
Curvature of the negative log likelihood w.r.t. the outputs f.
By default, this is the Fisher \(F(f)\) of distribution(f), exact for a
distribution with enumerable support and a Monte Carlo estimate otherwise.
For the built-in likelihoods, it equals the Hessian.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
y(Tensor, default:None) –targets, for likelihoods whose curvature depends on them. The default ignores them.
Returns:
-
H(Tensor) –(batch, ..., outputs, outputs), with the dtype off.
Source code in laplace/likelihoods.py
inverse_link
#
sample
#
Sample targets from the likelihood given the outputs f.
By default, this draws from distribution(f). Since distributions take no
generator, a given generator seeds the global one inside
torch.random.fork_rng, which leaves the global state as it was.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
generator(Generator, default:None) –source of randomness. The global generator is used if
None.
Returns:
-
y(Tensor) –samples with the shape of the targets.
output_gradient
#
HeteroscedasticGaussianLikelihood
#
Bases: Likelihood
Heteroscedastic Gaussian likelihood, i.e. regression where the network also
predicts the noise, as trained with nn.GaussianNLLLoss.
The network returns a mean \(\mu(x) \in \mathbb{R}^K\) and a variance
\(\sigma^2(x)\), as the pair (mean, var) that nn.GaussianNLLLoss takes. A
target then has the likelihood
The variance has the shape of the mean, or it is shared by the outputs of a
datum, see join_mean_variance. The
targets have the shape of the mean, and every entry of the targets but the last
dim is an observation. The options eps and full are those of
nn.GaussianNLLLoss: the variance is clamped at eps from below, and full
adds the constant \(\tfrac{1}{2} \log 2\pi\) of each output to the loss.
The loss is the summed nn.GaussianNLLLoss,
which is the negative log likelihood up to the normalizer
\(N K \log \sqrt{2\pi}\), or zero with full=True. So the loss factor is
\(1\).
The Laplace approximation is over the mean only, as in Immer et al. (2023): the variance is held at its value under the MAP parameters. The GGN is then
and parameters that only the variance depends on get no curvature from the data,
only from the prior. The predictive la(x) returns f_mean, f_alea, f_epis: the
mean, the network's variance, which is the aleatoric uncertainty, and the
covariance of the mean under the posterior, which is the epistemic uncertainty.
The predictive variance of the targets is f_alea plus the diagonal of
f_epis.
Inside the library, the outputs are (batch, ..., 2 * K), the mean followed by
the variance, and every method of this class takes them in that form.
Laplace joins the pair of the network while it runs the model. The output
Hessian and the output gradient are zero for the variance, and for the mean they
are \(\operatorname{diag}(\sigma^{-2})\) and \((\mu - y) / \sigma^2\).
inverse_link returns the mean, and the predictive likelihood is a
GaussianLikelihood over it. loss_fn also takes the pair, so
marglik_training can train the network with it.
Weight-space Laplace supports the diag, full, and kron structures with the
Curvlinops backends, and diag and full with any GGN or EF backend. Last-layer
Laplace and the function-space methods don't support this likelihood.
Parameters:
-
eps(float, default:1e-6) –lower bound of the variance, as in
nn.GaussianNLLLoss. -
full(bool, default:False) –whether the loss includes the constant, as in
nn.GaussianNLLLoss.
Raises:
-
ValueError–if
epsis not positive.
References
Immer, A., Palumbo, E., Marx, A., & Vogt, J. E. Effective Bayesian Heteroscedastic Regression with Deep Neural Networks. NeurIPS 2023.
Source code in laplace/likelihoods.py
fisher_samples
#
fisher_samples: int = 100
Number of samples for the Monte Carlo Fisher in the default output_hessian.
With 1000 data and 10 outputs, 100 samples give about 1.5% error in the summed
GGN and 25% per datum.
fisher_chunk_size
#
fisher_chunk_size: int = 10
Number of Monte Carlo samples drawn at once, to bound memory.
is_gaussian
#
is_gaussian: bool
Whether the likelihood is Gaussian, i.e. has a closed-form predictive and
allows sigma_noise.
name
#
name: str = 'heteroscedastic_gaussian'
Identifier of the likelihood, e.g. what is stored in state_dict().
loss_factor
#
loss_factor: float
Factor that turns the loss into the negative log likelihood, up to a constant. It is \(1\) by default.
predictive_likelihood
#
predictive_likelihood: Likelihood
Likelihood of the predictive distribution.
__init_subclass__
#
__init_subclass__(**kwargs: object) -> None
Require a name on every concrete subclass.
Raises:
-
TypeError–if a subclass with no abstract members left has no
name.
Source code in laplace/likelihoods.py
_enumerated_fisher
#
Exact Fisher of a distribution with enumerable support.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs) -
dist(Distribution) –distribution(f)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
_monte_carlo_fisher
#
Monte Carlo estimate of the Fisher from fisher_samples draws.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
loss
#
Summed loss of the outputs f w.r.t. the targets y, after checking
the targets with check_targets.
n_observations
#
n_observations(f: Tensor, y: Tensor) -> int
Number of observations in a batch.
By default, every leading dim of the outputs but the last is a batch dim,
and the targets share them. So this counts the leading dims of y, e.g.
B * L for outputs (B, L, K) and targets (B, L) or (B, L, K). The
batch size comes from the targets, so f may come from fewer data, as long
as it has the same number of dims.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs), possibly of a single datum. -
y(Tensor) –targets of the batch.
Returns:
-
n_obs(int) –
Source code in laplace/likelihoods.py
hyperparameters
#
Options of the likelihood that differ from their defaults, by name.
They are part of the likelihood's identity: two likelihoods are equal only if their names and hyperparameters match, and checkpoints store them. Override this in a subclass that takes options. Values are plain Python objects or tensors.
Returns:
-
hyperparameters(dict) –empty by default.
split
#
split(f: Tensor) -> tuple[Tensor, Tensor]
Split the joined outputs into the mean and the variance.
Parameters:
-
f(Tensor) –(batch, ..., 2 * K)
Returns:
-
mean(Tensor) –(batch, ..., K) -
var(Tensor) –(batch, ..., K), as the network returns it, without the clamp ateps.
Source code in laplace/likelihoods.py
distribution
#
Predictive distribution of the targets given the outputs f.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs)
Returns:
-
dist(Distribution) –a distribution whose
batch_shape + event_shapeis the shape of the targets.
loss_fn
#
loss_fn(reduction: str = 'sum') -> Module
Build the loss module. By default, it computes the negative
log-probability of the targets under distribution.
Parameters:
-
reduction(str, default:'sum') –reduction of the loss, as in
torch.nn.
Returns:
-
loss_fn(Module) –a new module on every call.
check_targets
#
Raise a ValueError if the targets y do not fit the outputs f. By
default, y must have the shape batch_shape + event_shape of
distribution(f).
Source code in laplace/likelihoods.py
log_normalizer
#
Constant that turns the negative loss into the log likelihood.
Parameters:
-
n_obs(int) –number of observations
-
n_outputs(int) –number of joined outputs \(2 K\), the mean and the variance.
-
sigma_noise(Tensor) –ignored, since the network predicts the noise. It sets the dtype and device of the result.
Returns:
-
c(Tensor) –\(N K \log \sqrt{2\pi}\), or zero with
full=True.
Source code in laplace/likelihoods.py
output_hessian
#
Curvature of the negative log likelihood w.r.t. the outputs f.
By default, this is the Fisher \(F(f)\) of distribution(f), exact for a
distribution with enumerable support and a Monte Carlo estimate otherwise.
For the built-in likelihoods, it equals the Hessian.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
y(Tensor, default:None) –targets, for likelihoods whose curvature depends on them. The default ignores them.
Returns:
-
H(Tensor) –(batch, ..., outputs, outputs), with the dtype off.
inverse_link
#
sample
#
Sample targets from the likelihood given the outputs f.
By default, this draws from distribution(f). Since distributions take no
generator, a given generator seeds the global one inside
torch.random.fork_rng, which leaves the global state as it was.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
generator(Generator, default:None) –source of randomness. The global generator is used if
None.
Returns:
-
y(Tensor) –samples with the shape of the targets.
Source code in laplace/likelihoods.py
output_gradient
#
Gradient of the negative log likelihood w.r.t. the outputs f. By
default, it comes from autograd through distribution(f).
CategoricalLikelihood
#
CategoricalLikelihood(
weight: Tensor | None = None,
ignore_index: int = -100,
label_smoothing: float = 0.0,
)
Bases: Likelihood
Categorical likelihood with a softmax link, i.e. classification.
With logits \(f \in \mathbb{R}^C\) and class probabilities \(p = \operatorname{softmax}(f)\), a class \(y\) has the likelihood \(p(y \mid f) = p_y\). The loss is the cross-entropy \(-\log p_y\), or \(-\sum_c y_c \log p_c\) for class probabilities \(y\), which is already the negative log likelihood. So the loss factor is \(1\) and the normalizer is zero.
The targets are class indices (batch, ...) or class probabilities with the
shape of the logits, e.g. one-hot or soft labels. As in nn.CrossEntropyLoss,
class probabilities must be floating point, and integer targets with the shape of
the logits raise a ValueError: call .float() on one-hot targets. For logits
with extra batch dims, e.g. (B, L, C) for sequences, loss flattens the batch
dims, since CrossEntropyLoss expects the class axis at dim 1. Every position is
then an observation; the class dim of probability targets does not count.
The options weight, ignore_index, and label_smoothing are those of
nn.CrossEntropyLoss, with the same defaults and meaning. Let \(q\) be the
one-hot index target or the probability target, smoothed as
\(q \leftarrow (1 - \varepsilon)\, q + \varepsilon / C\) with
\(\varepsilon\) the label smoothing. With class weights \(w\), the loss of a
position is
where \(m = [y \neq \text{ignore\_index}]\) for index targets and \(m = 1\) for probability targets, as in torch. Without weights, \(w = 1\). Only positions with \(m = 1\) count as observations. With the per-position scale \(s = w^\top q\), or \(s = 1\) without weights, the output gradient is
which is \(p - y\) for one-hot \(y\) and default options, and the output Hessian is
Without targets, output_hessian returns \(\operatorname{diag}(p) - p p^\top\)
without \(m\) and \(s\). The weight is cast to the dtype and device of the
logits wherever it is used. Class weights and label smoothing make this a
generalized likelihood, so log_marginal_likelihood is no longer a true model
evidence.
distribution, the inverse link (the softmax), and sample (one-hot draws
\(y \sim \operatorname{Cat}(p)\)) ignore the options, since they describe the
model's predictive, which the options leave unchanged.
Parameters:
-
weight(Tensor, default:None) –class weights of shape
(C,), as innn.CrossEntropyLoss. -
ignore_index(int, default:-100) –index target to leave out, as in
nn.CrossEntropyLoss. -
label_smoothing(float, default:0.0) –label smoothing \(\varepsilon \in [0, 1]\), as in
nn.CrossEntropyLoss.
Raises:
-
ValueError–if
weightis not 1-D orlabel_smoothingis outside \([0, 1]\).
Source code in laplace/likelihoods.py
fisher_samples
#
fisher_samples: int = 100
Number of samples for the Monte Carlo Fisher in the default output_hessian.
With 1000 data and 10 outputs, 100 samples give about 1.5% error in the summed
GGN and 25% per datum.
fisher_chunk_size
#
fisher_chunk_size: int = 10
Number of Monte Carlo samples drawn at once, to bound memory.
is_gaussian
#
is_gaussian: bool
Whether the likelihood is Gaussian, i.e. has a closed-form predictive and
allows sigma_noise.
predictive_likelihood
#
predictive_likelihood: Likelihood
Likelihood of the predictive distribution.
name
#
name: str = 'classification'
Identifier of the likelihood, e.g. what is stored in state_dict().
loss_factor
#
loss_factor: float
Factor that turns the loss into the negative log likelihood, up to a constant. It is \(1\) by default.
__init_subclass__
#
__init_subclass__(**kwargs: object) -> None
Require a name on every concrete subclass.
Raises:
-
TypeError–if a subclass with no abstract members left has no
name.
Source code in laplace/likelihoods.py
_enumerated_fisher
#
Exact Fisher of a distribution with enumerable support.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs) -
dist(Distribution) –distribution(f)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
_monte_carlo_fisher
#
Monte Carlo estimate of the Fisher from fisher_samples draws.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
log_normalizer
#
Constant that turns the negative loss into the log likelihood. It is zero by default.
Parameters:
-
n_obs(int) –number of observations
-
n_outputs(int) –number of outputs
-
sigma_noise(Tensor) –observation noise, ignored if the likelihood has none.
Returns:
-
c(Tensor) –a 0-dim zero with the dtype and device of
sigma_noise.
Source code in laplace/likelihoods.py
hyperparameters
#
Options of the likelihood that differ from their defaults, by name.
They are part of the likelihood's identity: two likelihoods are equal only if their names and hyperparameters match, and checkpoints store them. Override this in a subclass that takes options. Values are plain Python objects or tensors.
Returns:
-
hyperparameters(dict) –empty by default.
Source code in laplace/likelihoods.py
distribution
#
Predictive distribution of the targets given the outputs f.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs)
Returns:
-
dist(Distribution) –a distribution whose
batch_shape + event_shapeis the shape of the targets.
loss_fn
#
loss_fn(reduction: str = 'sum') -> Module
Build the loss module. By default, it computes the negative
log-probability of the targets under distribution.
Parameters:
-
reduction(str, default:'sum') –reduction of the loss, as in
torch.nn.
Returns:
-
loss_fn(Module) –a new module on every call.
_criterion
#
_criterion(
reduction: str, weight: Tensor | None
) -> CrossEntropyLoss
nn.CrossEntropyLoss with the options of this likelihood and weight.
Source code in laplace/likelihoods.py
_weight_like
#
The class weights with the dtype and device of the logits f.
check_targets
#
Raise a ValueError if the targets y do not fit the outputs f. By
default, y must have the shape batch_shape + event_shape of
distribution(f).
Source code in laplace/likelihoods.py
loss
#
Summed loss of the outputs f w.r.t. the targets y, after checking
the targets with check_targets.
n_observations
#
n_observations(f: Tensor, y: Tensor) -> int
Number of observations in a batch.
By default, every leading dim of the outputs but the last is a batch dim,
and the targets share them. So this counts the leading dims of y, e.g.
B * L for outputs (B, L, K) and targets (B, L) or (B, L, K). The
batch size comes from the targets, so f may come from fewer data, as long
as it has the same number of dims.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs), possibly of a single datum. -
y(Tensor) –targets of the batch.
Returns:
-
n_obs(int) –
_targets
#
_targets(
f: Tensor, y: Tensor
) -> tuple[Tensor, Tensor | None]
Smoothed target distribution \(q\) and mask \(m\) of the targets y.
Parameters:
-
f(Tensor) –logits
(batch, ..., C) -
y(Tensor) –class indices
(batch, ...)or class probabilities(batch, ..., C)
Returns:
-
q(Tensor) –(batch, ..., C), with the dtype off. -
m(Tensor or None) –(batch, ...)mask of the positions that count, orNonefor probability targets, which have no ignored positions.
Raises:
-
ValueError–if the targets do not fit the logits, see
check_targets.
Source code in laplace/likelihoods.py
output_hessian
#
Curvature of the negative log likelihood w.r.t. the outputs f.
By default, this is the Fisher \(F(f)\) of distribution(f), exact for a
distribution with enumerable support and a Monte Carlo estimate otherwise.
For the built-in likelihoods, it equals the Hessian.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
y(Tensor, default:None) –targets, for likelihoods whose curvature depends on them. The default ignores them.
Returns:
-
H(Tensor) –(batch, ..., outputs, outputs), with the dtype off.
Source code in laplace/likelihoods.py
inverse_link
#
sample
#
Sample targets from the likelihood given the outputs f.
By default, this draws from distribution(f). Since distributions take no
generator, a given generator seeds the global one inside
torch.random.fork_rng, which leaves the global state as it was.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
generator(Generator, default:None) –source of randomness. The global generator is used if
None.
Returns:
-
y(Tensor) –samples with the shape of the targets.
Source code in laplace/likelihoods.py
output_gradient
#
Gradient of the negative log likelihood w.r.t. the outputs f. By
default, it comes from autograd through distribution(f).
Source code in laplace/likelihoods.py
BernoulliLikelihood
#
Bases: Likelihood
Bernoulli likelihood with a sigmoid link, e.g. for binary or multi-label classification and per-pixel masks.
With logits \(f \in \mathbb{R}^K\) and probabilities \(p = \sigma(f)\), every
output is an independent binary target \(y_k \in \{0, 1\}\) with
\(p(y_k \mid f_k) = p_k^{y_k} (1 - p_k)^{1 - y_k}\). The loss is the binary
cross-entropy of nn.BCEWithLogitsLoss, which is already the negative log
likelihood. So the loss factor is \(1\) and the normalizer is zero.
The targets are floats with the shape of the logits, (batch, ..., outputs).
As in torch, they may be soft labels in \([0, 1]\). The outputs are on the last
dim, so an observation is one row of outputs. For logits (B, L, K), there are
\(B L\) observations.
The options weight and pos_weight are those of nn.BCEWithLogitsLoss, with
the same defaults and meaning, except that they are scalars or 1-D with one
entry per output. With \(w\) the weight, \(p_w\) the positive weight, both
\(1\) by default, and \(a = p_w\, y + 1 - y\), the loss of an output is
Its gradient is
which is \(p - y\) with the default options, and the output Hessian is the diagonal matrix
Without targets, output_hessian returns \(\operatorname{diag}(p (1 - p))\)
without \(w\) and \(a\). The options are cast to the dtype and device of the
logits wherever they are used. They make this a generalized likelihood, so
log_marginal_likelihood is no longer a true model evidence.
distribution, the inverse link (the sigmoid), and sample (draws
\(y \sim \operatorname{Bernoulli}(p)\)) ignore the options, since they describe
the model's predictive, which the options leave unchanged. The log_prob of the
distribution rejects soft labels, so the loss and the output gradient don't use
it.
Parameters:
-
weight(Tensor, default:None) –rescaling weight of the loss, a scalar or of shape
(outputs,), as innn.BCEWithLogitsLoss. A weight per example can't follow a shuffled data loader, so it is rejected. -
pos_weight(Tensor, default:None) –weight of the positive targets, a scalar or of shape
(outputs,), as innn.BCEWithLogitsLoss.
Raises:
-
ValueError–if
weightorpos_weighthas more than one dim.
Source code in laplace/likelihoods.py
fisher_samples
#
fisher_samples: int = 100
Number of samples for the Monte Carlo Fisher in the default output_hessian.
With 1000 data and 10 outputs, 100 samples give about 1.5% error in the summed
GGN and 25% per datum.
fisher_chunk_size
#
fisher_chunk_size: int = 10
Number of Monte Carlo samples drawn at once, to bound memory.
loss_factor
#
loss_factor: float
Factor that turns the loss into the negative log likelihood, up to a constant. It is \(1\) by default.
is_gaussian
#
is_gaussian: bool
Whether the likelihood is Gaussian, i.e. has a closed-form predictive and
allows sigma_noise.
predictive_likelihood
#
predictive_likelihood: Likelihood
Likelihood of the predictive distribution.
weight
#
Rescaling weight () or (outputs,), or None for equal weights.
pos_weight
#
Weight of the positive targets () or (outputs,), or None for one.
__init_subclass__
#
__init_subclass__(**kwargs: object) -> None
Require a name on every concrete subclass.
Raises:
-
TypeError–if a subclass with no abstract members left has no
name.
Source code in laplace/likelihoods.py
_enumerated_fisher
#
Exact Fisher of a distribution with enumerable support.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs) -
dist(Distribution) –distribution(f)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
_monte_carlo_fisher
#
Monte Carlo estimate of the Fisher from fisher_samples draws.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
n_observations
#
n_observations(f: Tensor, y: Tensor) -> int
Number of observations in a batch.
By default, every leading dim of the outputs but the last is a batch dim,
and the targets share them. So this counts the leading dims of y, e.g.
B * L for outputs (B, L, K) and targets (B, L) or (B, L, K). The
batch size comes from the targets, so f may come from fewer data, as long
as it has the same number of dims.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs), possibly of a single datum. -
y(Tensor) –targets of the batch.
Returns:
-
n_obs(int) –
Source code in laplace/likelihoods.py
log_normalizer
#
Constant that turns the negative loss into the log likelihood. It is zero by default.
Parameters:
-
n_obs(int) –number of observations
-
n_outputs(int) –number of outputs
-
sigma_noise(Tensor) –observation noise, ignored if the likelihood has none.
Returns:
-
c(Tensor) –a 0-dim zero with the dtype and device of
sigma_noise.
Source code in laplace/likelihoods.py
hyperparameters
#
Options of the likelihood that differ from their defaults, by name.
They are part of the likelihood's identity: two likelihoods are equal only if their names and hyperparameters match, and checkpoints store them. Override this in a subclass that takes options. Values are plain Python objects or tensors.
Returns:
-
hyperparameters(dict) –empty by default.
Source code in laplace/likelihoods.py
distribution
#
Predictive distribution of the targets given the outputs f.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs)
Returns:
-
dist(Distribution) –a distribution whose
batch_shape + event_shapeis the shape of the targets.
loss_fn
#
loss_fn(reduction: str = 'sum') -> Module
Build the loss module. By default, it computes the negative
log-probability of the targets under distribution.
Parameters:
-
reduction(str, default:'sum') –reduction of the loss, as in
torch.nn.
Returns:
-
loss_fn(Module) –a new module on every call.
_options_like
#
The weight \(w\) and the positive weight \(p_w\) with the dtype and
device of the logits f, or the float \(1\) for an option that is unset.
Source code in laplace/likelihoods.py
check_targets
#
Raise a ValueError if the targets y do not fit the outputs f. By
default, y must have the shape batch_shape + event_shape of
distribution(f).
Source code in laplace/likelihoods.py
loss
#
output_hessian
#
Curvature of the negative log likelihood w.r.t. the outputs f.
By default, this is the Fisher \(F(f)\) of distribution(f), exact for a
distribution with enumerable support and a Monte Carlo estimate otherwise.
For the built-in likelihoods, it equals the Hessian.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
y(Tensor, default:None) –targets, for likelihoods whose curvature depends on them. The default ignores them.
Returns:
-
H(Tensor) –(batch, ..., outputs, outputs), with the dtype off.
Source code in laplace/likelihoods.py
inverse_link
#
sample
#
Sample targets from the likelihood given the outputs f.
By default, this draws from distribution(f). Since distributions take no
generator, a given generator seeds the global one inside
torch.random.fork_rng, which leaves the global state as it was.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
generator(Generator, default:None) –source of randomness. The global generator is used if
None.
Returns:
-
y(Tensor) –samples with the shape of the targets.
output_gradient
#
Gradient of the negative log likelihood w.r.t. the outputs f. By
default, it comes from autograd through distribution(f).
BradleyTerryLikelihood
#
Bases: Likelihood
Bradley-Terry likelihood for reward modeling.
The model outputs a reward \(r(x)\) per item. For a pair of items \(x_1\) and \(x_2\), the probability that \(x_1\) is preferred is
the softmax of the two rewards. The curvature is therefore fitted with a
CategoricalLikelihood over the compared items, so the loss, the target check,
the output Hessian, the inverse link, samples, and the output gradient are all
categorical, and so is the count of observations: one per probability target or
per index target that isn't ignored. The predictive is a GaussianLikelihood
over the reward \(r(x)\).
Source code in laplace/likelihoods.py
fisher_samples
#
fisher_samples: int = 100
Number of samples for the Monte Carlo Fisher in the default output_hessian.
With 1000 data and 10 outputs, 100 samples give about 1.5% error in the summed
GGN and 25% per datum.
fisher_chunk_size
#
fisher_chunk_size: int = 10
Number of Monte Carlo samples drawn at once, to bound memory.
is_gaussian
#
is_gaussian: bool
Whether the likelihood is Gaussian, i.e. has a closed-form predictive and
allows sigma_noise.
name
#
name: str = 'reward_modeling'
Identifier of the likelihood, e.g. what is stored in state_dict().
loss_factor
#
loss_factor: float
Factor that turns the loss into the negative log likelihood, up to a constant. It is \(1\) by default.
predictive_likelihood
#
predictive_likelihood: Likelihood
Likelihood of the predictive distribution.
__init_subclass__
#
__init_subclass__(**kwargs: object) -> None
Require a name on every concrete subclass.
Raises:
-
TypeError–if a subclass with no abstract members left has no
name.
Source code in laplace/likelihoods.py
hyperparameters
#
Options of the likelihood that differ from their defaults, by name.
They are part of the likelihood's identity: two likelihoods are equal only if their names and hyperparameters match, and checkpoints store them. Override this in a subclass that takes options. Values are plain Python objects or tensors.
Returns:
-
hyperparameters(dict) –empty by default.
Source code in laplace/likelihoods.py
_enumerated_fisher
#
Exact Fisher of a distribution with enumerable support.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs) -
dist(Distribution) –distribution(f)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
_monte_carlo_fisher
#
Monte Carlo estimate of the Fisher from fisher_samples draws.
Parameters:
-
f(Tensor) –detached outputs
(batch, ..., outputs)
Returns:
-
F(Tensor) –(batch, ..., outputs, outputs)
Source code in laplace/likelihoods.py
log_normalizer
#
Constant that turns the negative loss into the log likelihood. It is zero by default.
Parameters:
-
n_obs(int) –number of observations
-
n_outputs(int) –number of outputs
-
sigma_noise(Tensor) –observation noise, ignored if the likelihood has none.
Returns:
-
c(Tensor) –a 0-dim zero with the dtype and device of
sigma_noise.
Source code in laplace/likelihoods.py
distribution
#
Predictive distribution of the targets given the outputs f.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs)
Returns:
-
dist(Distribution) –a distribution whose
batch_shape + event_shapeis the shape of the targets.
loss_fn
#
loss_fn(reduction: str = 'sum') -> Module
Build the loss module. By default, it computes the negative
log-probability of the targets under distribution.
Parameters:
-
reduction(str, default:'sum') –reduction of the loss, as in
torch.nn.
Returns:
-
loss_fn(Module) –a new module on every call.
check_targets
#
loss
#
n_observations
#
n_observations(f: Tensor, y: Tensor) -> int
Count the observed pairs, as the categorical likelihood of the fit does.
Parameters:
-
f(Tensor) –rewards of the pairs
(batch, ..., 2). -
y(Tensor) –class indices
(batch, ...)or class probabilities(batch, ..., 2).
Returns:
-
n_observations(int) –
Source code in laplace/likelihoods.py
output_hessian
#
Curvature of the negative log likelihood w.r.t. the outputs f.
By default, this is the Fisher \(F(f)\) of distribution(f), exact for a
distribution with enumerable support and a Monte Carlo estimate otherwise.
For the built-in likelihoods, it equals the Hessian.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
y(Tensor, default:None) –targets, for likelihoods whose curvature depends on them. The default ignores them.
Returns:
-
H(Tensor) –(batch, ..., outputs, outputs), with the dtype off.
inverse_link
#
sample
#
Sample targets from the likelihood given the outputs f.
By default, this draws from distribution(f). Since distributions take no
generator, a given generator seeds the global one inside
torch.random.fork_rng, which leaves the global state as it was.
Parameters:
-
f(Tensor) –outputs
(batch, ..., outputs) -
generator(Generator, default:None) –source of randomness. The global generator is used if
None.
Returns:
-
y(Tensor) –samples with the shape of the targets.
output_gradient
#
_NegLogProbLoss
#
_NegLogProbLoss(
likelihood: Likelihood, reduction: str = "sum"
)
Bases: Module
Negative log-probability of the targets under a likelihood's
distribution, the default loss_fn.
Parameters:
-
likelihood(Likelihood) –likelihood whose
distributionscores the targets. -
reduction(str, default:'sum') –'sum'or'mean'over all entries of the log-probability.
Source code in laplace/likelihoods.py
forward
#
Reduced negative log-probability of the targets y given the outputs
f.
Source code in laplace/likelihoods.py
_float_dtype
#
_float_dtype(x: Tensor | float) -> dtype
Dtype of x if it is a floating tensor, else the default dtype.
_zero_like
#
_zero_like(x: Tensor | float) -> Tensor
0-dim zero with the floating dtype and the device of x.
hyperparameters_equal
#
Compare two hyperparameter dicts by keys, then by values.
Parameters:
-
a(dict) –values are plain Python objects or tensors, compared with
_tensors_equalif either is a tensor. -
b(dict) –values are plain Python objects or tensors, compared with
_tensors_equalif either is a tensor.
Returns:
-
equal(bool) –
Source code in laplace/utils/utils.py
_noise_per_output
#
_noise_per_output(likelihood: Likelihood) -> Tensor | None
_is_heteroscedastic
#
_is_heteroscedastic(likelihood: Likelihood) -> bool
_flatten_categorical_targets
#
Flatten categorical targets to what nn.CrossEntropyLoss takes for the logits
f of shape (M, K), where M is the number of positions in f.
The kind of the targets follows from their number of dims. Class probabilities
have as many dims as f and keep their class dim, while class indices have one
dim less. So f must still have its batch dims, or a class dim could be taken
for a position.
Parameters:
-
f(Tensor) –logits
(batch, ..., K), not flattened. -
y(Tensor) –class indices
(batch, ...)or class probabilities(batch, ..., K).
Returns:
-
y(Tensor) –(M, K)for class probabilities, and(M,)for class indices, withMthe product of the leading dims off.
Source code in laplace/likelihoods.py
_name_of
#
The value of a string, or of a member of a (str, Enum) such as the old
Likelihood enum, whose str() is not its value.
get_likelihood
#
get_likelihood(
likelihood: Likelihood | str | Module,
) -> Likelihood
Turn a likelihood name or a torch criterion into a likelihood object.
Parameters:
-
likelihood(Likelihood or str or Module) –an instance, which is returned as is, one of
'regression','classification','reward_modeling','bernoulli', and'heteroscedastic_gaussian', or a torch criterion.nn.MSELossbecomes aGaussianLikelihood,nn.CrossEntropyLossaCategoricalLikelihoodwith the criterion'sweight,ignore_index, andlabel_smoothing,nn.BCEWithLogitsLossaBernoulliLikelihoodwith itsweightandpos_weight, andnn.GaussianNLLLossaHeteroscedasticGaussianLikelihoodwith itsepsandfull. The criterion'sreductionis ignored, since Laplace always sums the loss.
Returns:
-
likelihood(Likelihood) –
Raises:
-
ValueError–if
likelihoodis neither a likelihood instance, a known name, nor one of the four criteria above. Subclasses of the criteria are not accepted. Also if theweightorpos_weightof ann.BCEWithLogitsLosshas more than one dim.
Source code in laplace/likelihoods.py
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 | |