# Subnetworks

A full covariance over every weight is too big for most networks, but a full covariance over a few hundred of them is cheap. A subnetwork Laplace picks those weights and keeps the rest fixed. Let’s try it on the classifier of the [classification page](../quickstart/classification.llms.md).

> **NOTE:**
>
> This page uses the [`laplacekit-subnet`](https://github.com/laplacekit/laplacekit/tree/main/plugins/subnet) plugin. Install it with:
>
> ``` bash
> pip install "laplacekit[subnet]"
> ```

``` python
import torch
from sklearn.datasets import make_blobs
from torch import nn

import laplacekit as lk

x_np, y_np = make_blobs(
    n_samples=500,
    centers=4,
    cluster_std=1.2,
    center_box=(-10, 10),
    random_state=37,
)
x, y = torch.tensor(x_np, dtype=torch.float32), torch.tensor(y_np)
data = [(x, y)]

torch.manual_seed(99999)
model = nn.Sequential(
    nn.Linear(2, 20),
    nn.BatchNorm1d(20),
    nn.ReLU(),
    nn.Linear(20, 20),
    nn.BatchNorm1d(20),
    nn.ReLU(),
    nn.Linear(20, 4, bias=False),
)
opt = torch.optim.SGD(
    model.parameters(), lr=1e-3, momentum=0.9, weight_decay=5e-4
)

for _ in range(5000):
    opt.zero_grad()
    nn.functional.cross_entropy(model(x), y).backward()
    opt.step()

model.eval()
```

    Sequential(
      (0): Linear(in_features=2, out_features=20, bias=True)
      (1): BatchNorm1d(20, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
      (2): ReLU()
      (3): Linear(in_features=20, out_features=20, bias=True)
      (4): BatchNorm1d(20, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
      (5): ReLU()
      (6): Linear(in_features=20, out_features=4, bias=False)
    )

The strategies live in `lk.subnet`. `lk.subnet.largest_magnitude(100)` takes the 100 weights with the largest $|\theta|$, out of 640. `DenseGGN(joint=True)` gives them one dense covariance, across layers.

``` python
post_mag = lk.laplace(
    model,
    data,
    likelihood=lk.Categorical(),
    subset=lk.subnet.largest_magnitude(100),
    hessian_approx=lk.DenseGGN(joint=True),
)
print(post_mag)
```

    LaplacePosterior(
      subset         = largest_magnitude {"0.weight[idx]": (23,), "0.bias[idx]": (8,), "1.weight[idx]": (20,), "4.weight[idx]": (20,), "6.weight[idx]": (29,)}
      hessian_approx = DenseGGN(joint=True)
      curvature      = Joint[Dense] (4 blocks, 100 parameters)
      prior          = Isotropic(prior_precision=0.385)
      likelihood     = Categorical()
      hyper_tuner    = MarginalLikelihood()
      n_data         = 500
    )

`lk.subnet.largest_variance(diag, 100)` takes the 100 weights with the largest marginal variance under a cheaper posterior, usually a `Diag` over all weights. It also takes the SWAG variances of `lk.subnet.swag_variance(model, data, likelihood=lk.Categorical())`, which skip weights that the data never move. [Subnetworks](../examples/subnetwork.llms.md) compares the two.

``` python
diag = lk.laplace(
    model,
    data,
    likelihood=lk.Categorical(),
    subset=lk.subsets.all,
    hessian_approx=lk.DiagGGN(),
)
post_var = lk.laplace(
    model,
    data,
    likelihood=lk.Categorical(),
    subset=lk.subnet.largest_variance(diag, 100),
    hessian_approx=lk.DenseGGN(joint=True),
)
print(post_var)
```

    LaplacePosterior(
      subset         = largest_variance {"3.weight[idx]": (98,), "4.weight[idx]": (1,), "4.bias[idx]": (1,)}
      hessian_approx = DenseGGN(joint=True)
      curvature      = Joint[Dense] (2 blocks, 100 parameters)
      prior          = Isotropic(prior_precision=0.607)
      likelihood     = Categorical()
      hyper_tuner    = MarginalLikelihood()
      n_data         = 500
    )

The two pick different weights. By magnitude, the 100 come from the first and last layers and from the scales of both batch norms. By variance, 98 of them are in the middle layer, `3.weight`.

Both posteriors predict like any other. We look at the four corners of $[-15, 15]^2$, far from the data. The MAP network puts probability 1.0 on one class in three of them. The subnetworks stay sure in the first corner (0.98 and 0.97), and drop to between 0.30 and 0.66 in the other three.

``` python
far = torch.tensor([[-15.0, 15.0], [15.0, -15.0], [15.0, 15.0], [-15.0, -15.0]])

with torch.no_grad():
    print("MAP      ", model(far).softmax(-1).max(-1).values)

print("magnitude", lk.predict(post_mag, far).probs.max(-1).values)
print("variance ", lk.predict(post_var, far).probs.max(-1).values)
```

    MAP       tensor([1.0000, 1.0000, 1.0000, 0.7796])
    magnitude tensor([0.9801, 0.6273, 0.5686, 0.3562])
    variance  tensor([0.9737, 0.4197, 0.6550, 0.3034])

There are three more ways to choose, one line each. `lk.subnet.random(n)` draws $n$ weights at random, `lk.subsets.from_mask` takes a boolean mask per parameter, and `lk.subsets.named` takes whole parameters by name. The mask below keeps 20 weights of the last layer, and the two names hold 500.

``` python
mask = torch.zeros(4, 20, dtype=torch.bool)
mask[:, :5] = True  # the weights from the first five features

subnets = [
    lk.subnet.random(100),
    lk.subsets.from_mask({"6.weight": mask}),
    lk.subsets.named("3.*", "6.*"),
]

for subnet in subnets:
    post = lk.laplace(
        model,
        data,
        likelihood=lk.Categorical(),
        subset=subnet,
        hessian_approx=lk.DenseGGN(joint=True),
    )
    print(sum(m.numel() for m in post.mean.values()), "weights")
```

    100 weights
    20 weights
    500 weights

Note that KFAC reaches whole weight matrices through module hooks. So it refuses a subnetwork before it reads any data:

``` python
try:
    lk.laplace(
        model,
        data,
        likelihood=lk.Categorical(),
        subset=lk.subnet.largest_magnitude(100),
        hessian_approx=lk.KFAC(),
    )
except lk.CapabilityError as e:
    print("CapabilityError:", e)
```

    CapabilityError: KFAC() needs module hooks on the module's own parameters, but blocks ['0', '1', '4', '6'] hold index selections (Selection); use DiagGGN, DenseGGN or LowRankGGN

> **NOTE:**
>
> Split the weights into the chosen ones $\theta_S$ and the rest $\theta_R$. Subnetwork Laplace (Daxberger et al., 2021) keeps $\theta_R$ fixed at the MAP and puts a Gaussian on $\theta_S$ alone,
>
> $$p(\theta_S \mid \mathcal{D}) \approx \mathcal{N}\big(\theta_S \mid \theta_{S*}, (\lambda I + N G_{SS})^{-1}\big) ,$$
>
> where $G_{SS}$ is the block of the generalized Gauss-Newton matrix for the chosen entries. For $|S| = 100$, that is a $100 \times 100$ matrix, whatever the size of the network. The predictive linearizes the network in $\theta_S$ only. Choosing by variance follows the paper. It keeps the entries whose marginal variance, under a diagonal Laplace over all weights, is largest.

The full tutorial: [Subnetworks](../examples/subnetwork.llms.md)
