pytorch-lightning icon indicating copy to clipboard operation
pytorch-lightning copied to clipboard

Add stochastic weight averaging

Open williamFalcon opened this issue 6 years ago • 20 comments

Looks like we need to keep two copies of the model. Let $m_r$ define the root model and $m_c$ the current model. Then at the end of each epoch $n$, we update the weights of $m_r$ using a weighted average:

image

Anyone interested in implementing?

maybe enable as a callback? not sure this needs a flag?

@PyTorchLightning/core-contributors

williamFalcon avatar May 19 '20 17:05 williamFalcon

Isnt SWA already in PyTorch master? https://github.com/pytorch/pytorch/pull/35032

KeAWang avatar May 26 '20 15:05 KeAWang

So using torchcontrib.optim.SWA is relatively simple. Just wrap it around your base optimizer(s) in the configure_optimizers method.

The only tricky part would be that opt.swap_swa_sgd() needs to be called at training_epoch_end. What is the ideal way to do this? We should have access to optimizers using self.trainer.optimizers ... at which point, one would need to iterate the list and check if any of them are an instance of torchcontrib.optim.SWA and invoke opt.swap_swa_sgd() on them.

def configure_optimizers(self):
    optimizer = AdamW(self.parameters(), lr=1e-3, weight_decay=0.001)
    optimizer = torchcontrib.optim.SWA(optimizer, swa_start=10, swa_freq=5)
    return [optimizer]

def training_epoch_end(self, outputs):
    for opt in self.trainer.optimizers:
        if not type(opt) is torchcontrib.optim.SWA:
            continue
        opt.swap_swa_sgd()
    return {}

authman avatar May 29 '20 11:05 authman

I have the entirety of "Stochastic Weight Averaging Gaussian" or "SWAG" implemented in Lightning (the extended version of SWA): https://arxiv.org/abs/1902.02476. It's a different approach than just switching optimizers though. I'm not sure if it's more pythonic or less.

It records the average parameters, the average squared parameters, along with a a small number of recent weights to estimate the covariance of the weight posterior mode the optimizer currently sits in.

I'm not sure the best way of implementing it, but right now, I have a second "SWAG" model that inherits the first model (since SWA requires a pretrained model), and does SGD. I feel like this is the way to do it because the learning schedules are completely different, and you only do SWA after you have tuned your original model; but at the same time, you do want the same model, dataloader, augmentation, loss function, etc. So inheritance seems a decent way of implementing it: maybe inherit pl.LightningModule for the regular one, then inherit from that & a pl.SWAGLightningModule for the averaged one.

My current workflow, which should probably be refactored:

  • First model is a pl.LightningModule that you train normally. Call it MyModel
  • Second model is the SWAG variation, that inherits MyModel. It doesn't have it's own initialization function. Call it MyModelSWAG
  • You initialize the second model with model = MyModelSWAG.load_from_checkpoint(checkpoint_path).
  • You then call model.init_swag(swag_hparams) to record the SWAG hyperparameters.
  • You then train this model with a new Trainer.

Then, I add these functions:

  • Common:
    • Model function flat_state_dict converts the current model's state dict to a 1D vector and returns it.
    • Model function load_tensor_as_state_dict is the opposite: it takes a 1D vector and uses it to set the model's state dict.
    • Model function swag_aggregate_model uses flat_state_dict to update the average parameters and square parameters, and records the current weights, and then removes 1 set of old weights if you have greater than K number recorded (part of SWAG is they store several old weights to estimate Gaussian covariance at the end).
    • I write a swa_forward to load the average parameters with load_tensor_as_state_dict, call forward on the average parameters, and then load back the current parameters.
    • I write a swag_forward to sample parameters using the average weight, average square weight, and an estimate of the Gaussian covariance. It then uses load_tensor_as_state_dict on the parameters, calls forward then loads back the current parameters.
  • Functions the user needs to write:
    • I rewrite configure_optimizers to use a constant learning rate schedule, and SGD. This should load the parameters entered in init_swag.
    • I rewrite my version of validation_step to use the average parameters for validation loss: it calls swag_aggregate_model, and then measures the validation loss using swa_forward. But the user should write this themselves to record different statistics here, or if they'd like to record the validation loss of the current weights.

In practice, one could use swa_forward to use the average parameters for prediction, or swag_forward to randomly sample weights and make a prediction using that sample.

Let me know what you think of this structure and if I should share some code for a lightning implementation.

Cheers, Miles

MilesCranmer avatar Jul 12 '20 05:07 MilesCranmer

I think for now, we could go and add this to bolts.

justusperillieux avatar Jul 13 '20 19:07 justusperillieux

hi @MilesCranmer this is really cool! Mind waiting a few weeks since we need to wrap up the v1 before adding this? the main reason is that we are focused on improving the stability of PL and don't want to add big features that might affect this.

williamFalcon avatar Jul 23 '20 10:07 williamFalcon

Sure, no problem!

And happy to add to bolts instead if preferred. I'm curious: when does an algorithm move from bolts to the main framework? Though generally applicable to any NN, I don't think SWA/SWAG/MultiSWAG have found popular use yet. But at least SWA (=Stochastic Weight Averaging) seems like such a simple yet powerful strategy - you just average the weights in a final segment of training and get better loss - that maybe it would be good to eventually embed in the main trainer as a flagged option.

MilesCranmer avatar Jul 25 '20 02:07 MilesCranmer

Hi! Did anyone managed to make SWA work with lightning?

We tried to move our training from custom code to Pytorch lightning and SWA causes problems in migration. We use torchcontrib.optim.SWA implementation. I first wrapped my optimizer in cofigure_optimizers:

base_optimizer = AdamW(param_groups, ...)
optimizer = SWA(base_optimizer)

And then I swap_swa_sgd before and after validation cycles:

    def on_pre_performance_check(self) -> None:
        if self.current_epoch > 0:
            for opt in self.trainer.optimizers:
                if isinstance(opt, SWA):
                    opt.update_swa()
                    opt.swap_swa_sgd()
                    opt.bn_update(self.train_dataloader(), self.model, device=self.device)

    def on_post_performance_check(self) -> None:
        if self.current_epoch > 0:
            for opt in self.trainer.optimizers:
                if isinstance(opt, SWA):
                    opt.swap_swa_sgd()

zerogerc avatar Aug 13 '20 16:08 zerogerc

Any update on the issue? What's the most idiomatic way to approach this?

sakvaua avatar Oct 07 '20 09:10 sakvaua

This issue has been automatically marked as stale because it hasn't had any recent activity. This issue will be closed in 7 days if no further activity occurs. Thank you for your contributions, Pytorch Lightning Team!

stale[bot] avatar Nov 06 '20 15:11 stale[bot]

This issue has been automatically marked as stale because it hasn't had any recent activity. This issue will be closed in 7 days if no further activity occurs. Thank you for your contributions, Pytorch Lightning Team!

stale[bot] avatar Dec 09 '20 05:12 stale[bot]

for the record - https://pytorch.org/blog/pytorch-1.6-now-includes-stochastic-weight-averaging/

Borda avatar Dec 10 '20 09:12 Borda

FYI, here is my implementation of MultiSWAG: https://github.com/MilesCranmer/bnn_chaos_model/blob/master/spock_reg_model.py.

This is not in a form where one can plug-and-play the model into any code, but I thought the function implementations might be useful for some.

The main functionality is as follows:

Set self.w_avg=None, self.w2_avg=None, self.pre_D=None at initialization. These will contain the average, average squared, and array of some recorded positions, respectively. self.pre_D is used to compute the covariance matrix for a Gaussian. But all you need for SWA is self.w_avg, the others are for full-blown SWAG.

Also set self.n_models=0 at init.

Main hyperparameters: self.K=20 (max samples to record in self.pre_D) and self.c=2 (number steps or epochs before recording another sample in self.pre_D).

def aggregate_model(self):
    """Aggregate parameters for SWA/SWAG"""

    cur_w = self.flatten()
    cur_w2 = cur_w ** 2
    with torch.no_grad():
        if self.w_avg is None:
            self.w_avg = cur_w
            self.w2_avg = cur_w2
        else:
            self.w_avg = (self.w_avg * self.n_models + cur_w) / (self.n_models + 1)
            self.w2_avg = (self.w2_avg * self.n_models + cur_w2) / (self.n_models + 1)

        if self.pre_D is None:
            self.pre_D = cur_w.clone()[:, None]
        elif self.current_epoch % self.c == 0:
            #Record weights, measure discrepancy with average later
            self.pre_D = torch.cat((self.pre_D, cur_w[:, None]), dim=1)
            if self.pre_D.shape[1] > self.K:
                self.pre_D = self.pre_D[:, 1:]
                
    self.n_models += 1

self.w_avg is all you need for SWA. The other parameters are for the full MultiSWAG (if curious about this algorithm, I give a high-level explanation it a bit on my blog here in the "Parametrization" section). This takes longer to train (it's an ensemble model), but I found the performance improves further beyond what SWA gives you.

The function self.flatten() just turns the parameters into a 1D array, and is defined as follows:

def flatten(self):
    """Convert state dict into a vector"""
    ps = self.state_dict()
    p_vec = None
    for key in ps.keys():
        p = ps[key]
        if p_vec is None:
            p_vec = p.reshape(-1)
        else:
            p_vec = torch.cat((p_vec, p.reshape(-1)))
    return p_vec

The opposite of this is self.load(p_vec), defined as follows:

def load(self, p_vec):
    """Load a vector into the state dict"""
    cur_state_dict = self.state_dict()
    new_state_dict = OrderedDict()
    i = 0
    for key in cur_state_dict.keys():
        old_p = cur_state_dict[key]
        size = old_p.numel()
        shape = old_p.shape
        new_p = p_vec[i:i+size].reshape(*shape)
        new_state_dict[key] = new_p
        i += size

    self.load_state_dict(new_state_dict)

Thus, you can load the average parameters into the model via self.load(self.w_avg).

Now, I call the aggregation function inside my validation_epoch_end function once the 'swa_start' point of training has been reached (though you could also choose to aggregate every batch), like so:

def validation_epoch_end(self, outputs):
    ...
    if self.global_step > self.hparams['swa_start']:
        self.aggregate_model()
    ...

During my validation I also log the loss of the average parameters, like so:

tmp = self.flatten()
self.load(self.w_avg)
swa_loss = self.lossfnc(X_sample, y_sample, noisy_val=self.hparams['noisy_val'])/self.test_len
self.load(tmp)

(this loads the average parameters, then reloads the current step).

Now, if you also want to do the full SWAG, things get a bit more complicated in terms of the parameters to load. Here is my implementation to sample weights from the recorded average and low-rank covariance (in self.w2_avg and self.pre_D):

def sample_weights(self, scale=1):
    """Sample weights using SWAG:
    - w ~ N(avg_w, 1/2 * sigma + D . D^T/2(K-1))
        - This can be done with the following matrices:
            - z_1 ~ N(0, I_d); d the number of parameters
            - z_2 ~ N(0, I_K)
        - Then, compute:
        - w = avg_w + (1/sqrt(2)) * sigma^(1/2) . z_1 + D . z_2 / sqrt(2(K-1))
    """
    with torch.no_grad():
        avg_w = self.w_avg #[K]
        avg_w2 = self.w2_avg #[K]
        D = self.pre_D - avg_w[:, None]#[d, K]
        d = avg_w.shape[0]
        K = self.K
        z_1 = torch.randn((1, d), device=self.device)
        z_2 = torch.randn((K, 1), device=self.device)
        sigma = torch.abs(torch.diag(avg_w2 - avg_w**2))

        w = avg_w[None] + scale * (1.0/np.sqrt(2.0)) * z_1 @ sigma**0.5
        w += scale * (D @ z_2).T / np.sqrt(2*(K-1))
        w = w[0]

    self.load(w)

You usually set scale as a hyperparameter (how far away from the average weights you want to sample; so scale=0.0 => SWA). But scale=0.5 is what the authors used in the paper based on theory considerations, and I found this also works well in my paper.

I have a separate forward_swag function that samples new weights before running forward - averaging over multiple calls gives you the ensemble model (and multiple different models gives MultiSWAG):

def forward_swag(self, x, scale=0.5):
    # Sample using SWAG using recorded model moments
    self.sample_weights(scale=scale)
    ... # Call your forward function, etc

Then, for the scheduler, I use MultiStepLR and start my SWAG learning rate (bit higher than regular learning rate, so it walks around the weight minimum a bit) like so:

scheduler = torch.optim.lr_scheduler.MultiStepLR(opt, [self.swa_params['swa_start']], self.swa_params['swa_recording_lr_factor'])

Basically, it trains until it's in the minimum (you assume this is at swa_start), then keeps randomly walking for a bit while aggregating the average parameters.

Sorry for the long post - let me know if you have any questions. Cheers, Miles

MilesCranmer avatar Jan 14 '21 06:01 MilesCranmer

@MilesCranmer mind open a draft PR so we can interate on your proposal? =)

Borda avatar Jan 14 '21 08:01 Borda

@MilesCranmer still interested in sending multi-SWA or prefer to wait till the first one lands?

Borda avatar Feb 02 '21 09:02 Borda

Hey @Borda, sorry for the late response! The PR looks great for SWA! This looks nice a very clean way of doing it :) I will add comments to the PR about potentially having SWAG too.

Cheers, Miles

MilesCranmer avatar Feb 02 '21 21:02 MilesCranmer

Can't wait to use SWAG right now .

heartInsert avatar Feb 08 '21 16:02 heartInsert

@MilesCranmer I'd also be interested in SWAG

turian avatar Apr 22 '21 20:04 turian

It got introduced in Lightning 1.2

Trainer(stochastic_weight_avg=True)

awaelchli avatar Apr 22 '21 20:04 awaelchli

What's involved with getting this working for multiple optimizers (up to 3)?

bmahlbrand avatar Jul 10 '21 18:07 bmahlbrand

What's involved with getting this working for multiple optimizers (up to 3)?

Would need to add a flag to indicate which optimizers to wrap and update all the logic in the callback accordingly.

This is something contributors could try resolving!

carmocca avatar Jul 12 '21 12:07 carmocca