laplacekit-subnet 1.0.0__tar.gz

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,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: laplacekit-subnet
3
+ Version: 1.0.0
4
+ Summary: Subnetwork selection for laplacekit: random, largest magnitude, largest marginal variance
5
+ Author: Agustinus Kristiadi
6
+ Author-email: Agustinus Kristiadi <agustinus@kristia.de>
7
+ License-Expression: MIT
8
+ Requires-Dist: laplacekit>=1.0,<2
9
+ Requires-Python: >=3.11
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "laplacekit-subnet"
3
+ version = "1.0.0"
4
+ description = "Subnetwork selection for laplacekit: random, largest magnitude, largest marginal variance"
5
+ license = "MIT"
6
+ requires-python = ">=3.11"
7
+ dependencies = ["laplacekit>=1.0,<2"]
8
+
9
+ [[project.authors]]
10
+ name = "Agustinus Kristiadi"
11
+ email = "agustinus@kristia.de"
12
+
13
+ [project.entry-points."laplacekit.plugins"]
14
+ laplacekit_subnet = "laplacekit_subnet:plugin"
15
+
16
+ [build-system]
17
+ requires = ["uv_build>=0.13.0,<0.14"]
18
+ build-backend = "uv_build"
19
+
20
+ [tool.uv.sources.laplacekit]
21
+ workspace = true
@@ -0,0 +1,18 @@
1
+ [project]
2
+ name = "laplacekit-subnet"
3
+ version = "1.0.0"
4
+ description = "Subnetwork selection for laplacekit: random, largest magnitude, largest marginal variance"
5
+ authors = [{ name = "Agustinus Kristiadi", email = "agustinus@kristia.de" }]
6
+ license = "MIT"
7
+ requires-python = ">=3.11"
8
+ dependencies = ["laplacekit>=1.0,<2"]
9
+
10
+ [project.entry-points."laplacekit.plugins"]
11
+ laplacekit_subnet = "laplacekit_subnet:plugin"
12
+
13
+ [build-system]
14
+ requires = ["uv_build>=0.13.0,<0.14"]
15
+ build-backend = "uv_build"
16
+
17
+ [tool.uv.sources]
18
+ laplacekit = { workspace = true }
@@ -0,0 +1,33 @@
1
+ """Subnetwork Laplace (Daxberger et al. 2021): the approximation over `n` chosen weight entries.
2
+
3
+ Each strategy returns a `Subset` for `lk.laplace(..., subset=)`, which picks the entries:
4
+
5
+ ```python
6
+ diag = lk.laplace(model, data, likelihood=lik, subset=lk.subsets.all, hessian_approx=lk.DiagGGN())
7
+ post = lk.laplace(
8
+ model, data, likelihood=lik,
9
+ subset=lk.subnet.largest_variance(diag, 51), # or largest_magnitude(51), random(51)
10
+ hessian_approx=lk.DenseGGN(joint=True),
11
+ prior=lk.subnet.rescaled_prior(lam, 51, model),
12
+ )
13
+ ```
14
+
15
+ `random` draws the entries uniformly, `largest_magnitude` takes the largest weights, and
16
+ `largest_variance` the largest marginal variances. Those can come from a diagonal fit, as
17
+ above, or from `swag_variance`. `rescaled_prior` scales the prior precision to the
18
+ subnetwork as Daxberger et al. do. To choose entries by hand, use `lk.subsets.from_mask`
19
+ or `lk.subsets.named` from the core.
20
+
21
+ Code reaches this package as `lk.subnet`, which imports it on first use.
22
+ """
23
+
24
+ import laplacekit as lk
25
+ from laplacekit_subnet.prior import rescaled_prior
26
+ from laplacekit_subnet.selection import largest_magnitude, largest_variance, random
27
+ from laplacekit_subnet.swag import swag_variance
28
+
29
+ __all__ = ["largest_magnitude", "largest_variance", "random", "rescaled_prior", "swag_variance"]
30
+
31
+
32
+ plugin = lk.Plugin(supports=">=1.0,<2")
33
+ """The record behind the `laplacekit.plugins` entry point."""
@@ -0,0 +1,43 @@
1
+ """The prior precision that Daxberger et al. 2021 use for a subnetwork."""
2
+
3
+ import torch
4
+ from torch import Tensor, nn
5
+
6
+ import laplacekit as lk
7
+ from laplacekit_subnet.selection import _check_n
8
+
9
+ __all__ = ["rescaled_prior"]
10
+
11
+
12
+ def rescaled_prior(
13
+ prior_precision: float | Tensor, n: int, model: nn.Module, /
14
+ ) -> lk.priors.Isotropic:
15
+ r"""An isotropic prior over a subnetwork of $S$ entries, with precision $\lambda S / D$.
16
+
17
+ Daxberger et al. 2021 use $\lambda_S = \lambda S / D$ for a subnetwork of $S$ out of
18
+ $D$ entries. It keeps the prior's total variance, $S / \lambda_S = D / \lambda$.
19
+
20
+ Args:
21
+ prior_precision: The full network's prior precision $\lambda$. A float takes the dtype and
22
+ device of `model`'s first parameter.
23
+ n: The subnetwork size $S$, from 1 to $D$.
24
+ model: The network. $D$ counts every parameter entry of `model`, including frozen
25
+ ones.
26
+
27
+ Returns:
28
+ `lk.priors.Isotropic` with precision $\lambda S / D$.
29
+
30
+ Raises:
31
+ ValueError: `n` is not in $[1, D]$.
32
+ """
33
+
34
+ total = sum(p.numel() for p in model.parameters())
35
+ _check_n(n, total, "rescaled_prior")
36
+
37
+ if isinstance(prior_precision, Tensor):
38
+ value = prior_precision
39
+ else:
40
+ first = next(model.parameters())
41
+ value = torch.tensor(prior_precision, dtype=first.dtype, device=first.device)
42
+
43
+ return lk.priors.Isotropic(value * n / total)
File without changes
@@ -0,0 +1,194 @@
1
+ r"""The subnetwork strategies of Daxberger et al. 2021, which choose the `n` weight entries to keep.
2
+
3
+ `random` draws them uniformly, `largest_magnitude` takes the largest $|\theta|$, and
4
+ `largest_variance` takes the largest marginal variances, from a posterior or from given
5
+ variances such as those of `swag_variance`. Each returns a `Subset` that gives a
6
+ `Selection` of the picked entries. Ties at the cut go to the lower index.
7
+ """
8
+
9
+ from collections.abc import Mapping
10
+
11
+ import torch
12
+ from torch import Tensor, nn
13
+
14
+ import laplacekit as lk
15
+ from laplacekit.core import (
16
+ Capabilities,
17
+ ModelFn,
18
+ Params,
19
+ Selection,
20
+ Subset,
21
+ WeightPosterior,
22
+ )
23
+
24
+ __all__ = ["largest_magnitude", "largest_variance", "random"]
25
+
26
+
27
+ def random(
28
+ n: int, /, *, generator: torch.Generator | None = None, subset: Subset = lk.subsets.all
29
+ ) -> Subset:
30
+ """Pick `n` entries of the parameters of `of`, uniformly without replacement.
31
+
32
+ This is laplace-torch's `RandomSubnetMask` (Daxberger et al. 2021), with other random
33
+ draws.
34
+
35
+ Args:
36
+ n: The number of entries to pick, from 1 to the number of entries of the
37
+ parameters of `of`.
38
+ generator: Seeds the draw. `random` draws one seed from it when it is called,
39
+ or from torch's global RNG when `None`, so `torch.manual_seed` makes the pick
40
+ repeatable. The returned `Subset` picks the same entries every time it is
41
+ called, and the `generator=` of the fit does not change them.
42
+ subset: The subset to pick from. It must give whole parameters, not a `Selection`.
43
+
44
+ Returns:
45
+ The `Subset`, which gives a `Selection` of the picked entries. A call raises
46
+ `StructureError` when `of` gives a `Selection` or refuses the model (as
47
+ `lk.subsets.all` does without a module), and `ValueError` when `n` is not in
48
+ $[1, D]$ for the $D$ entries of the parameters of `of`.
49
+ """
50
+
51
+ # Drawn now, so every call of the subset picks the same entries.
52
+ seed = lk.core.spawn_generator(generator).initial_seed()
53
+
54
+ def pick(model: ModelFn, caps: Capabilities, /) -> Selection:
55
+ params = _whole(subset, model, caps, "random")
56
+ size = sum(p.numel() for p in params.values())
57
+ _check_n(n, size, "random")
58
+ scores = torch.rand(size, generator=torch.Generator().manual_seed(seed))
59
+
60
+ return _top(params, scores, n)
61
+
62
+ return pick
63
+
64
+
65
+ def largest_magnitude(n: int, /, *, subset: Subset = lk.subsets.all) -> Subset:
66
+ r"""Pick the `n` entries of the parameters of `of` with the largest $|\theta|$.
67
+
68
+ This is laplace-torch's `LargestMagnitudeSubnetMask` (Daxberger et al. 2021), and it
69
+ picks the same entries: the first `n` of a descending `argsort`. Ties go to the lower
70
+ index.
71
+
72
+ Args:
73
+ n: The number of entries to pick, from 1 to the number of entries of the
74
+ parameters of `of`.
75
+ subset: The subset to pick from. It must give whole parameters, not a `Selection`.
76
+
77
+ Returns:
78
+ The `Subset`, which gives a `Selection` of the picked entries. A call raises
79
+ `StructureError` when `of` gives a `Selection` or refuses the model (as
80
+ `lk.subsets.all` does without a module), and `ValueError` when `n` is not in
81
+ $[1, D]$ for the $D$ entries of the parameters of `of`.
82
+ """
83
+
84
+ def pick(model: ModelFn, caps: Capabilities, /) -> Selection:
85
+ params = _whole(subset, model, caps, "largest_magnitude")
86
+ _check_n(n, sum(p.numel() for p in params.values()), "largest_magnitude")
87
+ scores = torch.cat([p.detach().reshape(-1).abs() for p in params.values()])
88
+
89
+ return _top(params, scores, n)
90
+
91
+ return pick
92
+
93
+
94
+ def largest_variance(source: WeightPosterior | Params, n: int, /) -> Subset:
95
+ """Pick the `n` entries with the largest marginal variance.
96
+
97
+ This covers laplace-torch's `LargestVarianceDiagLaplaceSubnetMask` and
98
+ `LargestVarianceSWAGSubnetMask` (Daxberger et al. 2021). Ties at the cut go to the
99
+ lower index.
100
+
101
+ Args:
102
+ source: A posterior, usually a `Diag` fit over `lk.subsets.all`, or a mapping from
103
+ parameter names to variances, such as `swag_variance` returns. Its names and
104
+ shapes must be those of the module's parameters, so a posterior over a
105
+ `Selection` raises `StructureError` when the subset is called.
106
+ n: The number of entries to pick, from 1 to the number of entries of `source`.
107
+
108
+ Returns:
109
+ The `Subset`, which gives a `Selection` of the picked entries. A call raises
110
+ `StructureError` when the model has no module, a name in `source` is not a
111
+ parameter of the module, or a variance has another shape than its parameter.
112
+
113
+ Raises:
114
+ ValueError: `n` is not in $[1, D]$ for the $D$ entries of `source`.
115
+ StructureError: `source` is a posterior whose `variance` raises it, for
116
+ example because its precision is not positive definite.
117
+ """
118
+
119
+ if isinstance(source, Mapping):
120
+ var = dict(source)
121
+ what = "variances"
122
+ else:
123
+ var = dict(source.variance)
124
+ var = {name: var[name] for name in source.mean}
125
+ what = "posterior's"
126
+
127
+ names = list(var)
128
+ size = sum(var[name].numel() for name in names)
129
+ _check_n(n, size, "largest_variance")
130
+ scores = torch.cat([var[name].detach().reshape(-1) for name in names])
131
+
132
+ def pick(model: ModelFn, caps: Capabilities, /) -> Selection:
133
+ own = dict(_module(model, "largest_variance").named_parameters(remove_duplicate=False))
134
+ missing = [name for name in names if name not in own]
135
+
136
+ if missing:
137
+ raise lk.StructureError(
138
+ f"subnet.largest_variance: the {what} {missing} are not parameters of the "
139
+ "module; give whole parameters, not a Selection"
140
+ )
141
+
142
+ params = {name: own[name] for name in names}
143
+
144
+ for name in names:
145
+ if var[name].shape != params[name].shape:
146
+ raise lk.StructureError(
147
+ f"subnet.largest_variance: the variance of {name!r} has shape "
148
+ f"{tuple(var[name].shape)}, the parameter {tuple(params[name].shape)}"
149
+ )
150
+
151
+ return _top(params, scores, n)
152
+
153
+ return pick
154
+
155
+
156
+ def _module(model: ModelFn, subset: str) -> nn.Module:
157
+ if model.module is None:
158
+ raise lk.StructureError(f"subnet.{subset} needs a module, but ModelFn.module is None")
159
+
160
+ return model.module
161
+
162
+
163
+ def _whole(source: Subset, model: ModelFn, caps: Capabilities, what: str) -> Params:
164
+ params = source(model, caps)
165
+
166
+ if isinstance(params, Selection):
167
+ raise lk.StructureError(
168
+ f"subnet.{what}: subset= must give whole parameters (Params), got a Selection"
169
+ )
170
+
171
+ return params
172
+
173
+
174
+ def _check_n(n: int, size: int, subset: str) -> None:
175
+ if not 1 <= n <= size:
176
+ raise ValueError(f"subnet.{subset}: n must be in [1, {size}], the entry count, got {n}")
177
+
178
+
179
+ def _top(params: Params, scores: Tensor, n: int) -> Selection:
180
+ """The `n` largest scores, flattened over `params` in mapping order, as a `Selection`."""
181
+
182
+ # As laplace-torch picks them, with ties at the cut going to the lower index.
183
+ picked = torch.argsort(scores, descending=True, stable=True)[:n].sort().values
184
+ flat = torch.zeros(scores.numel(), dtype=torch.bool)
185
+ flat[picked.cpu()] = True
186
+
187
+ masks: dict[str, Tensor] = {}
188
+ start = 0
189
+
190
+ for name, p in params.items():
191
+ masks[name] = flat[start : start + p.numel()].reshape(p.shape).to(p.device)
192
+ start += p.numel()
193
+
194
+ return Selection.from_masks(params, masks)
@@ -0,0 +1,156 @@
1
+ """Diagonal SWAG variances (Maddox et al. 2019), which `largest_variance` can pick from."""
2
+
3
+ import copy
4
+ from collections.abc import Callable, Iterable
5
+ from typing import Any
6
+
7
+ import torch
8
+ from torch import Tensor, nn
9
+
10
+ import laplacekit as lk
11
+ import laplacekit.core as core
12
+ from laplacekit.core import (
13
+ Batch,
14
+ Likelihood,
15
+ ModelFn,
16
+ Outputs,
17
+ Params,
18
+ Targets,
19
+ )
20
+
21
+ __all__ = ["swag_variance"]
22
+
23
+
24
+ def swag_variance(
25
+ model: nn.Module,
26
+ data: lk.data.Data | Iterable[Any],
27
+ /,
28
+ *,
29
+ likelihood: Likelihood | None = None,
30
+ loss: Callable[[Outputs, Targets], Tensor] | None = None,
31
+ n_snapshots: int = 40,
32
+ every: int = 1,
33
+ lr: float = 0.01,
34
+ momentum: float = 0.9,
35
+ weight_decay: float = 3e-4,
36
+ min_var: float = 1e-30,
37
+ generator: torch.Generator | None = None,
38
+ ) -> Params:
39
+ r"""Diagonal SWAG variances of `model`'s parameters (Maddox et al. 2019).
40
+
41
+ A deep copy of `model` trains in train mode with SGD for `n_snapshots * every` epochs.
42
+ After every `every`-th epoch, starting with the first, the running mean and mean of
43
+ squares of its parameters take a snapshot. Over the $T$ snapshots
44
+ $\theta_1, \dots, \theta_T$, the variance of each entry is
45
+
46
+ $$\operatorname{Var}[\theta] = \max\Big(\frac{1}{T} \sum_{t=1}^T \theta_t^2 -
47
+ \Big(\frac{1}{T} \sum_{t=1}^T \theta_t\Big)^2, v_{\min}\Big),$$
48
+
49
+ where $v_{\min}$ is `min_var`. This is laplace-torch's `fit_diagonal_swag_var`, with
50
+ the same defaults.
51
+
52
+ Entries clamped at `min_var` tie in `largest_variance`, which breaks ties at the cut
53
+ toward the lower index. laplace-torch's unstable `argsort` may pick other entries
54
+ among them.
55
+
56
+ Args:
57
+ model: The network. It is not changed.
58
+ data: Training data with targets, as an `lk.data.Data` or a re-iterable loader
59
+ that `lk.data.from_loader` wraps.
60
+ likelihood: The likelihood whose batch mean of $-\log p(y \mid f)$ is the loss,
61
+ weighted by the batch's weights when it has them. Give exactly one of
62
+ `likelihood` and `loss`.
63
+ loss: A loss called as `loss(outputs, targets)`.
64
+ n_snapshots: The number of snapshots, at least 1.
65
+ every: The number of epochs between snapshots, at least 1.
66
+ lr: The SGD learning rate.
67
+ momentum: The SGD momentum.
68
+ weight_decay: The SGD weight decay.
69
+ min_var: The lower clamp on each variance.
70
+ generator: Seeds the data. One seed is drawn from it, or from torch's global RNG
71
+ when `None`, so `torch.manual_seed` makes the run repeatable. Every epoch reads
72
+ `data(g)` with the same CPU generator `g` seeded from it, so a shuffling source
73
+ shuffles differently each epoch.
74
+
75
+ Returns:
76
+ A mapping from each parameter name of `model` to its variances, shaped like the
77
+ parameter.
78
+
79
+ Raises:
80
+ ValueError: Not exactly one of `likelihood` and `loss` is given, or `n_snapshots` or
81
+ `every` is below 1. During training, when a batch has no targets, or has
82
+ weights while `loss` is given.
83
+ TypeError: `data` is its own iterator (a generator, for example), or, during
84
+ training, an item is neither a `Batch` nor an `(inputs, targets)` pair.
85
+ StructureError: During training, `likelihood`'s `log_prob` refuses a batch's
86
+ outputs or targets, returns a scalar, or gives a bad mask (see
87
+ `laplacekit.core.log_prob`).
88
+ """
89
+
90
+ if (likelihood is None) == (loss is None):
91
+ raise ValueError("subnet.swag_variance needs exactly one of likelihood= and loss=")
92
+
93
+ for name, value in (("n_snapshots", n_snapshots), ("every", every)):
94
+ if value < 1:
95
+ raise ValueError(f"subnet.swag_variance needs {name} >= 1, got {value}")
96
+
97
+ src = data if isinstance(data, lk.data.Data) else lk.data.from_loader(data)
98
+ data_generator = lk.core.spawn_generator(generator)
99
+
100
+ net = copy.deepcopy(model).train()
101
+ fn = ModelFn.from_module(net)
102
+ params = dict(net.named_parameters())
103
+ optimizer = torch.optim.SGD(
104
+ params.values(), lr=lr, momentum=momentum, weight_decay=weight_decay
105
+ )
106
+
107
+ def objective(batch: Batch) -> Tensor:
108
+ if batch.targets is None:
109
+ raise ValueError("subnet.swag_variance needs data with targets, but a batch has none")
110
+
111
+ f = fn(params, batch.inputs)
112
+
113
+ if loss is not None:
114
+ if batch.weights is not None:
115
+ raise ValueError(
116
+ "subnet.swag_variance: loss= takes no example weights, but a batch has some"
117
+ )
118
+
119
+ return loss(f, batch.targets)
120
+
121
+ assert likelihood is not None
122
+ log_p = core.log_prob(likelihood, f, batch.targets, inputs=batch.inputs)
123
+
124
+ if batch.weights is None:
125
+ return -log_p.mean()
126
+
127
+ return -(batch.weights * log_p).sum() / batch.weights.sum()
128
+
129
+ dtypes = {k: core.stat_dtype(p.dtype) for k, p in params.items()}
130
+ mean = {k: torch.zeros_like(p, dtype=dtypes[k]) for k, p in params.items()}
131
+ sq_mean = {k: torch.zeros_like(p, dtype=dtypes[k]) for k, p in params.items()}
132
+ taken = 0
133
+
134
+ for epoch in range(n_snapshots * every):
135
+ for batch in src(data_generator):
136
+ optimizer.zero_grad()
137
+
138
+ with torch.enable_grad():
139
+ objective(batch).backward()
140
+
141
+ optimizer.step()
142
+
143
+ if epoch % every != 0:
144
+ continue
145
+
146
+ old, new = taken / (taken + 1), 1 / (taken + 1)
147
+
148
+ with torch.no_grad():
149
+ for k, p in params.items():
150
+ theta = p.detach().to(dtypes[k])
151
+ mean[k] = mean[k] * old + theta * new
152
+ sq_mean[k] = sq_mean[k] * old + theta**2 * new
153
+
154
+ taken += 1
155
+
156
+ return {k: torch.clamp(sq_mean[k] - mean[k] ** 2, min=min_var) for k in params}