VaLLA#
laplace.baselaplace.VaLLA
#
VaLLA(
model: Module,
likelihood: Likelihood | str,
inducing_locations: Tensor | MutableMapping | str,
num_inducing: int | None = None,
inducing_classes: Tensor | None = None,
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,
seed: int = 0,
alpha: float = 1.0,
mc_softmax_samples: int = 0,
)
Bases: BaseFunctionalLaplace
Variational linearized Laplace with inducing outputs and a fixed MAP model.
The network weights remain fixed while fit optimizes the variational
factor, inducing locations, prior precision, and regression noise.
Parameters:
-
model(Module) –Pretrained network to linearize.
-
likelihood(Likelihood or str) –"classification","regression", or"reward_modeling". -
inducing_locations(torch.Tensor, MutableMapping, or str) –Initial inputs, or
"random"or"kmeans"to select them from the training loader. Floating-point tensor locations are optimized; mapping-style and integer tensor locations remain fixed. -
num_inducing(int or None, default:None) –Number of locations required with a selection strategy. If explicit locations are supplied, this must match their count when provided.
-
inducing_classes(Tensor or None, default:None) –Output coordinate selected at each inducing location, shaped
[num_inducing]. Explicit inputs default to coordinate zero. Strategies use training class labels for classification and coordinate zero for regression and individual rewards. -
sigma_noise(float or Tensor, default:1.0) –Initial observation standard deviation for regression.
-
prior_precision(float or Tensor, default:1.0) –Initial scalar parameter-prior precision.
-
prior_mean(float or Tensor, default:0.0) –Prior mean; only zero is supported.
-
temperature(float, default:1.0) –Positive scale of the likelihood contribution.
-
enable_backprop(bool, default:False) –Retain derivatives through predictive moments.
-
dict_key_x(str, default:"input_ids") –Input key for mapping-style batches.
-
dict_key_y(str, default:"labels") –Target key for mapping-style batches.
-
backend(type[CurvatureInterface] or None, default:None) –Curvature backend used for parameter Jacobians.
-
backend_kwargs(dict[str, Any] or None, default:None) –Additional curvature backend options.
-
seed(int, default:0) –Seed for inducing-point selection and Monte Carlo fitting.
-
alpha(float, default:1.0) –Alpha-divergence value in
[0, 1]; zero uses the ELBO limit. -
mc_softmax_samples(int, default:0) –Monte Carlo draws for classification data terms when positive. Required for classification or reward modeling when
alpha != 1.
Attributes:
-
fit_history_(dict[str, list[float]]) –objectiverecords minibatch-scaled objective values computed before each update;val_nllrecords validation negative log likelihood. -
L(Parameter) –Packed lower-triangular variational factor containing
num_inducing * (num_inducing + 1) // 2entries. -
log_prior_precision(Parameter) –Trainable logarithm of scalar parameter-prior precision.
-
log_noise_variance(Parameter or None) –Trainable logarithm of observation variance for regression;
Nonefor classification and reward modeling. -
generator(Generator) –Random generator for Monte Carlo data terms on the model device.
Notes
fit returns None and records objective and validation NLL in
fit_history_. Repeated fits reset variational and inducing state by
default; fit(..., override=False) continues optimization.
Source code in laplace/baselaplace.py
4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 | |
_backend_kwargs
#
_asdl_fisher_kwargs
#
_asdl_fisher_kwargs: dict[str, Any] = (
dict()
if asdl_fisher_kwargs is None
else asdl_fisher_kwargs
)
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_noise_variance
#
log_noise_variance = (
Parameter(2 * clone())
if likelihood == REGRESSION
else None
)
_inducing_strategy
#
_inducing_strategy = (
inducing_locations
if isinstance(inducing_locations, str)
else None
)
inducing_classes
#
inducing_classes = (
zeros(num_inducing, device=_device, dtype=long)
if inducing_classes is None
else as_tensor(
inducing_classes, device=_device, dtype=long
)
)
_initial_inducing_locations
#
_initial_inducing_locations = (
None
if _inducing_strategy is not None
else _clone_fixed_inputs(inducing_locations)
)
log_likelihood
#
Reject access to an untracked training log likelihood.
Raises:
-
NotImplementedError–Always raised because VaLLA records its alpha-divergence objective rather than a training log likelihood.
_curv_closure
#
_curv_closure(
X: Tensor | MutableMapping[str, Tensor | Any],
y: Tensor,
N: int,
) -> tuple[Tensor, Tensor]
__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 | |
predictive
#
predictive(
x: Tensor,
pred_type: PredType | str,
link_approx: LinkApprox | str,
n_samples: int,
) -> Tensor | tuple[Tensor, Tensor]
Source code in laplace/baselaplace.py
_check_jacobians
#
Source code in laplace/baselaplace.py
_gridsearch
#
_gridsearch(
loss: Metric | Callable[[Tensor], Tensor | float],
interval: Tensor,
val_loader: DataLoader,
pred_type: PredType | str,
link_approx: LinkApprox | str = LinkApprox.PROBIT,
n_samples: int = 100,
progress_bar: bool = False,
) -> Tensor
Source code in laplace/baselaplace.py
_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
_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
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
_clone_fixed_inputs
#
Detach and recursively copy fixed inducing inputs.
Parameters:
-
value(Any) –Tensor, mapping, sequence, or metadata to copy.
Returns:
-
Any–Independent copy with detached tensors and the same nesting.
Source code in laplace/baselaplace.py
_make_inducing
#
Prepare inducing inputs and expose eligible locations for optimization.
Parameters:
-
inputs(Any) –Batched inducing tensor, mapping-style model input, or an array-like input convertible to a floating-point tensor.
Returns:
-
Tensor or dict–Copied inputs on the model device. Floating-point tensor inputs become trainable parameters in the model dtype. Mappings and integer tensors remain detached and fixed.
Source code in laplace/baselaplace.py
_init_variational_factor
#
Initialize the packed lower-triangular variational factor.
Source code in laplace/baselaplace.py
_factor_matrix
#
Unpack the trainable lower-triangular variational factor.
Returns:
-
Tensor–Lower-triangular matrix shaped
[num_inducing, num_inducing]with gradients retained through its packed entries inL.
Source code in laplace/baselaplace.py
_batch
#
Move a training batch and its targets to the model device.
Parameters:
-
batch(Any) –(inputs, targets)or a mapping containingdict_key_y.
Returns:
-
tuple[Any, Tensor]–Model inputs and targets on the model device. Floating-point inputs use the model dtype; target dtypes are preserved.
Source code in laplace/baselaplace.py
_gather_inducing
#
Choose inducing inputs and output coordinates from training data.
Parameters:
-
loader(DataLoader) –Training loader used for random or k-means selection.
Raises:
-
ValueError–If the loader is empty, too small, or incompatible with k-means.
Source code in laplace/baselaplace.py
4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 | |
_query_jacobians
#
_query_jacobians(
x: Tensor | MutableMapping,
*,
differentiable: bool = False
) -> tuple[Tensor, Tensor]
Return model Jacobians and outputs for query inputs.
Parameters:
-
x(Tensor or MutableMapping) –Batched inputs.
-
differentiable(bool, default:False) –Preserve gradients through Jacobian computation.
Returns:
-
tuple[Tensor, Tensor]–Parameter Jacobians shaped
[batch, outputs, parameters]and network outputs shaped[batch, outputs].
Source code in laplace/baselaplace.py
_inducing_jacobians
#
Return selected-output Jacobians at all inducing locations.
Returns:
-
Tensor–Parameter Jacobians shaped
[num_inducing, parameters], with one output coordinate per location. Gradients through trainable inducing locations are retained.
Raises:
-
RuntimeError–If inducing locations have not been initialized.
Source code in laplace/baselaplace.py
_inducing_factor
#
_inducing_factor(
jacobians: Tensor,
) -> tuple[Tensor, Tensor, Tensor]
Factor the inducing system without forming its Gram matrix.
Parameters:
-
jacobians(Tensor) –Selected-output inducing Jacobians shaped
[num_inducing, parameters].
Returns:
-
features(Tensor) –Variationally transformed inducing Jacobians divided by the square root of prior precision, shaped
[num_inducing, parameters]. -
basis(Tensor) –Reduced QR basis of the vertically stacked feature transpose and identity, shaped
[parameters + num_inducing, num_inducing]. -
triangular(Tensor) –Upper-triangular QR factor shaped
[num_inducing, num_inducing].
Notes
The factorization uses float64 arithmetic for numerical stability.
Source code in laplace/baselaplace.py
_posterior_covariance
#
_posterior_covariance(
jacobians: Tensor,
inducing_jacobians: Tensor,
*,
joint: bool,
basis: Tensor | None = None
) -> Tensor
Form latent covariance using the orthogonal inducing complement.
Parameters:
-
jacobians(Tensor) –Query Jacobians shaped
[batch, outputs, parameters]. -
inducing_jacobians(Tensor) –Selected-output inducing Jacobians shaped
[num_inducing, parameters]. -
joint(bool) –Include covariance between query inputs when true.
-
basis(Tensor or None, default:None) –Precomputed orthonormal inducing basis shaped
[parameters + num_inducing, num_inducing]. Computed frominducing_jacobianswhen omitted.
Returns:
-
Tensor–Latent covariance shaped
[batch, outputs, outputs], or[batch * outputs, batch * outputs]whenjoint=True, in the query Jacobian dtype. Observation noise is excluded.
Source code in laplace/baselaplace.py
_latent_distribution
#
_latent_distribution(
x: Tensor | MutableMapping, joint: bool = False
) -> tuple[Tensor, Tensor, Tensor, Tensor]
Return latent moments and factors for the variational objective.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
joint(bool, default:False) –Retain covariance between input rows.
Returns:
-
mean(Tensor) –Network outputs shaped
[batch, outputs], including whenjoint=True. -
covariance(Tensor) –Latent covariance shaped
[batch, outputs, outputs], or[batch * outputs, batch * outputs]whenjoint=True. Observation noise is excluded. -
features(Tensor) –Float64 scaled variational features shaped
[num_inducing, parameters]. -
triangular(Tensor) –Float64 upper-triangular inducing-system factor shaped
[num_inducing, num_inducing].
Source code in laplace/baselaplace.py
_glm_predictive_distribution
#
_glm_predictive_distribution(
x: Tensor | MutableMapping, joint: bool = False
) -> tuple[Tensor, Tensor]
Compute model outputs and VaLLA latent covariance for inputs.
Parameters:
-
x(Tensor or MutableMapping) –Batched model inputs.
-
joint(bool, default:False) –Retain covariance between input rows.
Returns:
-
mean(Tensor) –Network outputs shaped
[batch, outputs], flattened to[batch * outputs]whenjoint=True. -
covariance(Tensor) –Latent covariance shaped
[batch, outputs, outputs], or[batch * outputs, batch * outputs]whenjoint=True. Observation noise is excluded.
Source code in laplace/baselaplace.py
functional_variance
#
Return per-input latent covariance from parameter Jacobians.
Parameters:
-
jacobians(Tensor) –Parameter Jacobians shaped
[batch, outputs, parameters].
Returns:
-
Tensor–Per-input covariance shaped
[batch, outputs, outputs].
Source code in laplace/baselaplace.py
functional_covariance
#
Return joint latent covariance from parameter Jacobians.
Parameters:
-
jacobians(Tensor) –Parameter Jacobians shaped
[batch, outputs, parameters].
Returns:
-
Tensor–Joint covariance shaped
[batch * outputs, batch * outputs].
Source code in laplace/baselaplace.py
_objective
#
_objective(x: Any, y: Tensor) -> Tensor
Return the minibatch-scaled alpha objective plus inducing KL.
Parameters:
-
x(Any) –Batched model inputs.
-
y(Tensor) –Regression targets or class labels.
Returns:
-
Tensor–Scalar loss minimized during fitting.
Source code in laplace/baselaplace.py
5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 | |
_validation_nll
#
Return mean predictive negative log likelihood on a loader.
Parameters:
-
loader(DataLoader) –Nonempty validation loader with regression targets or class labels.
Returns:
-
Tensor–Scalar NLL averaged over examples, summing over regression output coordinates. Regression includes observation noise; classification uses the probit approximation.
Source code in laplace/baselaplace.py
fit
#
fit(
train_loader: DataLoader,
*,
iterations: int = 100,
lr: float = 0.001,
val_loader: DataLoader | None = None,
val_steps: int | None = None,
progress_bar: bool = False,
override: bool = True
) -> None
Optimize the VaLLA variational posterior and hyperparameters.
Parameters:
-
train_loader(DataLoader) –Training batches used for inducing selection and optimization.
-
iterations(int, default:100) –Number of minibatch optimizer steps.
-
lr(float, default:1e-3) –Adam learning rate.
-
val_loader(DataLoader or None, default:None) –Optional data for predictive negative log likelihood.
-
val_steps(int or None, default:None) –Evaluate validation NLL every
val_stepsiterations when given. -
progress_bar(bool, default:False) –Show an optimization progress bar.
-
override(bool, default:True) –Reset inducing and variational state; false continues a prior fit.
Raises:
-
ValueError–If optimization settings or inducing classes are invalid.
Source code in laplace/baselaplace.py
5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 | |
optimize_prior_precision
#
Reject separate prior tuning because :meth:fit learns the precision.
Parameters:
-
*args(Any, default:()) –Positional arguments accepted for compatibility with BaseLaplace.
-
**kwargs(Any, default:{}) –Keyword arguments accepted for compatibility with BaseLaplace.
Raises:
-
NotImplementedError–Always raised. VaLLA optimizes prior precision jointly with the variational parameters during fitting.
Source code in laplace/baselaplace.py
log_marginal_likelihood
#
Reject marginal-likelihood evaluation for the VaLLA approximation.
Parameters:
-
*args(Any, default:()) –Positional arguments accepted for compatibility with BaseLaplace.
-
**kwargs(Any, default:{}) –Keyword arguments accepted for compatibility with BaseLaplace.
Raises:
-
NotImplementedError–Always raised. The optimized alpha-divergence objective is not a Laplace marginal likelihood.
Source code in laplace/baselaplace.py
state_dict
#
Return a checkpoint containing fitted variational and inducing state.
Returns:
-
dict[str, Any]–Variational factor, inducing locations and output coordinates, hyperparameters, fitting history, initialization settings, random generator state, model fingerprint, and backend/input settings.
Raises:
-
RuntimeError–If the posterior has not been fitted.
Notes
Loading validates the pretrained model against the saved fingerprint; it does not restore model parameters or buffers. Construct the receiving estimator with the same pretrained model and configuration.
Source code in laplace/baselaplace.py
load_state_dict
#
Restore a fitted VaLLA checkpoint for the same pretrained model.
Parameters:
Raises:
-
ValueError–If the checkpoint is unfitted or incompatible with this model.