laplace.baselaplace
#
BaseFunctionalLaplace
#
BaseFunctionalLaplace(
model: Module,
likelihood: Likelihood | str,
sigma_noise: float | Tensor = 1.0,
prior_precision: float | Tensor = 1.0,
prior_mean: float | Tensor = 0.0,
temperature: float = 1.0,
enable_backprop: bool = False,
dict_key_x: str = "input_ids",
dict_key_y: str = "labels",
backend: type[CurvatureInterface] | None = None,
backend_kwargs: dict[str, Any] | None = None,
asdl_fisher_kwargs: dict[str, Any] | None = None,
)
Bases: BaseLaplace
Provide prediction and sampling shared by function-space estimators.
Subclasses supply latent predictive moments and refresh their own posterior
state. This class handles output links, sampling, and checkpoint settings
for FunctionalLaplace, ELLA, and VaLLA.
Source code in laplace/baselaplace.py
log_likelihood
#
Compute log likelihood on the training data after .fit() has been called.
The log likelihood is computed on-demand based on the loss and, for example,
the observation noise which makes it differentiable in the latter for
iterative updates.
Returns:
-
log_likelihood(Tensor) –
prior_precision_diag
#
Obtain the diagonal prior precision \(p_0\) constructed from either a scalar, layer-wise, or diagonal prior precision.
Returns:
-
prior_precision_diag(Tensor) –
_uses_backpack_backend
#
_uses_backpack_backend: bool
Whether the curvature backend extends modules using BackPACK.
_uses_asdl_backend
#
_uses_asdl_backend: bool
Whether the curvature backend computes Jacobians using ASDL.
optimize_prior_precision
#
optimize_prior_precision(
pred_type: PredType | str,
method: TuningMethod | str = TuningMethod.MARGLIK,
n_steps: int = 100,
lr: float = 0.1,
init_prior_prec: float | Tensor = 1.0,
prior_structure: (
PriorStructure | str
) = PriorStructure.DIAG,
val_loader: DataLoader | None = None,
loss: (
Metric | Callable[[Tensor], Tensor | float] | None
) = None,
log_prior_prec_min: float = -4,
log_prior_prec_max: float = 4,
grid_size: int = 100,
link_approx: LinkApprox | str = LinkApprox.PROBIT,
n_samples: int = 100,
verbose: bool = False,
progress_bar: bool = False,
log_prior_prec_base: float = 10.0,
) -> None
Optimize the prior precision post-hoc using the method
specified by the user.
Parameters:
-
pred_type(PredType or str in {'glm', 'nn'}) –type of posterior predictive, linearized GLM predictive or neural network sampling predictiv. The GLM predictive is consistent with the curvature approximations used here.
-
method(TuningMethod or str in {'marglik', 'gridsearch'}, default:PredType.MARGLIK) –specifies how the prior precision should be optimized.
-
n_steps(int, default:100) –the number of gradient descent steps to take.
-
lr(float, default:1e-1) –the learning rate to use for gradient descent.
-
init_prior_prec(float or tensor, default:1.0) –initial prior precision before the first optimization step.
-
prior_structure(PriorStructure or str in {'scalar', 'layerwise', 'diag'}, default:PriorStructure.SCALAR) –if init_prior_prec is scalar, the prior precision is optimized with this structure. otherwise, the structure of init_prior_prec is maintained.
-
val_loader(DataLoader, default:None) –DataLoader for the validation set; each iterate is a training batch (X, y).
-
loss(callable or Metric, default:None) –loss function to use for CV. If callable, the loss is computed offline (memory intensive). If torchmetrics.Metric, running loss is computed (efficient). The default depends on the likelihood:
RunningNLLMetric()for classification and reward modeling, runningMeanSquaredError()for regression. -
log_prior_prec_min(float, default:-4) –exponent of the lower bound of the gridsearch interval.
-
log_prior_prec_max(float, default:4) –exponent of the upper bound of the gridsearch interval.
-
grid_size(int, default:100) –number of values to consider inside the gridsearch interval.
-
link_approx(LinkApprox or str in {'mc', 'probit', 'bridge'}, default:LinkApprox.PROBIT) –how to approximate the classification link function for the
'glm'. Forpred_type='nn', only'mc'is possible. -
n_samples(int, default:100) –number of samples for
link_approx='mc'. -
verbose(bool, default:False) –if true, the optimized prior precision will be printed (can be a large tensor if the prior has a diagonal covariance).
-
progress_bar(bool, default:False) –whether to show a progress bar; updated at every batch-Hessian computation. Useful for very large model and large amount of data, esp. when
subset_of_weights='all'. -
log_prior_prec_base(float, default:10.0) –base of the logarithmic gridsearch interval. The bounds are
log_prior_prec_baseraised tolog_prior_prec_minandlog_prior_prec_max.
Source code in laplace/baselaplace.py
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | |
_glm_forward_call
#
_glm_forward_call(
x: Tensor | MutableMapping,
likelihood: Likelihood | str,
joint: bool = False,
link_approx: LinkApprox | str = LinkApprox.PROBIT,
n_samples: int = 100,
diagonal_output: bool = False,
) -> Tensor | tuple[Tensor, Tensor]
Compute the posterior predictive on input data x for "glm" pred type.
Parameters:
-
x(Tensor or MutableMapping) –(batch_size, input_shape)if tensor. If MutableMapping, must contain the said tensor. -
likelihood(Likelihood or str in {'classification', 'regression', 'reward_modeling'}) –determines the log likelihood Hessian approximation.
-
link_approx(('mc', 'probit', 'bridge', 'bridge_norm'), default:'mc') –how to approximate the classification link function for the
'glm'. Forpred_type='nn', only 'mc' is possible. -
joint(bool, default:False) –Whether to output a joint predictive distribution in regression with
pred_type='glm'. If set toTrue, the predictive distribution has the same form as GP posterior, i.e. N([f(x1), ...,f(xm)], Cov[f(x1), ..., f(xm)]). IfFalse, then only outputs the marginal predictive distribution. Only available for regression and GLM predictive. -
n_samples(int, default:100) –number of samples for
link_approx='mc'. -
diagonal_output(bool, default:False) –whether to use a diagonalized posterior predictive on the outputs. Only works for
pred_type='glm'andlink_approx='mc'.
Returns:
-
predictive(Tensor or tuple[Tensor]) –For
likelihood='classification', a torch.Tensor is returned with a distribution over classes (similar to a Softmax). Forlikelihood='regression', a tuple of torch.Tensor is returned with the mean and the predictive variance. Forlikelihood='regression'andjoint=True, a tuple of torch.Tensor is returned with the mean and the predictive covariance.
Source code in laplace/baselaplace.py
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 | |
sample
#
sample(
n_samples: int = 1, generator: Generator | None = None
) -> Tensor
Sample from the Laplace posterior approximation, i.e., \( \theta \sim \mathcal{N}(\theta_{MAP}, P^{-1})\).
Parameters:
-
n_samples(int, default:100) –number of samples
-
generator(Generator, default:None) –random number generator to control the samples
Returns:
-
samples(Tensor) –
Source code in laplace/baselaplace.py
_glm_predictive_samples
#
_glm_predictive_samples(
f_mu: Tensor,
f_var: Tensor,
n_samples: int,
diagonal_output: bool = False,
generator: Generator | None = None,
) -> Tensor
Sample from the posterior predictive on input data x using "glm" prediction
type. I.e., the inverse-link function correponding to the likelihood is applied
on top of the functional sample.
Parameters:
-
f_mu(Tensor or MutableMapping) –glm predictive mean
(batch_size, output_shape) -
f_var(Tensor or MutableMapping) –glm predictive covariances
(batch_size, output_shape, output_shape) -
n_samples(int) –number of samples
-
diagonal_output(bool, default:False) –whether to use a diagonalized glm posterior predictive on the outputs.
-
generator(Generator, default:None) –random number generator to control the samples (if sampling used)
Returns:
-
samples(Tensor) –samples
(n_samples, batch_size, output_shape)
Source code in laplace/baselaplace.py
_checkpoint_configuration
#
Record input keys and backend options required by a checkpoint.
Returns:
Source code in laplace/baselaplace.py
_validate_checkpoint_configuration
#
Reject a checkpoint created with different input or backend settings.
Parameters:
Raises:
-
ValueError–If a required setting differs from the current estimator.
Source code in laplace/baselaplace.py
_glm_predictive_distribution
#
_glm_predictive_distribution(
x: Tensor | MutableMapping, joint: bool = False
) -> tuple[Tensor, Tensor]
Provide latent moments from a concrete function-space estimator.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
joint(bool, default:False) –Whether to retain covariance between input rows.
Returns:
-
tuple[Tensor, Tensor]–Mean
[B, O]and covariance[B, O, O]in model-output units. Withjoint=True, the mean is[B*O]and covariance is[B*O, B*O]. Observation noise is excluded.
Raises:
-
NotImplementedError–If the subclass does not implement latent predictive moments.
Source code in laplace/baselaplace.py
_refresh_posterior
#
_check_fitted
#
Refresh a fitted posterior or reject predictions before fitting.
Raises:
-
RuntimeError–If
fithas not completed.
Source code in laplace/baselaplace.py
_check_nonempty_inputs
#
_check_nonempty_inputs(x: Tensor | MutableMapping) -> None
Require at least one input row for a function-space prediction.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
Raises:
-
ValueError–If the input batch is empty.
Source code in laplace/baselaplace.py
predictive_moments
#
predictive_moments(
x: Tensor | MutableMapping, *, joint: bool = False
) -> tuple[Tensor, Tensor]
Return latent predictive moments without observation noise.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
joint(bool, default:False) –Include covariance between input rows when
True.
Returns:
-
tuple[Tensor, Tensor]–Mean
[B, O]and covariance[B, O, O]by default. Withjoint=True, the mean is flattened and covariance has shape[B*O, B*O].
Raises:
-
RuntimeError–If the posterior has not been fitted.
-
ValueError–If the input batch is empty.
Source code in laplace/baselaplace.py
_classification_validation_nll
#
_classification_validation_nll(
x: Tensor | MutableMapping, targets: Tensor
) -> Tensor
Compute summed classification NLL using the probit logit scale.
Parameters:
-
x(Tensor or MutableMapping) –Validation inputs.
-
targets(Tensor) –Class targets for those inputs.
Returns:
-
Tensor–Summed negative log likelihood for the batch.
Source code in laplace/baselaplace.py
__call__
#
__call__(
x: Tensor | MutableMapping,
pred_type: PredType | str = PredType.GP,
joint: bool = False,
link_approx: LinkApprox | str = LinkApprox.PROBIT,
n_samples: int = 100,
diagonal_output: bool = False,
generator: Generator | None = None,
fitting: bool = False,
**model_kwargs: dict[str, Any]
) -> Tensor | tuple[Tensor, Tensor]
Predict from the fitted function-space posterior.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
pred_type(PredType or str, default:PredType.GP) –Prediction type. Function-space estimators support only
"gp". -
joint(bool, default:False) –Retain cross-input covariance for regression predictions.
-
link_approx(LinkApprox or str, default:LinkApprox.PROBIT) –Approximation for the classification probability link.
-
n_samples(int, default:100) –Number of draws for a Monte Carlo classification link.
-
diagonal_output(bool, default:False) –Return only output variances for regression when supported.
-
generator(Generator or None, default:None) –Random generator for Monte Carlo classification predictions.
-
fitting(bool, default:False) –Evaluate reward-model preference pairs as classification inputs.
-
**model_kwargs(Any, default:{}) –Accepted for compatibility with the base prediction interface; these arguments are not forwarded to the model.
Returns:
-
Tensor or tuple[Tensor, Tensor]–Classification probabilities
[B, C], or regression/reward latent mean and covariance. Withjoint=True, the regression mean is flattened and covariance has shape[B*O, B*O].
Raises:
-
RuntimeError–If the posterior has not been fitted.
-
ValueError–If the input batch is empty, the prediction type or link is unsupported, or the generator has an incompatible type or device.
Notes
Regression and individual reward predictions exclude observation
noise. Their marginal mean is [B, O] and covariance is
[B, O, O], or variance [B, O] with diagonal_output=True.
Source code in laplace/baselaplace.py
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 | |
_glm_functional_samples
#
_glm_functional_samples(
f_mu: Tensor,
f_var: Tensor,
n_samples: int,
diagonal_output: bool = False,
generator: Generator | None = None,
) -> Tensor
Draw per-input latent samples from supplied Gaussian moments.
Parameters:
-
f_mu(Tensor) –Latent means shaped
[B, O]. -
f_var(Tensor) –Per-input covariance shaped
[B, O, O]. -
n_samples(int) –Number of draws.
-
diagonal_output(bool, default:False) –Drop covariance between output coordinates before sampling.
-
generator(Generator or None, default:None) –Random generator for the draws.
Returns:
-
Tensor–Latent draws shaped
[n_samples, B, O].
Source code in laplace/baselaplace.py
functional_samples
#
functional_samples(
x: Tensor | MutableMapping,
pred_type: PredType | str = PredType.GLM,
n_samples: int = 100,
diagonal_output: bool = False,
generator: Generator | None = None,
joint: bool = False,
) -> Tensor
Draw latent outputs; use joint=True to retain cross-input covariance.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
pred_type(PredType or str, default:PredType.GLM) –Accepted for API compatibility. Every value draws from the function-space posterior;
"nn"does not draw model weights. -
n_samples(int, default:100) –Number of draws.
-
diagonal_output(bool, default:False) –Drop cross-output covariance before sampling.
-
generator(Generator or None, default:None) –Random generator on the model device.
-
joint(bool, default:False) –Retain covariance between input rows.
Returns:
-
Tensor–Latent draws shaped
[n_samples, B, O].
Raises:
-
RuntimeError–If the posterior has not been fitted.
-
ValueError–If the input batch is empty, the sampling type is unsupported, or
n_samplesis not positive.
Source code in laplace/baselaplace.py
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 | |
predictive_samples
#
predictive_samples(
x: Tensor | MutableMapping,
pred_type: PredType | str = PredType.GLM,
n_samples: int = 100,
diagonal_output: bool = False,
generator: Generator | None = None,
fitting: bool = False,
joint: bool = False,
) -> Tensor
Draw outputs and apply the classification link when appropriate.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
pred_type(PredType or str, default:PredType.GLM) –Accepted for function-space sampling API compatibility.
-
n_samples(int, default:100) –Number of draws.
-
diagonal_output(bool, default:False) –Drop cross-output covariance before sampling.
-
generator(Generator or None, default:None) –Random generator on the model device.
-
fitting(bool, default:False) –Interpret reward-model inputs as preference pairs.
-
joint(bool, default:False) –Retain covariance between input rows.
Returns:
-
Tensor–Predictive draws shaped
[n_samples, B, O].
Raises:
-
RuntimeError–If the posterior has not been fitted.
-
ValueError–If the input batch is empty, the sampling type is unsupported, or
n_samplesis not positive.
Notes
Classification draws are class probabilities obtained by applying softmax to latent samples. Regression and individual reward draws are latent function values without observation noise.
Source code in laplace/baselaplace.py
FunctionalLaplace
#
FunctionalLaplace(
model: Module,
likelihood: Likelihood | str,
n_subset: int,
sigma_noise: float | Tensor = 1.0,
prior_precision: float | Tensor = 1.0,
prior_mean: float | Tensor = 0.0,
temperature: float = 1.0,
enable_backprop: bool = False,
dict_key_x="input_ids",
dict_key_y="labels",
backend: type[CurvatureInterface] | None = BackPackGGN,
backend_kwargs: dict[str, Any] | None = None,
independent_outputs: bool = False,
seed: int = 0,
)
Bases: BaseFunctionalLaplace
Applying the GGN (Generalized Gauss-Newton) approximation for the Hessian in the Laplace approximation of the posterior turns the underlying probabilistic model from a BNN into a GLM (generalized linear model). This GLM (in the weight space) is equivalent to a GP (in the function space), see Approximate Inference Turns Deep Networks into Gaussian Processes (Khan et al., 2019)
This class implements the (approximate) GP inference through which we obtain the desired quantities (posterior predictive, marginal log-likelihood). See Improving predictions of Bayesian neural nets via local linearization (Immer et al., 2021) for more details.
Note that for likelihood='classification', we approximate \( L_{NN} \) with a diagonal matrix
( \( L_{NN} \) is a block-diagonal matrix, where blocks represent Hessians of per-data-point log-likelihood w.r.t.
neural network output \( f \), See Appendix A.2.1 for exact definition). We
resort to such an approximation because of the (possible) errors found in Laplace approximation for
multiclass GP classification in Chapter 3.5 of R&W 2006 GP book,
see the question
here
for more details. Alternatively, one could also resort to one-vs-one or one-vs-rest implementations
for multiclass classification, however, that is not (yet) supported here.
Parameters:
-
model(Module) – -
likelihood(Likelihood or str in {'classification', 'regression', 'reward_modeling'}) –determines the log likelihood Hessian approximation. In the case of 'reward_modeling', it fits Laplace using the classification likelihood, then does prediction as in regression likelihood. The model needs to be defined accordingly: The forward pass during training takes
x.shape == (batch_size, 2, dim)withy.shape = (batch_size,). Meanwhile, during evaluationx.shape == (batch_size, dim). Reward modeling is supported byKronLaplace,DiagLaplace,ELLA, andVaLLA. -
sigma_noise(Tensor or float, default:1) –observation noise for the regression setting; must be 1 for classification
-
prior_precision(Tensor or float, default:1) –prior precision of a Gaussian prior (= weight decay); can be scalar, per-layer, or diagonal in the most general case
-
prior_mean(Tensor or float, default:0) –prior mean of a Gaussian prior, useful for continual learning
-
temperature(float, default:1) –temperature of the likelihood; lower temperature leads to more concentrated posterior and vice versa.
-
enable_backprop(bool, default:False) –whether to enable backprop to the input
xthrough the Laplace predictive. Useful for e.g. Bayesian optimization. -
dict_key_x–The dictionary key under which the input tensor
xis stored. Only has effect when the model takes aMutableMappingas the input. Useful for Huggingface LLM models. -
dict_key_y–The dictionary key under which the target tensor
yis stored. Only has effect when the model takes aMutableMappingas the input. Useful for Huggingface LLM models. -
backend(subclasses of `laplace.curvature.CurvatureInterface`, default:BackPackGGN) –backend for access to curvature/Hessian approximations. Defaults to CurvlinopsGGN if None.
-
backend_kwargs(dict, default:None) –arguments passed to the backend on initialization, for example to set the number of MC samples for stochastic approximations.
-
n_subset(int) –number of data points for Subset-of-Data (SOD) approximate GP inference.
-
independent_outputs(bool, default:False) –GP kernel here is product of Jacobians, which results in a \( C \times C\) matrix where \(C\) is the output dimension. If
True, only a diagonal of a GP kernel is used. This is (somewhat) equivalent to assuming independent GPs across output channels. -
seed(int, default:0) –Random seed for subset of data sampler.
Source code in laplace/baselaplace.py
log_likelihood
#
Compute log likelihood on the training data after .fit() has been called.
The log likelihood is computed on-demand based on the loss and, for example,
the observation noise which makes it differentiable in the latter for
iterative updates.
Returns:
-
log_likelihood(Tensor) –
prior_precision_diag
#
Obtain the diagonal prior precision \(p_0\) constructed from either a scalar, layer-wise, or diagonal prior precision.
Returns:
-
prior_precision_diag(Tensor) –
_uses_backpack_backend
#
_uses_backpack_backend: bool
Whether the curvature backend extends modules using BackPACK.
_uses_asdl_backend
#
_uses_asdl_backend: bool
Whether the curvature backend computes Jacobians using ASDL.
log_det_ratio
#
Computes log determinant term in GP marginal likelihood
For classification we use eq. (3.44) from Chapter 3.5 from
GP book R&W 2006 with
(note that we always use diagonal approximation \(D\) of the Hessian of log likelihood w.r.t. \(f\)):
log determinant term := \( \log | I + D^{1/2}K D^{1/2} | \)
For regression, we use "standard" GP marginal likelihood:
log determinant term := \( \log | K + \sigma_2 I | \)
scatter
#
Compute scatter term in GP log marginal likelihood.
For classification we use eq. (3.44) from Chapter 3.5 from
GP book R&W 2006 with \(\hat{f} = f \):
scatter term := \( f K^{-1} f^{T} \)
For regression, we use "standard" GP marginal likelihood:
scatter term := \( (y - m)K^{-1}(y -m )^T \), where \( m \) is the mean of the GP prior, which in our case corresponds to \( m := f + J (\theta - \theta_{MAP}) \)
__call__
#
__call__(
x: Tensor | MutableMapping,
pred_type: PredType | str = PredType.GP,
joint: bool = False,
link_approx: LinkApprox | str = LinkApprox.PROBIT,
n_samples: int = 100,
diagonal_output: bool = False,
generator: Generator | None = None,
fitting: bool = False,
**model_kwargs: dict[str, Any]
) -> Tensor | tuple[Tensor, Tensor]
Predict from the fitted function-space posterior.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
pred_type(PredType or str, default:PredType.GP) –Prediction type. Function-space estimators support only
"gp". -
joint(bool, default:False) –Retain cross-input covariance for regression predictions.
-
link_approx(LinkApprox or str, default:LinkApprox.PROBIT) –Approximation for the classification probability link.
-
n_samples(int, default:100) –Number of draws for a Monte Carlo classification link.
-
diagonal_output(bool, default:False) –Return only output variances for regression when supported.
-
generator(Generator or None, default:None) –Random generator for Monte Carlo classification predictions.
-
fitting(bool, default:False) –Evaluate reward-model preference pairs as classification inputs.
-
**model_kwargs(Any, default:{}) –Accepted for compatibility with the base prediction interface; these arguments are not forwarded to the model.
Returns:
-
Tensor or tuple[Tensor, Tensor]–Classification probabilities
[B, C], or regression/reward latent mean and covariance. Withjoint=True, the regression mean is flattened and covariance has shape[B*O, B*O].
Raises:
-
RuntimeError–If the posterior has not been fitted.
-
ValueError–If the input batch is empty, the prediction type or link is unsupported, or the generator has an incompatible type or device.
Notes
Regression and individual reward predictions exclude observation
noise. Their marginal mean is [B, O] and covariance is
[B, O, O], or variance [B, O] with diagonal_output=True.
Source code in laplace/baselaplace.py
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 | |
_glm_forward_call
#
_glm_forward_call(
x: Tensor | MutableMapping,
likelihood: Likelihood | str,
joint: bool = False,
link_approx: LinkApprox | str = LinkApprox.PROBIT,
n_samples: int = 100,
diagonal_output: bool = False,
) -> Tensor | tuple[Tensor, Tensor]
Compute the posterior predictive on input data x for "glm" pred type.
Parameters:
-
x(Tensor or MutableMapping) –(batch_size, input_shape)if tensor. If MutableMapping, must contain the said tensor. -
likelihood(Likelihood or str in {'classification', 'regression', 'reward_modeling'}) –determines the log likelihood Hessian approximation.
-
link_approx(('mc', 'probit', 'bridge', 'bridge_norm'), default:'mc') –how to approximate the classification link function for the
'glm'. Forpred_type='nn', only 'mc' is possible. -
joint(bool, default:False) –Whether to output a joint predictive distribution in regression with
pred_type='glm'. If set toTrue, the predictive distribution has the same form as GP posterior, i.e. N([f(x1), ...,f(xm)], Cov[f(x1), ..., f(xm)]). IfFalse, then only outputs the marginal predictive distribution. Only available for regression and GLM predictive. -
n_samples(int, default:100) –number of samples for
link_approx='mc'. -
diagonal_output(bool, default:False) –whether to use a diagonalized posterior predictive on the outputs. Only works for
pred_type='glm'andlink_approx='mc'.
Returns:
-
predictive(Tensor or tuple[Tensor]) –For
likelihood='classification', a torch.Tensor is returned with a distribution over classes (similar to a Softmax). Forlikelihood='regression', a tuple of torch.Tensor is returned with the mean and the predictive variance. Forlikelihood='regression'andjoint=True, a tuple of torch.Tensor is returned with the mean and the predictive covariance.
Source code in laplace/baselaplace.py
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 | |
sample
#
sample(
n_samples: int = 1, generator: Generator | None = None
) -> Tensor
Sample from the Laplace posterior approximation, i.e., \( \theta \sim \mathcal{N}(\theta_{MAP}, P^{-1})\).
Parameters:
-
n_samples(int, default:100) –number of samples
-
generator(Generator, default:None) –random number generator to control the samples
Returns:
-
samples(Tensor) –
Source code in laplace/baselaplace.py
functional_samples
#
functional_samples(
x: Tensor | MutableMapping,
pred_type: PredType | str = PredType.GLM,
n_samples: int = 100,
diagonal_output: bool = False,
generator: Generator | None = None,
joint: bool = False,
) -> Tensor
Draw latent outputs; use joint=True to retain cross-input covariance.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
pred_type(PredType or str, default:PredType.GLM) –Accepted for API compatibility. Every value draws from the function-space posterior;
"nn"does not draw model weights. -
n_samples(int, default:100) –Number of draws.
-
diagonal_output(bool, default:False) –Drop cross-output covariance before sampling.
-
generator(Generator or None, default:None) –Random generator on the model device.
-
joint(bool, default:False) –Retain covariance between input rows.
Returns:
-
Tensor–Latent draws shaped
[n_samples, B, O].
Raises:
-
RuntimeError–If the posterior has not been fitted.
-
ValueError–If the input batch is empty, the sampling type is unsupported, or
n_samplesis not positive.
Source code in laplace/baselaplace.py
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 | |
_glm_functional_samples
#
_glm_functional_samples(
f_mu: Tensor,
f_var: Tensor,
n_samples: int,
diagonal_output: bool = False,
generator: Generator | None = None,
) -> Tensor
Draw per-input latent samples from supplied Gaussian moments.
Parameters:
-
f_mu(Tensor) –Latent means shaped
[B, O]. -
f_var(Tensor) –Per-input covariance shaped
[B, O, O]. -
n_samples(int) –Number of draws.
-
diagonal_output(bool, default:False) –Drop covariance between output coordinates before sampling.
-
generator(Generator or None, default:None) –Random generator for the draws.
Returns:
-
Tensor–Latent draws shaped
[n_samples, B, O].
Source code in laplace/baselaplace.py
_glm_predictive_samples
#
_glm_predictive_samples(
f_mu: Tensor,
f_var: Tensor,
n_samples: int,
diagonal_output: bool = False,
generator: Generator | None = None,
) -> Tensor
Sample from the posterior predictive on input data x using "glm" prediction
type. I.e., the inverse-link function correponding to the likelihood is applied
on top of the functional sample.
Parameters:
-
f_mu(Tensor or MutableMapping) –glm predictive mean
(batch_size, output_shape) -
f_var(Tensor or MutableMapping) –glm predictive covariances
(batch_size, output_shape, output_shape) -
n_samples(int) –number of samples
-
diagonal_output(bool, default:False) –whether to use a diagonalized glm posterior predictive on the outputs.
-
generator(Generator, default:None) –random number generator to control the samples (if sampling used)
Returns:
-
samples(Tensor) –samples
(n_samples, batch_size, output_shape)
Source code in laplace/baselaplace.py
_checkpoint_configuration
#
Record input keys and backend options required by a checkpoint.
Returns:
Source code in laplace/baselaplace.py
_validate_checkpoint_configuration
#
Reject a checkpoint created with different input or backend settings.
Parameters:
Raises:
-
ValueError–If a required setting differs from the current estimator.
Source code in laplace/baselaplace.py
_check_fitted
#
Refresh a fitted posterior or reject predictions before fitting.
Raises:
-
RuntimeError–If
fithas not completed.
Source code in laplace/baselaplace.py
_check_nonempty_inputs
#
_check_nonempty_inputs(x: Tensor | MutableMapping) -> None
Require at least one input row for a function-space prediction.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
Raises:
-
ValueError–If the input batch is empty.
Source code in laplace/baselaplace.py
predictive_moments
#
predictive_moments(
x: Tensor | MutableMapping, *, joint: bool = False
) -> tuple[Tensor, Tensor]
Return latent predictive moments without observation noise.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
joint(bool, default:False) –Include covariance between input rows when
True.
Returns:
-
tuple[Tensor, Tensor]–Mean
[B, O]and covariance[B, O, O]by default. Withjoint=True, the mean is flattened and covariance has shape[B*O, B*O].
Raises:
-
RuntimeError–If the posterior has not been fitted.
-
ValueError–If the input batch is empty.
Source code in laplace/baselaplace.py
_classification_validation_nll
#
_classification_validation_nll(
x: Tensor | MutableMapping, targets: Tensor
) -> Tensor
Compute summed classification NLL using the probit logit scale.
Parameters:
-
x(Tensor or MutableMapping) –Validation inputs.
-
targets(Tensor) –Class targets for those inputs.
Returns:
-
Tensor–Summed negative log likelihood for the batch.
Source code in laplace/baselaplace.py
predictive_samples
#
predictive_samples(
x: Tensor | MutableMapping,
pred_type: PredType | str = PredType.GLM,
n_samples: int = 100,
diagonal_output: bool = False,
generator: Generator | None = None,
fitting: bool = False,
joint: bool = False,
) -> Tensor
Draw outputs and apply the classification link when appropriate.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
pred_type(PredType or str, default:PredType.GLM) –Accepted for function-space sampling API compatibility.
-
n_samples(int, default:100) –Number of draws.
-
diagonal_output(bool, default:False) –Drop cross-output covariance before sampling.
-
generator(Generator or None, default:None) –Random generator on the model device.
-
fitting(bool, default:False) –Interpret reward-model inputs as preference pairs.
-
joint(bool, default:False) –Retain covariance between input rows.
Returns:
-
Tensor–Predictive draws shaped
[n_samples, B, O].
Raises:
-
RuntimeError–If the posterior has not been fitted.
-
ValueError–If the input batch is empty, the sampling type is unsupported, or
n_samplesis not positive.
Notes
Classification draws are class probabilities obtained by applying softmax to latent samples. Regression and individual reward draws are latent function values without observation noise.
Source code in laplace/baselaplace.py
_check_prior_precision
#
_check_prior_precision(prior_precision: float | Tensor)
Checks if the given prior precision is suitable for the GP interpretation of LLA. As such, only single value priors, i.e., isotropic priors are suitable.
Source code in laplace/baselaplace.py
_init_K_MM
#
Allocates memory for the kernel matrix evaluated at the subset of the training data points. If the subset is of size \(M\) and the problem has \(C\) outputs, this is a list of C \((M,M\)) tensors for diagonal kernel and \((M x C, M x C)\) otherwise.
Source code in laplace/baselaplace.py
_init_Sigma_inv
#
Allocates memory for the cholesky decomposition of [ K_{MM} + \Lambda_{MM}^{-1}. ] See See Improving predictions of Bayesian neural nets via local linearization (Immer et al., 2021) Equation 15 for more information.
Source code in laplace/baselaplace.py
_store_K_batch
#
Given the kernel matrix between the i-th and the j-th batch, stores it in the corresponding position in self.K_MM.
Source code in laplace/baselaplace.py
_build_L
#
_build_L(lambdas: list[Tensor])
Given a list of the Hessians of per-batch log-likelihood w.r.t. neural network output \( f \), returns the contatenation of these hessians in a suitable format for the used kernel (diagonal or not).
In this function the diagonal approximation is performed. Please refer to the introduction of the class for more details.
Parameters:
-
lambdas(list of torch.Tensor of shape (C, C)) –Contains per-batch log-likelihood w.r.t. neural network output \( f \).
Returns:
-
L(list with length C of tensors with shape M or tensor (MxC)) –Contains the given Hessians in a suitable format.
Source code in laplace/baselaplace.py
_build_Sigma_inv
#
Computes the cholesky decomposition of [ K_{MM} + \Lambda_{MM}^{-1}. ] See See Improving predictions of Bayesian neural nets via local linearization (Immer et al., 2021) Equation 15 for more information.
<<<<<<< HEAD As the diagonal approximation is performed with \Lambda_{MM} (which is stored in self.L), ======= As the diagonal approximation is performed with \(\Lambda_{MM}\) (which is stored in self.L),
main the code is greatly simplified.
Source code in laplace/baselaplace.py
_get_SoD_data_loader
#
Subset-of-Datapoints data loader
Source code in laplace/baselaplace.py
fit
#
fit(
train_loader: DataLoader | MutableMapping,
progress_bar: bool = False,
)
Fit the Laplace approximation of a GP posterior.
Parameters:
-
train_loader(DataLoader) –train_loader.datasetneeds to be set to access \(N\), size of the data settrain_loader.batch_sizeneeds to be set to access \(b\) batch_size -
progress_bar(bool, default:False) –whether to show a progress bar during the fitting process.
Source code in laplace/baselaplace.py
2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 | |
_refresh_posterior
#
Rebuild the subset-of-data GP posterior after a prior change.
Warns:
-
UserWarning–If prior precision changed since fitting and the cached posterior must be recomputed.
Source code in laplace/baselaplace.py
functional_variance
#
GP posterior variance:
Parameters:
-
Js_star(torch.Tensor of shape (N*, C, P)) –Jacobians of test data points
Returns:
-
f_var(torch.Tensor of shape (N*,C, C)) –Contains the posterior variances of N* testing points.
Source code in laplace/baselaplace.py
functional_covariance
#
GP posterior covariance:
Parameters:
-
Js_star(torch.Tensor of shape (N*, C, P)) –Jacobians of test data points
Returns:
-
f_var(torch.Tensor of shape (N*xC, N*xC)) –Contains the posterior covariances of N* testing points.
Source code in laplace/baselaplace.py
_build_K_star_M
#
_build_K_star_M(
K_M_star: Tensor, joint: bool = False
) -> Tensor
Computes K_{M} (K_{MM}+ L_{MM}^{-1})^{-1} K_{M} given K_{M*}.
Parameters:
-
K_M_star(list of torch.Tensor) –Contains K_{M*}. Tensors have shape (N_test, C, C) or (N_test, C) for diagonal kernel. -
joint(boolean, default:False) –Wether to compute cross covariances or not.
Returns:
-
torch.tensor of shape (N_test, N_test, C) for joint diagonal,– -
(N_test, C) for non-joint diagonal, (N_test, N_test, C, C) for– -
joint non-diagonal and (N_test, C, C) for non-joint non-diagonal.–
Source code in laplace/baselaplace.py
optimize_prior_precision
#
optimize_prior_precision(
pred_type: PredType | str = PredType.GP,
method: TuningMethod | str = TuningMethod.MARGLIK,
n_steps: int = 100,
lr: float = 0.1,
init_prior_prec: float | Tensor = 1.0,
prior_structure: (
PriorStructure | str
) = PriorStructure.SCALAR,
val_loader: DataLoader | None = None,
loss: (
Metric | Callable[[Tensor], Tensor | float] | None
) = None,
log_prior_prec_min: float = -4,
log_prior_prec_max: float = 4,
grid_size: int = 100,
link_approx: LinkApprox | str = LinkApprox.PROBIT,
n_samples: int = 100,
verbose: bool = False,
progress_bar: bool = False,
log_prior_prec_base: float = 10.0,
) -> None
optimize_prior_precision_base from BaseLaplace with pred_type='gp'
Source code in laplace/baselaplace.py
_kernel_batch
#
Compute K_bb, which is part of K_MM kernel matrix.
Parameters:
-
jacobians(Tensor(b, C, P)) – -
batch(Tensor(b, C)) –
Returns:
-
kernel(tensor) –K_bb with shape (b * C, b * C)
Source code in laplace/baselaplace.py
_kernel_star
#
_kernel_star(
jacobians: Tensor, joint: bool = False
) -> Tensor
Compute K_star_star kernel matrix.
Parameters:
-
jacobians(Tensor(b, C, P)) –
Returns:
-
kernel(tensor) –K_star with shape (b, C, C)
Source code in laplace/baselaplace.py
_kernel_batch_star
#
Compute K_b_star, which is a part of K_M_star kernel matrix.
Parameters:
-
jacobians(Tensor(b1, C, P)) – -
batch(Tensor(b2, C)) –
Returns:
-
kernel(tensor) –K_batch_star with shape (b1, b2, C, C)
Source code in laplace/baselaplace.py
_jacobians
#
A wrapper function to compute jacobians - this enables reusing same kernel methods (kernel_batch etc.) in FunctionalLaplace and FunctionalLLLaplace by simply overwriting this method instead of all kernel methods.
Source code in laplace/baselaplace.py
_mean_scatter_term_batch
#
Compute mean vector in the scatter term in the log marginal likelihood
See scatter_lml property above for the exact equations of mean vectors in scatter terms for
both types of likelihood (regression, classification).
Parameters:
-
Js(tensor) –Jacobians (batch, output_shape, parameters)
-
f(tensor) –NN output (batch, output_shape)
-
y(Tensor) –data labels (batch, output_shape)
Returns:
-
mu(tensor) –K_batch_star with shape (batch, output_shape)
Source code in laplace/baselaplace.py
log_marginal_likelihood
#
log_marginal_likelihood(
prior_precision: Tensor | None = None,
sigma_noise: Tensor | None = None,
) -> Tensor
Compute the Laplace approximation to the log marginal likelihood.
Requires that the Laplace approximation has been fit before.
The resulting torch.Tensor is differentiable in prior_precision and
sigma_noise if these have gradients enabled.
By passing prior_precision or sigma_noise, the current value is
overwritten. This is useful for iterating on the log marginal likelihood.
Parameters:
-
prior_precision(Tensor, default:None) –prior precision if should be changed from current
prior_precisionvalue -
sigma_noise(Tensor, default:None) –observation noise standard deviation if should be changed
Returns:
-
log_marglik(Tensor) –