laplacekit-gp 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,71 @@
1
+ """GP methods for function-space Laplace: ELLA, VaLLA and FSP-Laplace.
2
+
3
+ The methods are ELLA (Deng et al. 2022), VaLLA (Ortega et al. 2024) and FSP-Laplace
4
+ (Cinquin et al. 2024). ELLA approximates the linearized network's kernel with Nyström
5
+ features. VaLLA fits variational inducing points. FSP-Laplace places a GP prior on the
6
+ network's outputs.
7
+
8
+ Code reaches this package as `lk.gp`, which imports it on first use.
9
+ """
10
+
11
+ import laplacekit as lk
12
+ from laplacekit_gp.fsp import (
13
+ MAX_CONTEXT_JACOBIAN_ENTRIES,
14
+ FSPPosterior,
15
+ FunctionPrior,
16
+ RangePrecision,
17
+ fsp_laplace,
18
+ rkhs_norm,
19
+ )
20
+ from laplacekit_gp.kernels import RBF, Kernel, Matern, Periodic, Product, Sum
21
+ from laplacekit_gp.nystrom import ELLA, MAX_BASIS_ENTRIES, NystromGP
22
+ from laplacekit_gp.points import (
23
+ MAX_KMEANS_ENTRIES,
24
+ Drawn,
25
+ Picked,
26
+ Points,
27
+ fixed,
28
+ from_data,
29
+ grid,
30
+ kmeans,
31
+ uniform,
32
+ )
33
+ from laplacekit_gp.variational import (
34
+ VaLLA,
35
+ VariationalGP,
36
+ fit_variational,
37
+ variational_loss,
38
+ )
39
+
40
+ __all__: list[str] = [
41
+ "MAX_BASIS_ENTRIES",
42
+ "MAX_CONTEXT_JACOBIAN_ENTRIES",
43
+ "MAX_KMEANS_ENTRIES",
44
+ "RBF",
45
+ "Drawn",
46
+ "FSPPosterior",
47
+ "FunctionPrior",
48
+ "Kernel",
49
+ "Matern",
50
+ "ELLA",
51
+ "NystromGP",
52
+ "Periodic",
53
+ "Picked",
54
+ "Points",
55
+ "Product",
56
+ "RangePrecision",
57
+ "Sum",
58
+ "VaLLA",
59
+ "VariationalGP",
60
+ "fit_variational",
61
+ "fixed",
62
+ "from_data",
63
+ "fsp_laplace",
64
+ "grid",
65
+ "kmeans",
66
+ "rkhs_norm",
67
+ "uniform",
68
+ "variational_loss",
69
+ ]
70
+
71
+ plugin = lk.Plugin(supports=">=1.0,<2")
laplacekit_gp/_gram.py ADDED
@@ -0,0 +1,151 @@
1
+ """The GGN projected onto a basis, Vᵀ (Σ wₙ Jₙᵀ Hₙ Jₙ) V, as a monoid."""
2
+
3
+ from typing import Self, get_args
4
+
5
+ import torch
6
+ from torch import Tensor
7
+ from torch.func import vmap
8
+
9
+ from laplacekit.core import (
10
+ MAX_DENSE_EVENT,
11
+ Batch,
12
+ FitContext,
13
+ HasOutputHessian,
14
+ Params,
15
+ Requirements,
16
+ Strategy,
17
+ StructureError,
18
+ output_hessian,
19
+ pytree,
20
+ replace,
21
+ stat_dtype,
22
+ static,
23
+ )
24
+ from laplacekit_gp._jacobian import features
25
+
26
+ __all__ = ["GramStat", "ProjectedGram", "check_event"]
27
+
28
+
29
+ def check_event(ctx: FitContext, what: str, /) -> None:
30
+ """Raise `StructureError` when the MC Fisher would form dense blocks too large.
31
+
32
+ The MC Fisher stands in for the output Hessian of a likelihood without
33
+ `HasOutputHessian`. Its blocks are `[E, E]`, with E from the probe, and E may not
34
+ exceed `MAX_DENSE_EVENT`.
35
+ """
36
+
37
+ event = ctx.caps.event_size
38
+
39
+ if (
40
+ event is not None
41
+ and event > MAX_DENSE_EVENT
42
+ and not isinstance(ctx.likelihood, HasOutputHessian)
43
+ ):
44
+ raise StructureError(
45
+ f"{what} with the MC Fisher forms a dense {event}x{event} matrix per example; "
46
+ f"give {type(ctx.likelihood).__name__} an output_hessian method (HasOutputHessian)"
47
+ )
48
+
49
+
50
+ @pytree
51
+ class GramStat:
52
+ """A weighted sum of `[r, r]` projected GGN terms, with the total weight."""
53
+
54
+ gram: Tensor
55
+ weight: Tensor
56
+
57
+ @property
58
+ def total_weight(self) -> Tensor:
59
+ return self.weight
60
+
61
+ def __add__(self, other: Self, /) -> Self:
62
+ return type(self)(self.gram + other.gram, self.weight + other.weight)
63
+
64
+ def scaled(self, s: Tensor, /) -> Self:
65
+ return type(self)(s * self.gram, s * self.weight)
66
+
67
+
68
+ @pytree
69
+ class ProjectedGram:
70
+ """Σₙ wₙ Φₙᵀ Hₙ Φₙ, where Φₙ = Jₙ `basis` and `basis` is `[P, r]` in the order of the params.
71
+
72
+ H is the output Hessian of the fit's likelihood without its curvature scale, or the
73
+ MC Fisher when the likelihood has no closed-form Hessian. Each term is Φₙᵀ (H Φₙ),
74
+ with `mv` applying H to the r columns of Φ, and is then symmetrized. `strategy` sets how Φ
75
+ is formed (see `features`). `finalize` returns the per-example average with the total
76
+ weight, and refuses a total weight of zero.
77
+ """
78
+
79
+ basis: Tensor
80
+ strategy: Strategy = static()
81
+
82
+ def __post_init__(self) -> None:
83
+ if self.strategy not in get_args(Strategy.__value__):
84
+ raise ValueError(
85
+ 'ProjectedGram strategy must be "forward-mode" or "reverse-mode", '
86
+ f"got {self.strategy!r}"
87
+ )
88
+
89
+ @property
90
+ def requires(self) -> Requirements:
91
+ return Requirements(
92
+ jvp=self.strategy == "forward-mode",
93
+ vjp=self.strategy == "reverse-mode",
94
+ vmap=True,
95
+ needs_output_hessian=True,
96
+ )
97
+
98
+ def init(self, params: Params, ctx: FitContext, /) -> GramStat:
99
+ n_params = sum(p.numel() for p in params.values())
100
+
101
+ if self.basis.ndim != 2 or self.basis.shape[0] != n_params:
102
+ raise StructureError(
103
+ f"ProjectedGram needs a [P, r] basis with P = {n_params} (the parameter "
104
+ f"count), got shape {tuple(self.basis.shape)}"
105
+ )
106
+
107
+ check_event(ctx, "ProjectedGram")
108
+
109
+ p = next(iter(params.values()))
110
+ dtype = stat_dtype(p.dtype)
111
+ r = self.basis.shape[1]
112
+
113
+ return GramStat(
114
+ torch.zeros(r, r, dtype=dtype, device=p.device),
115
+ torch.zeros((), dtype=dtype, device=p.device),
116
+ )
117
+
118
+ def update(
119
+ self,
120
+ stat: GramStat,
121
+ params: Params,
122
+ batch: Batch,
123
+ generator: torch.Generator,
124
+ ctx: FitContext,
125
+ /,
126
+ ) -> GramStat:
127
+ dtype = stat.gram.dtype
128
+ f, phi = features(ctx.model, params, batch.inputs, self.basis, self.strategy, dtype)
129
+ hess = output_hessian(ctx.likelihood, f, generator=generator, inputs=batch.inputs)
130
+ n, e = phi.shape[0], phi.shape[1]
131
+
132
+ if batch.weights is None:
133
+ w = torch.ones(n, dtype=dtype, device=phi.device)
134
+ elif bool((batch.weights < 0).any()):
135
+ raise ValueError("Batch.weights must be non-negative")
136
+ else:
137
+ w = batch.weights.to(dtype)
138
+
139
+ # H applied to Φ's r columns: r `mv` calls under one vmap, none per output entry.
140
+ cols = phi.to(f.dtype).reshape(n, *f.shape[1:], -1)
141
+ h_phi = vmap(hess.mv, in_dims=-1, out_dims=-1)(cols).reshape(n, e, -1).to(dtype)
142
+ term = torch.einsum("n,ner,nes->rs", w, phi, h_phi)
143
+ gram = stat.gram + (term + term.T) / 2
144
+
145
+ return replace(stat, gram=gram, weight=stat.weight + w.sum())
146
+
147
+ def finalize(self, stat: GramStat, /) -> GramStat:
148
+ if not bool(stat.weight > 0):
149
+ raise ValueError("ProjectedGram saw no data with positive weight")
150
+
151
+ return replace(stat, gram=stat.gram / stat.weight)
@@ -0,0 +1,161 @@
1
+ """Jacobian rows, and products of the Jacobian with a basis, for a model's flattened outputs.
2
+
3
+ Parameters are flattened in the order of `params`, and the P columns follow that order.
4
+ Outputs are flattened per example, so E is the number of output entries of one example.
5
+ """
6
+
7
+ import math
8
+ from collections.abc import Mapping
9
+ from typing import Any, cast
10
+
11
+ import torch
12
+ from torch import Tensor
13
+ from torch.func import jvp, vjp, vmap
14
+
15
+ from laplacekit.core import (
16
+ Capabilities,
17
+ Inputs,
18
+ ModelFn,
19
+ Params,
20
+ Strategy,
21
+ StructureError,
22
+ tree_map,
23
+ )
24
+ from laplacekit.function_space import is_shared, jacobian
25
+
26
+ __all__ = ["JVP_CHUNK", "VJP_CHUNK_ENTRIES", "choose_via", "features", "rows"]
27
+
28
+ JVP_CHUNK = 64
29
+ """The number of basis columns that `features` pushes through one vmapped `jvp`."""
30
+
31
+ VJP_CHUNK_ENTRIES = 2**24
32
+ """The most Jacobian entries (inputs times E times P) in one block of `features` with
33
+ `strategy="reverse-mode"`. The E P rows of a single input always go in one block."""
34
+
35
+
36
+ def choose_via(caps: Capabilities, /) -> Strategy:
37
+ """Choose the mode for `features`: jvp when the probe found jvp and vmap, else vjp.
38
+
39
+ Forward mode pushes the r basis columns through the model. Reverse mode builds all
40
+ E P Jacobian rows of each input and multiplies them by the `[P, r]` basis, which costs
41
+ E P memory and 2 E P r flops per input. Forward mode was faster on the models
42
+ measured, even with r above E, so it is the default, as in laplace-torch's `ELLA`.
43
+ Without jvp or without vmap, the choice is vjp. Without vmap, the method's check of
44
+ its requirements then refuses the model.
45
+ """
46
+
47
+ return "forward-mode" if caps.jvp and caps.vmap else "reverse-mode"
48
+
49
+
50
+ def _in_dims(inputs: Inputs) -> tuple[Any, Any]:
51
+ """Which leaves are shared by every input, and the matching `vmap` in_dims.
52
+
53
+ Shared leaves are 0-dim tensors and non-tensors.
54
+ """
55
+
56
+ shared = tree_map(is_shared, inputs)
57
+ in_dims = tree_map(lambda sh: None if sh else 0, shared)
58
+
59
+ return shared, in_dims
60
+
61
+
62
+ def _flat(grads: Mapping[str, Tensor], names: list[str], lead: int) -> Tensor:
63
+ """Concatenate per-parameter tensors, keeping `lead` leading axes."""
64
+
65
+ return torch.cat([grads[k].reshape(*grads[k].shape[:lead], -1) for k in names], dim=lead)
66
+
67
+
68
+ def rows(
69
+ model: ModelFn, params: Params, inputs: Inputs, coords: Tensor | None, dtype: torch.dtype
70
+ ) -> Tensor:
71
+ """Jacobian rows of the flattened outputs, `[m k, P]` for m inputs.
72
+
73
+ With `coords=None`, it returns the rows of every output entry (k = E, row n E + e),
74
+ like `fs.jacobian`. Otherwise `coords`, `[m]` int64, selects one flattened entry per
75
+ input (k = 1), computed by a VJP with a one-hot cotangent per input, vmapped over the
76
+ inputs.
77
+ """
78
+
79
+ if coords is None:
80
+ return jacobian(model, params, inputs, dtype)
81
+
82
+ names = list(params)
83
+ p = dict(params)
84
+ shared, in_dims = _in_dims(inputs)
85
+
86
+ def lead(x: Inputs) -> Inputs:
87
+ return tree_map(lambda t, sh: t if sh else t.unsqueeze(0), x, shared)
88
+
89
+ def one(x: Inputs, c: Tensor) -> Tensor:
90
+ xb = lead(x)
91
+
92
+ def fwd(q: Params) -> Tensor:
93
+ return cast(Tensor, model(q, xb)).reshape(-1)
94
+
95
+ out, pull = cast(Any, vjp(fwd, p))
96
+ hot = (torch.arange(out.shape[0], device=out.device) == c).to(out.dtype)
97
+
98
+ return _flat(cast(Mapping[str, Tensor], pull(hot)[0]), names, 0)
99
+
100
+ return vmap(one, in_dims=(in_dims, 0))(inputs, coords).to(dtype)
101
+
102
+
103
+ def features(
104
+ model: ModelFn,
105
+ params: Params,
106
+ inputs: Inputs,
107
+ basis: Tensor,
108
+ strategy: Strategy,
109
+ dtype: torch.dtype,
110
+ ) -> tuple[Tensor, Tensor]:
111
+ """The outputs f and Φ = J(x) basis, `[N, E, r]`, for a `[P, r]` basis.
112
+
113
+ `strategy="forward-mode"` pushes the basis columns forward, `JVP_CHUNK` at a time under `vmap`,
114
+ after casting each column to its parameter's dtype. `strategy="reverse-mode"` takes the Jacobian
115
+ rows (`rows`) of a few inputs at a time, up to `VJP_CHUNK_ENTRIES` entries or one
116
+ input, and multiplies each block by the basis. Φ comes back in `dtype`, and f as the
117
+ model returns it. A model whose outputs are not one tensor raises `StructureError`.
118
+ """
119
+
120
+ p = dict(params)
121
+ out = model(p, inputs)
122
+
123
+ if not isinstance(out, Tensor):
124
+ raise StructureError(
125
+ f"features need a model returning one tensor, got {type(out).__name__}"
126
+ )
127
+
128
+ f = out
129
+ n, e, r = f.shape[0], math.prod(f.shape[1:]), basis.shape[1]
130
+
131
+ if strategy == "reverse-mode":
132
+ n_params = sum(v.numel() for v in p.values())
133
+ step = max(1, VJP_CHUNK_ENTRIES // max(1, e * n_params))
134
+ shared, _ = _in_dims(inputs)
135
+ b = basis.to(dtype)
136
+ blocks = []
137
+
138
+ # The rows of `step` inputs at a time, each block projected before the next.
139
+ for s in range(0, n, step):
140
+ part = tree_map(lambda t, sh, s=s: t if sh else t[s : s + step], inputs, shared)
141
+ blocks.append(rows(model, params, part, None, dtype) @ b)
142
+
143
+ return f, torch.cat(blocks).reshape(n, e, r)
144
+
145
+ names = list(p)
146
+ sizes = [p[k].numel() for k in names]
147
+
148
+ def fwd(q: Params) -> Tensor:
149
+ return cast(Tensor, model(q, inputs))
150
+
151
+ def push(column: Tensor) -> Tensor:
152
+ parts = torch.split(column, sizes)
153
+ tangent = {
154
+ k: v.reshape(p[k].shape).to(p[k].dtype) for k, v in zip(names, parts, strict=True)
155
+ }
156
+
157
+ return cast(Tensor, jvp(fwd, (p,), (tangent,))[1]).reshape(n, e)
158
+
159
+ cols = [vmap(push)(basis[:, s : s + JVP_CHUNK].T).to(dtype) for s in range(0, r, JVP_CHUNK)]
160
+
161
+ return f, torch.cat(cols).permute(1, 2, 0)
@@ -0,0 +1,80 @@
1
+ """Lanczos tridiagonalization of a symmetric positive definite matrix.
2
+
3
+ The module also gives the inverse root that the tridiagonal matrix yields (Golub and Van
4
+ Loan, section 10.1).
5
+ """
6
+
7
+ from collections.abc import Callable
8
+
9
+ import torch
10
+ from torch import Tensor
11
+
12
+ __all__ = ["lanczos", "pinv_root"]
13
+
14
+ _BREAKDOWN = 1e-12
15
+ """Lanczos stops when β falls below this fraction of the norm of T so far."""
16
+
17
+
18
+ def lanczos(mv: Callable[[Tensor], Tensor], v0: Tensor, steps: int) -> tuple[Tensor, Tensor]:
19
+ """Q `[n, k]` with orthonormal columns, and the tridiagonal T = Qᵀ K Q `[k, k]`.
20
+
21
+ `mv` applies K, and `v0`, `[n]`, is the start vector. Each new vector is
22
+ orthogonalized twice against all earlier ones. Everything runs in float64, and `mv`
23
+ receives float64 vectors. Lanczos stops after `steps` steps, or earlier when β, the
24
+ norm of the next residual, falls below 1e-12 times the norm of T. The Krylov space is
25
+ then invariant, so k ≤ `steps`. Raises `ValueError` when `v0` is zero or `steps` is
26
+ below 1.
27
+ """
28
+
29
+ if steps < 1:
30
+ raise ValueError(f"lanczos needs steps >= 1, got {steps}")
31
+
32
+ v = v0.to(torch.float64)
33
+ norm = v.norm()
34
+
35
+ if not bool(norm > 0):
36
+ raise ValueError("lanczos needs a nonzero start vector")
37
+
38
+ qs = [v / norm]
39
+ alphas: list[Tensor] = []
40
+ betas: list[Tensor] = []
41
+
42
+ for j in range(steps):
43
+ w = mv(qs[j]).to(torch.float64)
44
+ alphas.append(qs[j] @ w)
45
+ q = torch.stack(qs, dim=1)
46
+
47
+ # Full reorthogonalization, twice ("twice is enough").
48
+ w = w - q @ (q.T @ w)
49
+ w = w - q @ (q.T @ w)
50
+
51
+ beta = w.norm()
52
+ t_norm = torch.stack(alphas).square().sum() + 2 * sum(b.square() for b in betas)
53
+
54
+ if j == steps - 1 or bool(beta < _BREAKDOWN * t_norm.sqrt()):
55
+ break
56
+
57
+ betas.append(beta)
58
+ qs.append(w / beta)
59
+
60
+ k = len(alphas)
61
+ t = torch.diag(torch.stack(alphas))
62
+
63
+ if k > 1:
64
+ off = torch.stack(betas[: k - 1])
65
+ t = t + torch.diag(off, 1) + torch.diag(off, -1)
66
+
67
+ return torch.stack(qs[:k], dim=1), t
68
+
69
+
70
+ def pinv_root(q: Tensor, t: Tensor) -> Tensor:
71
+ """L = Q U_T D_T^{-1/2} from T = U_T D_T U_Tᵀ, so that L Lᵀ = Q T⁺ Qᵀ.
72
+
73
+ Eigenvalues of T at most eps · k · max are dropped, with eps from T's dtype. A nearly
74
+ singular T then loses columns instead of dividing by a tiny pivot.
75
+ """
76
+
77
+ evals, evecs = torch.linalg.eigh(t)
78
+ keep = evals > torch.finfo(t.dtype).eps * t.shape[0] * evals.max()
79
+
80
+ return q @ evecs[:, keep] / evals[keep].sqrt()
@@ -0,0 +1,31 @@
1
+ """A check, shared by the GP posteriors, that the model's fixed parameters are unchanged.
2
+
3
+ Each posterior's `check_versions` calls it. Having that method makes the posterior a
4
+ `HasVersions`, so `lk.core.mean_outputs`, `lk.predict_outputs` and `lk.sample_outputs` also call it
5
+ before they run a weight-space posterior (`FSPPosterior`). Function-space posteriors
6
+ (`NystromGP`, `VariationalGP`) call it in `at`.
7
+ """
8
+
9
+ from collections.abc import Mapping
10
+
11
+ from laplacekit.core import ModelFn
12
+
13
+
14
+ def check_versions(model: ModelFn, versions: Mapping[str, int], used: str) -> None:
15
+ """Raise `RuntimeError` if a fixed parameter of `model`'s module changed in place.
16
+
17
+ `versions` holds the version counters taken at fit time. `used` names what the posterior
18
+ computed from the old value, for the error message.
19
+ """
20
+
21
+ module = model.module
22
+ live = dict(module.named_parameters()) if module is not None else {}
23
+
24
+ for name, version in versions.items():
25
+ now = live[name]._version if name in live else None
26
+
27
+ if now != version:
28
+ raise RuntimeError(
29
+ f"fixed parameter {name!r} changed in place since the fit (version "
30
+ f"{version}, now {now}); {used}; refit the posterior"
31
+ )