# laplacekit_subnet

`laplacekit_subnet`

Subnetwork Laplace (Daxberger et al. 2021): the approximation over `n` chosen weight entries.

Each strategy returns a `Subset` for `lk.laplace(..., subset=)`, which picks the entries:

``` python
diag = lk.laplace(model, data, likelihood=lik, subset=lk.subsets.all, hessian_approx=lk.DiagGGN())
post = lk.laplace(
    model, data, likelihood=lik,
    subset=lk.subnet.largest_variance(diag, 51),  # or largest_magnitude(51), random(51)
    hessian_approx=lk.DenseGGN(joint=True),
    prior=lk.subnet.rescaled_prior(lam, 51, model),
)
```

`random` draws the entries uniformly, `largest_magnitude` takes the largest weights, and `largest_variance` the largest marginal variances. Those can come from a diagonal fit, as above, or from `swag_variance`. `rescaled_prior` scales the prior precision to the subnetwork as Daxberger et al. do. To choose entries by hand, use `lk.subsets.from_mask` or `lk.subsets.named` from the core.

Code reaches this package as `lk.subnet`, which imports it on first use.

## Functions

| Name | Description |
|----|----|
| [largest_magnitude](#laplacekit_subnet.largest_magnitude) | Pick the `n` entries of the parameters of `of` with the largest $\|\theta\|$. |
| [largest_variance](#laplacekit_subnet.largest_variance) | Pick the `n` entries with the largest marginal variance. |
| [random](#laplacekit_subnet.random) | Pick `n` entries of the parameters of `of`, uniformly without replacement. |
| [rescaled_prior](#laplacekit_subnet.rescaled_prior) | An isotropic prior over a subnetwork of $S$ entries, with precision $\lambda S / D$. |
| [swag_variance](#laplacekit_subnet.swag_variance) | Diagonal SWAG variances of `model`’s parameters (Maddox et al. 2019). |

### largest_magnitude

``` python
largest_magnitude(n, /, *, subset=lk.subsets.all)
```

Pick the `n` entries of the parameters of `of` with the largest $|\theta|$.

This is laplace-torch’s `LargestMagnitudeSubnetMask` (Daxberger et al. 2021), and it picks the same entries: the first `n` of a descending `argsort`. Ties go to the lower index.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| n | int | The number of entries to pick, from 1 to the number of entries of the parameters of `of`. | *required* |
| subset | Subset | The subset to pick from. It must give whole parameters, not a `Selection`. | `lk.subsets.all` |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | Subset | The `Subset`, which gives a `Selection` of the picked entries. A call raises `StructureError` when `of` gives a `Selection` or refuses the model (as `lk.subsets.all` does without a module), and `ValueError` when `n` is not in $[1, D]$ for the $D$ entries of the parameters of `of`. |

### largest_variance

``` python
largest_variance(source, n, /)
```

Pick the `n` entries with the largest marginal variance.

This covers laplace-torch’s `LargestVarianceDiagLaplaceSubnetMask` and `LargestVarianceSWAGSubnetMask` (Daxberger et al. 2021). Ties at the cut go to the lower index.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| source | WeightPosterior \| Params | A posterior, usually a `Diag` fit over `lk.subsets.all`, or a mapping from parameter names to variances, such as `swag_variance` returns. Its names and shapes must be those of the module’s parameters, so a posterior over a `Selection` raises `StructureError` when the subset is called. | *required* |
| n | int | The number of entries to pick, from 1 to the number of entries of `source`. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | Subset | The `Subset`, which gives a `Selection` of the picked entries. A call raises `StructureError` when the model has no module, a name in `source` is not a parameter of the module, or a variance has another shape than its parameter. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | ValueError | `n` is not in $[1, D]$ for the $D$ entries of `source`. |
|  | StructureError | `source` is a posterior whose `variance` raises it, for example because its precision is not positive definite. |

### random

``` python
random(n, /, *, generator=None, subset=lk.subsets.all)
```

Pick `n` entries of the parameters of `of`, uniformly without replacement.

This is laplace-torch’s `RandomSubnetMask` (Daxberger et al. 2021), with other random draws.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| n | int | The number of entries to pick, from 1 to the number of entries of the parameters of `of`. | *required* |
| generator | torch.Generator \| None | Seeds the draw. `random` draws one seed from it when it is called, or from torch’s global RNG when `None`, so `torch.manual_seed` makes the pick repeatable. The returned `Subset` picks the same entries every time it is called, and the `generator=` of the fit does not change them. | `None` |
| subset | Subset | The subset to pick from. It must give whole parameters, not a `Selection`. | `lk.subsets.all` |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | Subset | The `Subset`, which gives a `Selection` of the picked entries. A call raises `StructureError` when `of` gives a `Selection` or refuses the model (as `lk.subsets.all` does without a module), and `ValueError` when `n` is not in $[1, D]$ for the $D$ entries of the parameters of `of`. |

### rescaled_prior

``` python
rescaled_prior(prior_precision, n, model, /)
```

An isotropic prior over a subnetwork of $S$ entries, with precision $\lambda S / D$.

Daxberger et al. 2021 use $\lambda_S = \lambda S / D$ for a subnetwork of $S$ out of $D$ entries. It keeps the prior’s total variance, $S / \lambda_S = D / \lambda$.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| prior_precision | float \| Tensor | The full network’s prior precision $\lambda$. A float takes the dtype and device of `model`’s first parameter. | *required* |
| n | int | The subnetwork size $S$, from 1 to $D$. | *required* |
| model | nn.Module | The network. $D$ counts every parameter entry of `model`, including frozen ones. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | lk.priors.Isotropic | `lk.priors.Isotropic` with precision $\lambda S / D$. |

#### Raises

| Name | Type       | Description             |
|------|------------|-------------------------|
|      | ValueError | `n` is not in $[1, D]$. |

### swag_variance

``` python
swag_variance(
    model,
    data,
    /,
    *,
    likelihood=None,
    loss=None,
    n_snapshots=40,
    every=1,
    lr=0.01,
    momentum=0.9,
    weight_decay=0.0003,
    min_var=1e-30,
    generator=None,
)
```

Diagonal SWAG variances of `model`’s parameters (Maddox et al. 2019).

A deep copy of `model` trains in train mode with SGD for `n_snapshots * every` epochs. After every `every`-th epoch, starting with the first, the running mean and mean of squares of its parameters take a snapshot. Over the $T$ snapshots $\theta_1, \dots, \theta_T$, the variance of each entry is

$$\operatorname{Var}[\theta] = \max\Big(\frac{1}{T} \sum_{t=1}^T \theta_t^2 -
\Big(\frac{1}{T} \sum_{t=1}^T \theta_t\Big)^2, v_{\min}\Big),$$

where $v_{\min}$ is `min_var`. This is laplace-torch’s `fit_diagonal_swag_var`, with the same defaults.

Entries clamped at `min_var` tie in `largest_variance`, which breaks ties at the cut toward the lower index. laplace-torch’s unstable `argsort` may pick other entries among them.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| model | nn.Module | The network. It is not changed. | *required* |
| data | lk.data.Data \| Iterable\[Any\] | Training data with targets, as an `lk.data.Data` or a re-iterable loader that `lk.data.from_loader` wraps. | *required* |
| likelihood | Likelihood \| None | The likelihood whose batch mean of $-\log p(y \mid f)$ is the loss, weighted by the batch’s weights when it has them. Give exactly one of `likelihood` and `loss`. | `None` |
| loss | Callable\[\[Outputs, Targets\], Tensor\] \| None | A loss called as `loss(outputs, targets)`. | `None` |
| n_snapshots | int | The number of snapshots, at least 1. | `40` |
| every | int | The number of epochs between snapshots, at least 1. | `1` |
| lr | float | The SGD learning rate. | `0.01` |
| momentum | float | The SGD momentum. | `0.9` |
| weight_decay | float | The SGD weight decay. | `0.0003` |
| min_var | float | The lower clamp on each variance. | `1e-30` |
| generator | torch.Generator \| None | Seeds the data. One seed is drawn from it, or from torch’s global RNG when `None`, so `torch.manual_seed` makes the run repeatable. Every epoch reads `data(g)` with the same CPU generator `g` seeded from it, so a shuffling source shuffles differently each epoch. | `None` |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | Params | A mapping from each parameter name of `model` to its variances, shaped like the parameter. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | ValueError | Not exactly one of `likelihood` and `loss` is given, or `n_snapshots` or `every` is below 1. During training, when a batch has no targets, or has weights while `loss` is given. |
|  | TypeError | `data` is its own iterator (a generator, for example), or, during training, an item is neither a `Batch` nor an `(inputs, targets)` pair. |
|  | StructureError | During training, `likelihood`’s `log_prob` refuses a batch’s outputs or targets, returns a scalar, or gives a bad mask (see `laplacekit.core.log_prob`). |
