SWAG (SWA-Gaussian) estimates uncertainty by continuing to train a trained model with SGD, building a Gaussian from the mean and covariance of the weights visited along the way, and averaging predictions over many sets of weights sampled from that distribution. Maddox et al. proposed it in 2019 as a simple approximation to Bayesian inference that also scales to large models.
Bayesian neural networks represent uncertainty by giving the weights a distribution, but they are sensitive to hyperparameters and hard to apply to today's large datasets and networks. Variational inference methods such as Bayes by Backprop are known to be difficult to train for large models such as residual networks.
SWAG extends the idea of the method it builds on, SWA (Stochastic Weight Averaging).
SWA: When SGD continues with a relatively large learning rate, the weights wander around a good solution. Taking the average of those weights (the first moment) as a single solution improves generalization.
SWAG: In addition to the mean, it also collects the spread of the weights (the second moment) and represents the weight distribution as a Gaussian.
As an analogy, it is like recording the footprints of a hiker wandering along a valley floor and mapping not only the center of the valley (the mean) but also in which directions and how far the valley extends (the covariance). The starting point of SWAG is that the path SGD follows contains information about the loss landscape (the shape of the posterior).
Theory
SWAG builds the weight distribution as follows (Algorithm 1 in the paper; left of the figure above).
Start from weights θ0 obtained by ordinary training.
Continue SGD with a relatively large constant learning rate (or a cyclical learning rate).
At regular intervals (every epoch in the paper's CIFAR experiments), record the weights θi and incrementally update the mean of the weights θˉ and the mean of the squared weights θ2.
Append the deviation at that point, θi−θˉi (where θˉi is the mean of the first i weights), as a column of the deviation matrix D^. Only the last K columns of D^ are kept.
When recording is finished, build an approximate posterior over the weights (a Gaussian) from the mean, the variance, and the deviation matrix.
After recording T weights, the mean (the SWA solution) and the per-weight variance are given by the following (Sections 3.2–3.3 of the paper; squares are element-wise).
Using only Σdiag, i.e. N(θSWA,Σdiag), is called SWAG-Diagonal. Since this alone cannot represent correlations between weights, SWAG adds a low-rank covariance built from the deviation matrix (Section 3.4 of the paper).
K is the rank of the low-rank approximation, and K=20 in all of the paper's experiments. The factor 21 is there because both the diagonal term and the low-rank term contain the variance of the weights, so using them as is would count the variance twice.
If the network has d weights, weights can be sampled with the following expression without forming the d×d covariance matrix (Eq. (1) in the paper).
The second term costs O(d) and the third O(Kd). Only θSWA, θ2, and the K deviation vectors need to be stored, and they do not have to reside on the GPU.
Computing Predictions and Uncertainty
Predictions are obtained by approximating Bayesian model averaging with Monte Carlo.
Sample one set of weights from the approximate posterior q(θ) (Eq. (1) above).
For models that use batch normalization, pass the training data through the network with the sampled weights to update the batch normalization statistics.
Run a forward pass on the test input with those weights.
Repeat steps 1–3 S times and average the predicted probabilities.
p(y∗∣D,x∗)≈S1i=1∑Sp(y∗∣θ~i,x∗),θ~i∼q(θ)
The paper uses S=30 in its experiments. For WideResNet on CIFAR-100, about 3 samples were enough to match the NLL of SWA, and about 30 were needed for accuracy to stabilize. Quantities such as the entropy of the predicted probabilities serve as the uncertainty.
The batch normalization statistics must be updated every time weights are sampled, because the mean weights and the sampled weights do not match the statistics from training. In the paper, skipping this update made the NLL much worse (Appendix D.4 of the paper). Inference therefore costs S statistic updates in addition to S forward passes. On ImageNet, the statistics are updated with a random 10% of the training data.
On the prior: SWAG does not place an explicit prior, but the paper explains that training with SGD and weight decay (L2 regularization) corresponds to a Gaussian prior on the weights. Any ordinary model trained with SGD and weight decay can therefore use SWAG without changing how it is trained.
Why the SGD Trajectory Can Approximate the Posterior
SGD with a constant learning rate does not converge to a single point but wanders around a good solution. Theoretical work (by Mandt et al. and others) had shown that under certain conditions the stationary distribution of the SGD iterates is close to the posterior. The paper, however, also confirms that those assumptions (such as convexity) do not hold for deep networks.
The paper therefore examined the actual loss landscape. For PreResNet-164 on CIFAR-100, it measured the loss when moving away from θSWA along the principal directions (eigenvectors) of the SWAG covariance and found the following (Figure 1 in the paper).
The larger the SWAG variance in a direction, the wider the loss valley in that direction. The SGD trajectory contains information about the shape of the posterior.
In the plane spanned by the top two eigenvectors, the loss contours aligned well with the SWAG ellipses.
SWAG-Diagonal had almost no variance in these directions.
What SWAG captures is the shape within the low-dimensional subspace that SGD wandered through. The paper itself notes that this subspace is very small compared with the full dimension of the weight space and that SWAG is expected to underestimate the variance in random directions.
Findings from the Paper's Experiments
The paper evaluated SWAG on image classification on CIFAR-10/100 and ImageNet, on transfer from a model trained on CIFAR-10 to STL-10, and on language modeling. On CIFAR, models were trained for 300 epochs, and weights were collected every epoch from epoch 160 onward.
Test NLL (lower is better; Tables 6–8 in the paper's appendix; CIFAR values are averages over 3 runs)
("–" marks values that are absent from the paper's tables or whose column could not be determined. The paper states that MC dropout could not be trained successfully on PreResNet-164 with any dropout probability. See also VGG and ResNet.)
The table shows the following.
SWAG had the lowest NLL in most settings. The paper concludes that SWAG and SWAG-Diagonal matched or outperformed the other methods on every task, with SWAG the best overall. There are exceptions, however: for WideResNet28x10 on CIFAR-10, for example, SWA + temperature scaling (0.1064) is lower than SWAG (0.1122).
SWA + temperature scaling is a strong baseline. It requires validation data to set the temperature, though, and its benefit shrank on data from a different distribution than training (the transfer to STL-10).
Accuracy is about the same as SWA. For ResNet-152 on ImageNet, for example, SGD reached 78.39%, SWA 78.92%, and SWAG 79.08%.
Comparison with deep ensembles: For PreResNet-164 on CIFAR-100, an ensemble of 3 independently trained SGD models reached a high accuracy of 82.1%, but its NLL of 0.6922 was worse than a single SWAG model (0.6595). An ensemble of 5 reached an NLL of 0.6478, about the same as SWAG, but at 5 times SWAG's training compute. Ensembling 3 independently trained SWAG models gave an NLL of 0.6178.
Language modeling (3-layer LSTM): SWAG further reduced test perplexity, from 56.7 with SWA to 56.26 on Penn Treebank and from 65.0 with SWA to 64.1 on WikiText-2.
Practical Caveats
Keep the following points in mind when using SWAG.
The learning rate changes the size of the variance. The SWAG covariance is determined by the SGD learning rate and momentum. The paper recommends choosing the learning rate by the NLL on validation data. It also experimented with scaling the covariance at sampling time and reports that 0.5 worked best (this corresponds to the 21 in the formula).
Behavior with optimizers other than SGD has not been verified. The paper leaves use with Adam and other optimizers to future work.
Inference costs more than S times as much. Each sampled set of weights requires a forward pass and an update of the batch normalization statistics.
Memory for K+2 copies of the weights is required. These are θSWA, θ2, and the K deviations. They can be kept on the CPU.
The SWAG distribution only covers the region SGD wandered through (within a single valley). The analysis in Figure 1 of the paper is also within a single valley and does not include solutions in other valleys. To make use of solutions from different valleys, combine several independently trained SWAG models, as in the paper's experiments.
Comparison with Other Methods
Other methods for estimating uncertainty compare as follows.
Method
Training
Inference
Characteristics
SWAG
After ordinary training, continue SGD and collect the mean and covariance of the weights
Sample S sets of weights, update statistics, and run forward passes
Does not change how the model is trained; also represents correlations between weights (low-rank)
SWAG-Diagonal
Same as SWAG (without the deviation matrix)
Same as SWAG
Less memory; cannot represent correlations, and NLL is often worse than SWAG
Requires validation data; less effective under distribution shift
Rules of thumb for choosing:
If a model trained with SGD and weight decay already exists and retraining many times is not an option, SWAG is a good fit. The only extra training is a short continuation of SGD.
To trust the probabilities even on data from a different distribution than training, SWAG gave better results than temperature scaling (the paper's transfer to STL-10).
If compute allows, training several SWAG models independently and combining them improves results further.
PyTorch example
▶Show code
python
import copy
import torch
import torch.nn as nn
from torch.optim.swa_utils import update_bn
"""
A small implementation of SWAG (Maddox et al., 2019)
Continue SGD from a trained model and collect the first and second moments of the weights and the deviations every epoch (Algorithm 1)
"""
K = 20 # number of columns of the deviation matrix (rank of the low-rank part). K = 20 in all of the paper's experiments
S = 30 # number of weight sets sampled at inference
def flatten(model):
return torch.cat([p.detach().flatten() for p in model.parameters()])
def assign(model, vec):
i = 0
for p in model.parameters():
n = p.numel()
p.data.copy_(vec[i:i + n].view_as(p))
i += n
class SWAG:
def __init__(self, model):
self.model = model
self.n = 0
self.mean = torch.zeros_like(flatten(model)) # θ̄ (the SWA mean)
self.sq_mean = torch.zeros_like(self.mean) # mean of θ²
self.dev = [] # columns of the deviation matrix D̂ (last K)
def collect(self):
"""Call at regular intervals during SGD (e.g., every epoch)"""
theta = flatten(self.model)
self.mean = (self.n * self.mean + theta) / (self.n + 1)
self.sq_mean = (self.n * self.sq_mean + theta ** 2) / (self.n + 1)
self.dev.append(theta - self.mean) # θ_i − θ̄_i
if len(self.dev) > K:
self.dev.pop(0)
self.n += 1
def sample(self, scale=0.5):
"""Eq. (1): θ~ = θ_SWA + √scale·Σ_diag^{1/2} z1 + √scale·D̂ z2 / √(K−1) (scale = 1/2 gives the paper's formula)"""
var = torch.clamp(self.sq_mean - self.mean ** 2, min=1e-30)
z1 = torch.randn_like(self.mean)
D = torch.stack(self.dev, dim=1) # [d, K]
z2 = torch.randn(D.shape[1])
k = D.shape[1]
return self.mean + (scale ** 0.5) * var.sqrt() * z1 + (scale ** 0.5) * (D @ z2) / (max(k - 1, 1) ** 0.5)
def train_swag(model, train_loader, epochs=40, lr=0.05, weight_decay=5e-4):
"""Continue SGD from the trained model and collect the weights every epoch"""
optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9, weight_decay=weight_decay)
criterion = nn.CrossEntropyLoss()
swag = SWAG(model)
for _ in range(epochs):
model.train()
for x, y in train_loader:
optimizer.zero_grad()
criterion(model(x), y).backward()
optimizer.step()
swag.collect()
return swag
@torch.no_grad()
def swag_predict(swag, train_loader, x, n_samples=S):
"""Sample weights, update the batch normalization statistics, predict, and average the probabilities"""
net = copy.deepcopy(swag.model)
probs = 0
for _ in range(n_samples):
assign(net, swag.sample())
update_bn(train_loader, net) # recompute the batch normalization statistics with the sampled weights
net.eval()
probs = probs + torch.softmax(net(x), dim=1) / n_samples
return probs
# Usage (model has been trained with SGD and weight decay)
# swag = train_swag(model, train_loader)
# probs = swag_predict(swag, train_loader, x_test)
FAQ
Q. What is the difference between SWA and SWAG?
A.
SWA uses the mean of the weights visited by SGD, θSWA, as a single solution and predicts with one forward pass. SWAG additionally collects the variance and the deviation matrix to build a Gaussian, samples many sets of weights from it, and averages the predictions. In the paper's experiments, accuracy was about the same, while SWAG gave better NLL and calibration.
Q. How should the number of deviation-matrix columns $K$ and the number of sampled weight sets $S$ be chosen?
A.
The paper uses K=20 and S=30 in all of its experiments. For WideResNet on CIFAR-100, about 3 samples matched the NLL of SWA, and accuracy stabilized at about 30. The paper recommends choosing S based on validation data and the available compute.
Q. Compared with [temperature scaling](/uncertainty/temperature-scaling), which should be used?
A.
On data from the same distribution, SWA combined with temperature scaling can perform nearly as well as SWAG. Temperature scaling needs only one inference pass but requires validation data to set the temperature. In the paper, SWAG gave clearly better results when the data distribution shifted, such as training on CIFAR-10 and testing on STL-10.