2021-02-04 18:36:54 +00:00
|
|
|
# Copyright The PyTorch Lightning team.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2021-04-08 07:29:06 +00:00
|
|
|
from collections import OrderedDict
|
|
|
|
|
2021-02-04 18:36:54 +00:00
|
|
|
import pytest
|
|
|
|
import torch
|
|
|
|
from torch import nn
|
2021-04-30 15:14:43 +00:00
|
|
|
from torch.optim import Optimizer, SGD
|
2021-02-04 18:36:54 +00:00
|
|
|
from torch.utils.data import DataLoader
|
|
|
|
|
|
|
|
from pytorch_lightning import LightningModule, seed_everything, Trainer
|
2021-04-30 15:14:43 +00:00
|
|
|
from pytorch_lightning.callbacks import BackboneFinetuning, BaseFinetuning, ModelCheckpoint
|
2022-03-10 16:01:08 +00:00
|
|
|
from pytorch_lightning.utilities.imports import _TORCH_GREATER_EQUAL_1_11
|
2021-02-09 10:10:52 +00:00
|
|
|
from tests.helpers import BoringModel, RandomDataset
|
2021-02-04 18:36:54 +00:00
|
|
|
|
|
|
|
|
2021-04-30 15:14:43 +00:00
|
|
|
class TestBackboneFinetuningCallback(BackboneFinetuning):
|
2021-06-21 15:08:07 +00:00
|
|
|
def on_train_epoch_start(self, trainer, pl_module):
|
|
|
|
super().on_train_epoch_start(trainer, pl_module)
|
2021-04-30 15:14:43 +00:00
|
|
|
epoch = trainer.current_epoch
|
|
|
|
if self.unfreeze_backbone_at_epoch <= epoch:
|
|
|
|
optimizer = trainer.optimizers[0]
|
2021-07-26 11:37:35 +00:00
|
|
|
current_lr = optimizer.param_groups[0]["lr"]
|
2021-04-30 15:14:43 +00:00
|
|
|
backbone_lr = self.previous_backbone_lr
|
|
|
|
if epoch < 6:
|
|
|
|
assert backbone_lr <= current_lr
|
|
|
|
else:
|
|
|
|
assert backbone_lr == current_lr
|
|
|
|
|
|
|
|
|
2021-02-04 18:36:54 +00:00
|
|
|
def test_finetuning_callback(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test finetuning callbacks works as expected."""
|
2021-02-04 18:36:54 +00:00
|
|
|
|
|
|
|
seed_everything(42)
|
|
|
|
|
|
|
|
class FinetuningBoringModel(BoringModel):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.backbone = nn.Sequential(nn.Linear(32, 32, bias=False), nn.BatchNorm1d(32), nn.ReLU())
|
|
|
|
self.layer = torch.nn.Linear(32, 2)
|
|
|
|
self.backbone.has_been_used = False
|
|
|
|
|
|
|
|
def training_step(self, batch, batch_idx):
|
|
|
|
output = self(batch)
|
|
|
|
loss = self.loss(batch, output)
|
|
|
|
return {"loss": loss}
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
self.backbone.has_been_used = True
|
|
|
|
x = self.backbone(x)
|
|
|
|
return self.layer(x)
|
|
|
|
|
|
|
|
def configure_optimizers(self):
|
|
|
|
optimizer = torch.optim.SGD(self.layer.parameters(), lr=0.1)
|
|
|
|
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.7)
|
|
|
|
return [optimizer], [lr_scheduler]
|
|
|
|
|
|
|
|
def train_dataloader(self):
|
|
|
|
return DataLoader(RandomDataset(32, 64), batch_size=2)
|
|
|
|
|
|
|
|
model = FinetuningBoringModel()
|
2021-04-30 15:14:43 +00:00
|
|
|
callback = TestBackboneFinetuningCallback(unfreeze_backbone_at_epoch=3, verbose=False)
|
2021-02-04 18:36:54 +00:00
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
trainer = Trainer(limit_train_batches=4, default_root_dir=tmpdir, callbacks=[callback], max_epochs=8)
|
2021-02-04 18:36:54 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
assert model.backbone.has_been_used
|
|
|
|
|
|
|
|
|
2021-04-30 15:14:43 +00:00
|
|
|
class TestBackboneFinetuningWarningCallback(BackboneFinetuning):
|
|
|
|
def finetune_function(self, pl_module, epoch: int, optimizer, opt_idx: int):
|
|
|
|
"""Called when the epoch begins."""
|
|
|
|
|
|
|
|
if epoch == 0:
|
|
|
|
self.unfreeze_and_add_param_group(
|
|
|
|
pl_module.backbone, optimizer, 0.1, train_bn=self.train_bn, initial_denom_lr=self.initial_denom_lr
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2021-02-04 18:36:54 +00:00
|
|
|
def test_finetuning_callback_warning(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test finetuning callbacks works as expected."""
|
2021-02-04 18:36:54 +00:00
|
|
|
|
|
|
|
seed_everything(42)
|
|
|
|
|
|
|
|
class FinetuningBoringModel(BoringModel):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.backbone = nn.Linear(32, 2, bias=False)
|
|
|
|
self.layer = None
|
|
|
|
self.backbone.has_been_used = False
|
|
|
|
|
|
|
|
def training_step(self, batch, batch_idx):
|
|
|
|
output = self(batch)
|
|
|
|
loss = self.loss(batch, output)
|
|
|
|
return {"loss": loss}
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
self.backbone.has_been_used = True
|
|
|
|
x = self.backbone(x)
|
|
|
|
return x
|
|
|
|
|
|
|
|
def train_dataloader(self):
|
|
|
|
return DataLoader(RandomDataset(32, 64), batch_size=2)
|
|
|
|
|
|
|
|
def configure_optimizers(self):
|
|
|
|
optimizer = torch.optim.SGD(self.parameters(), lr=0.1)
|
|
|
|
return optimizer
|
|
|
|
|
2021-04-30 15:14:43 +00:00
|
|
|
chk = ModelCheckpoint(dirpath=tmpdir, save_last=True)
|
2021-02-04 18:36:54 +00:00
|
|
|
|
|
|
|
model = FinetuningBoringModel()
|
|
|
|
model.validation_step = None
|
2021-04-30 15:14:43 +00:00
|
|
|
callback = TestBackboneFinetuningWarningCallback(unfreeze_backbone_at_epoch=3, verbose=False)
|
2021-02-04 18:36:54 +00:00
|
|
|
|
|
|
|
with pytest.warns(UserWarning, match="Did you init your optimizer in"):
|
2021-07-26 11:37:35 +00:00
|
|
|
trainer = Trainer(limit_train_batches=1, default_root_dir=tmpdir, callbacks=[callback, chk], max_epochs=2)
|
2021-02-04 18:36:54 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
assert model.backbone.has_been_used
|
2021-10-25 19:05:31 +00:00
|
|
|
trainer = Trainer(max_epochs=3)
|
|
|
|
trainer.fit(model, ckpt_path=chk.last_model_path)
|
2021-02-04 18:36:54 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_freeze_unfreeze_function(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test freeze properly sets requires_grad on the modules."""
|
2021-02-04 18:36:54 +00:00
|
|
|
|
|
|
|
seed_everything(42)
|
|
|
|
|
|
|
|
class FreezeModel(LightningModule):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.backbone = nn.Sequential(nn.Linear(32, 32), nn.BatchNorm1d(32), nn.ReLU(), nn.Linear(32, 2))
|
|
|
|
|
|
|
|
model = FreezeModel()
|
|
|
|
BaseFinetuning.freeze(model, train_bn=True)
|
|
|
|
assert not model.backbone[0].weight.requires_grad
|
|
|
|
assert model.backbone[1].weight.requires_grad
|
|
|
|
assert not model.backbone[3].weight.requires_grad
|
|
|
|
|
|
|
|
BaseFinetuning.freeze(model, train_bn=False)
|
|
|
|
assert not model.backbone[0].weight.requires_grad
|
|
|
|
assert not model.backbone[1].weight.requires_grad
|
|
|
|
assert not model.backbone[3].weight.requires_grad
|
|
|
|
|
|
|
|
BaseFinetuning.make_trainable(model)
|
|
|
|
assert model.backbone[0].weight.requires_grad
|
|
|
|
assert model.backbone[1].weight.requires_grad
|
|
|
|
assert model.backbone[3].weight.requires_grad
|
|
|
|
|
|
|
|
BaseFinetuning.freeze(model.backbone[0], train_bn=False)
|
|
|
|
assert not model.backbone[0].weight.requires_grad
|
|
|
|
|
|
|
|
BaseFinetuning.freeze(([(model.backbone[1]), [model.backbone[3]]]), train_bn=True)
|
|
|
|
assert model.backbone[1].weight.requires_grad
|
|
|
|
assert not model.backbone[3].weight.requires_grad
|
|
|
|
|
|
|
|
|
|
|
|
def test_unfreeze_and_add_param_group_function(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test unfreeze_and_add_param_group properly unfreeze parameters and add to the correct param_group."""
|
2021-02-04 18:36:54 +00:00
|
|
|
|
|
|
|
seed_everything(42)
|
|
|
|
|
|
|
|
class FreezeModel(LightningModule):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.backbone = nn.Sequential(
|
|
|
|
nn.Linear(32, 32, bias=False),
|
|
|
|
nn.Linear(32, 32, bias=False),
|
|
|
|
nn.Linear(32, 32, bias=False),
|
|
|
|
nn.Linear(32, 32, bias=False),
|
|
|
|
nn.Linear(32, 32, bias=False),
|
2021-02-06 12:28:26 +00:00
|
|
|
nn.BatchNorm1d(32),
|
2021-02-04 18:36:54 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
model = FreezeModel()
|
|
|
|
optimizer = SGD(model.backbone[0].parameters(), lr=0.01)
|
|
|
|
|
2021-10-06 08:39:36 +00:00
|
|
|
with pytest.warns(UserWarning, match="The provided params to be frozen already"):
|
2021-02-04 18:36:54 +00:00
|
|
|
BaseFinetuning.unfreeze_and_add_param_group(model.backbone[0], optimizer=optimizer)
|
|
|
|
assert optimizer.param_groups[0]["lr"] == 0.01
|
|
|
|
|
|
|
|
model.backbone[1].weight.requires_grad = False
|
|
|
|
BaseFinetuning.unfreeze_and_add_param_group(model.backbone[1], optimizer=optimizer)
|
|
|
|
assert len(optimizer.param_groups) == 2
|
|
|
|
assert optimizer.param_groups[1]["lr"] == 0.001
|
|
|
|
assert torch.equal(optimizer.param_groups[1]["params"][0], model.backbone[1].weight)
|
|
|
|
assert model.backbone[1].weight.requires_grad
|
|
|
|
|
2021-10-06 08:39:36 +00:00
|
|
|
with pytest.warns(UserWarning, match="The provided params to be frozen already"):
|
2021-02-04 18:36:54 +00:00
|
|
|
BaseFinetuning.unfreeze_and_add_param_group(model, optimizer=optimizer, lr=100, train_bn=False)
|
|
|
|
assert len(optimizer.param_groups) == 3
|
|
|
|
assert optimizer.param_groups[2]["lr"] == 100
|
|
|
|
assert len(optimizer.param_groups[2]["params"]) == 3
|
|
|
|
for group_idx, group in enumerate(optimizer.param_groups):
|
|
|
|
if group_idx == 0:
|
|
|
|
assert torch.equal(optimizer.param_groups[0]["params"][0], model.backbone[0].weight)
|
|
|
|
if group_idx == 2:
|
|
|
|
assert torch.equal(optimizer.param_groups[2]["params"][0], model.backbone[2].weight)
|
|
|
|
assert torch.equal(optimizer.param_groups[2]["params"][1], model.backbone[3].weight)
|
|
|
|
assert torch.equal(optimizer.param_groups[2]["params"][2], model.backbone[4].weight)
|
PoC: Accelerator refactor (#5743)
* restoring the result from subprocess
* fix queue.get() order for results
* add missing "block_backward_sync" context manager
* add missing "block_backward_sync" context manager
* fix sync_batchnorm
* fix supported gpu-ids for tuple
* fix clip gradients and inf recursion
* accelerator selection: added cluster_environment plugin
* fix torchelastic test
* fix reduce early stopping decision for DDP
* fix tests: callbacks, conversion to lightning optimizer
* fix lightning optimizer does not pickle
* fix setting benchmark and deterministic option
* fix slurm amp test
* fix prepare_data test and determine node_rank
* fix retrieving last path when testing
* remove obsolete plugin argument
* fix test: test_trainer_config
* fix torchscript tests
* fix trainer.model access
* move properties
* fix test_transfer_batch_hook
* fix auto_select_gpus
* fix omegaconf test
* fix test that needs to simulate slurm ddp
* add horovod plugin
* fix test with named arguments
* clean up whitespace
* fix datamodules test
* remove old accelerators
* fix naming
* move old plugins
* move to plugins
* create precision subpackage
* create training_type subpackage
* fix all new import errors
* fix wrong arguments order passed to test
* fix LR finder
* Added sharded training type and amp plugin
* Move clip grad to precision plugin
* Added sharded spawn, select accelerators based on distributed_backend + enable custom fp16 plugin automatically
* Fix import issue, attempting to fix tests
* Fix initial test
* Reflect hook logic from master, should wrap model after move to device
* Optional state consolidation, since master has optimizers not wrapped
* change attribute for instance test
* reset optimizers
optimizers are not used in main process, so state would be wrong.
* legacy
* imports in accel
* legacy2
* trainer imports
* fix import errors after rebase
* move hook to new setup location
* provide unwrapping logic
* fix trainer callback system
* added ddp2 implementation
* fix imports .legacy
* move plugins
* restore legacy
* drop test.py from root
* add tpu accelerator and plugins
* fixes
* fix lightning optimizer merge
* reset bugreportmodel
* unwrapping
* step routing forward
* model access
* unwrap
* opt
* integrate distrib_type
* sync changes
* sync
* fixes
* add forgotten generators
* add missing logic
* update
* import
* missed imports
* import fixes
* isort
* mv f
* changelog
* format
* move helper to parallel plugin
* d
* add world size
* clean up
* duplicate
* activate ddp_sharded and tpu
* set nvidia flags
* remove unused colab var
* use_tpu <-> on_tpu attrs
* make some ddp_cpu and clusterplugin tests pass
* Ref/accelerator connector (#5742)
* final cleanup
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* connector cleanup
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* trainer cleanup
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* accelerator cleanup + missing logic in accelerator connector
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* add missing changes to callbacks
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* reflect accelerator changes to lightning module
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* clean cluster envs
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* cleanup plugins
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* add broadcasting
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* yapf
* remove plugin connector
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* plugins
* manual optimization
* update optimizer routing
* add rank to torchelastic
* fix memory mixed precision
* setstate on trainer for pickling in ddp spawn
* add predict method
* add back commented accelerator code
* adapt test for sync_batch_norm to new plugin
* fix deprecated tests
* fix ddp cpu choice when no num_processes are given
* yapf format
* skip a memory test that cannot pass anymore
* fix pickle error in spawn plugin
* x
* avoid
* x
* fix cyclic import in docs build
* add support for sharded
* update typing
* add sharded and sharded_spawn to distributed types
* make unwrap model default
* refactor LightningShardedDataParallel similar to LightningDistributedDataParallel
* update sharded spawn to reflect changes
* update sharded to reflect changes
* Merge 1.1.5 changes
* fix merge
* fix merge
* yapf isort
* fix merge
* yapf isort
* fix indentation in test
* copy over reinit scheduler implementation from dev1.2
* fix apex tracking calls with dev_debugger
* reduce diff to dev1.2, clean up
* fix trainer config test when gpus>0 and num_processes >0 and ddp_cpu
* sort plugin tests legacy/new
* fix error handling for amp on cpu
* fix merge
fix merge
fix merge
* [Feat] Resolve manual_backward (#5837)
* resolve manual_backward
* resolve flake8
* update
* resolve for ddp_spawn
* resolve flake8
* resolve flake8
* resolve flake8
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
* fix tests/accelerator tests on cpu
* [BugFix] Resolve manual optimization (#5852)
* resolve manual_optimization
* update
* update
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
* Remove copy trainer parameters to happen earlier within the loop and add safe guard to get ref model (#5856)
* resovle a bug
* Accelerator refactor sharded rpc (#5854)
* rpc branch
* merge
* update handling of rpc
* make devices etc. Optional in RPC
* set devices etc. later if necessary
* remove devices from sequential
* make devices optional in rpc
* fix import
* uncomment everything
* fix cluster selection
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
* resolve bug
* fix assert in rpc test
* resolve a test
* fix docs compilation
* accelerator refactor - fix for sharded parity test (#5866)
* fix memory issue with ddp_spawn
* x
x
x
x
x
x
x
x
x
* x
* Remove DDP2 as this does not apply
* Add missing pre optimizer hook to ensure lambda closure is called
* fix apex docstring
* [accelerator][BugFix] Resolve some test for 1 gpu (#5863)
* update
* revert init
* resolve a bug
* update
* resolve flake8
* update
* update
* update
* revert init
* resolve a bug
* update
* resolve flake8
* update
* update
* update
* update
* update
* revert init
* resolve a bug
* update
* resolve flake8
* update
* update
* update
* revert init
* update
* resolve flake8
* update
* update
* update
* update
* update
* all_gather
* update
* make plugins work, add misconfig for RPC
* update
* update
* remove breaking test
* resolve some tests
* resolve flake8
* revert to ddp_spawn
Co-authored-by: root <root@ip-172-31-88-60.ec2.internal>
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
Co-authored-by: Justus Schock <justus.schock@rwth-aachen.de>
* yapf isort
* resolve flake8
* fix apex doctests
* fix apex doctests 2
* resolve docs
* update drone
* clean env
* update
* update
* update
* update
* merge
* Fix RPC related tests, clean out old API, update for new accelerator API [skip ci] (#5881)
* Fix RPC related tests, clean out old API, update for new accelerator API
* Move tests out of legacy folder, update paths and names
* Update test_remove_1-4.py
* Expose properties for tpu cores/gpus/num_gpus
* Add root GPU property
* Move properties to properties.py
* move tests that were previously in drone
* Fix root GPU property (#5908)
* Move root GPU to property, remove horovod set as this is handled in horovod plugin, ensure we mock correctly to set GPU accelerator
* Add missing tests back
* fix best model path transfer when no checkpoint callback available
* Fix setup hook order [wip] (#5858)
* Call trainer setup hook before accelerator setup
* Add test case
* add new test
* typo
* fix callback order in test
Co-authored-by: tchaton <thomas@grid.ai>
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* rename ddp sequential -> rpc sequential for special test
* revert
* fix stupid merge problem
* Use property in connector for sampler (#5913)
* merge the import conflicts
* fix spawning of processes in slurm
* [wip] Fix some bugs for TPU [skip ci] (#5878)
* fixed for single tpu
* fixed spawn
* fixed spawn
* update
* update
* wip
* resolve bugs
* resolve bug
* update on comment
* removed decorator
* resolve comments
* set to 4
* update
* update
* need cleaning
* update
* update
* update
* resolve flake8
* resolve bugs
* exclude broadcast
* resolve bugs
* change test
* update
* update
* skip if meet fails
* properly raise trace
* update
* add catch
* wrap test
* resolve typo
* update
* typo
Co-authored-by: Lezwon Castelino <lezwon@gmail.com>
Co-authored-by: Your Name <you@example.com>
* resolve some tests
* update
* fix imports
* update
* resolve flake8
* update azure pipeline
* skip a sharded test on cpu that requires a gpu
* resolve tpus
* resolve bug
* resolve flake8
* update
* updat utils
* revert permission change on files
* suggestions from carlos
Co-authored-by: Carlos Mocholí <carlossmocholi@gmail.com>
* remove unrelated formatting changes
* remove incomplete comment
* Update pytorch_lightning/accelerators/__init__.py
Co-authored-by: Carlos Mocholí <carlossmocholi@gmail.com>
* remove unrelated formatting change
* add types
* warn 1.7 ddp manual backward only if ddp kwarg unset
* yapf + isort
* pep8 unused imports
* fix cyclic import in docs
* Apply suggestions from code review
* typer in accelerator.py
* typo
* Apply suggestions from code review
* formatting
* update on comments
* update typo
* Update pytorch_lightning/trainer/properties.py
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* update
* suggestion from code review
* suggestion from code review
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
Co-authored-by: SeanNaren <sean@grid.ai>
Co-authored-by: Jirka Borovec <jirka.borovec@seznam.cz>
Co-authored-by: chaton <thomas@grid.ai>
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
Co-authored-by: Sean Naren <sean.narenthiran@gmail.com>
Co-authored-by: root <root@ip-172-31-88-60.ec2.internal>
Co-authored-by: Lezwon Castelino <lezwon@gmail.com>
Co-authored-by: Your Name <you@example.com>
Co-authored-by: Carlos Mocholí <carlossmocholi@gmail.com>
Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-02-12 20:48:56 +00:00
|
|
|
|
|
|
|
|
2021-04-30 15:14:43 +00:00
|
|
|
class OnEpochLayerFinetuning(BaseFinetuning):
|
|
|
|
def freeze_before_training(self, pl_module: LightningModule):
|
|
|
|
self.freeze(pl_module.layer)
|
|
|
|
|
|
|
|
def finetune_function(self, pl_module: LightningModule, epoch: int, optimizer: Optimizer, opt_idx: int):
|
|
|
|
self.unfreeze_and_add_param_group(pl_module.layer[epoch + 1], optimizer)
|
|
|
|
|
|
|
|
|
2021-07-23 17:49:32 +00:00
|
|
|
def test_base_finetuning_internal_optimizer_metadata(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test the param_groups updates are properly saved within the internal state of the BaseFinetuning
|
|
|
|
Callbacks."""
|
2021-04-30 15:14:43 +00:00
|
|
|
|
|
|
|
seed_everything(42)
|
|
|
|
|
|
|
|
class FreezeModel(BoringModel):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.layer = nn.Sequential(
|
|
|
|
nn.Linear(32, 32, bias=False),
|
|
|
|
nn.Linear(32, 32, bias=True),
|
|
|
|
nn.Linear(32, 32, bias=False),
|
|
|
|
nn.Linear(32, 32, bias=True),
|
|
|
|
nn.Linear(32, 32, bias=False),
|
|
|
|
nn.Linear(32, 2, bias=True),
|
|
|
|
)
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
return self.layer(x)
|
|
|
|
|
|
|
|
def configure_optimizers(self):
|
|
|
|
return torch.optim.SGD(self.layer[0].parameters(), lr=0.1)
|
|
|
|
|
|
|
|
cb = OnEpochLayerFinetuning()
|
|
|
|
chk = ModelCheckpoint(dirpath=tmpdir, save_last=True)
|
|
|
|
model = FreezeModel()
|
|
|
|
trainer = Trainer(default_root_dir=tmpdir, max_epochs=5, limit_train_batches=1, callbacks=[cb, chk])
|
|
|
|
trainer.fit(model)
|
2021-07-23 17:49:32 +00:00
|
|
|
assert len(cb._internal_optimizer_metadata[0]) == 6
|
2021-07-26 11:37:35 +00:00
|
|
|
assert cb._internal_optimizer_metadata[0][0]["params"] == ["layer.0.weight"]
|
|
|
|
assert cb._internal_optimizer_metadata[0][1]["params"] == ["layer.1.weight", "layer.1.bias"]
|
|
|
|
assert cb._internal_optimizer_metadata[0][2]["params"] == ["layer.2.weight"]
|
|
|
|
assert cb._internal_optimizer_metadata[0][3]["params"] == ["layer.3.weight", "layer.3.bias"]
|
|
|
|
assert cb._internal_optimizer_metadata[0][4]["params"] == ["layer.4.weight"]
|
|
|
|
assert cb._internal_optimizer_metadata[0][5]["params"] == ["layer.5.weight", "layer.5.bias"]
|
2021-04-30 15:14:43 +00:00
|
|
|
|
|
|
|
model = FreezeModel()
|
|
|
|
cb = OnEpochLayerFinetuning()
|
2021-10-25 19:05:31 +00:00
|
|
|
trainer = Trainer(max_epochs=10, callbacks=[cb])
|
2021-07-23 17:49:32 +00:00
|
|
|
with pytest.raises(IndexError, match="index 6 is out of range"):
|
2021-10-25 19:05:31 +00:00
|
|
|
trainer.fit(model, ckpt_path=chk.last_model_path)
|
2021-04-30 15:14:43 +00:00
|
|
|
|
|
|
|
|
2022-02-05 04:23:16 +00:00
|
|
|
class ConvBlock(nn.Module):
|
|
|
|
def __init__(self, in_channels, out_channels):
|
|
|
|
super().__init__()
|
|
|
|
self.conv = nn.Conv2d(in_channels, out_channels, 3)
|
|
|
|
self.act = nn.ReLU()
|
|
|
|
self.bn = nn.BatchNorm2d(out_channels)
|
2021-04-08 07:29:06 +00:00
|
|
|
|
2022-02-05 04:23:16 +00:00
|
|
|
def forward(self, x):
|
|
|
|
x = self.conv(x)
|
|
|
|
x = self.act(x)
|
|
|
|
return self.bn(x)
|
2021-04-08 07:29:06 +00:00
|
|
|
|
|
|
|
|
2022-02-05 04:23:16 +00:00
|
|
|
class ConvBlockParam(nn.Module):
|
|
|
|
def __init__(self, in_channels, out_channels):
|
|
|
|
super().__init__()
|
|
|
|
self.module_dict = nn.ModuleDict({"conv": nn.Conv2d(in_channels, out_channels, 3), "act": nn.ReLU()})
|
|
|
|
# add trivial test parameter to convblock to validate parent (non-leaf) module parameter handling
|
|
|
|
self.parent_param = nn.Parameter(torch.zeros((1), dtype=torch.float))
|
|
|
|
self.bn = nn.BatchNorm2d(out_channels)
|
2021-06-14 16:01:07 +00:00
|
|
|
|
2022-02-05 04:23:16 +00:00
|
|
|
def forward(self, x):
|
|
|
|
x = self.module_dict["conv"](x)
|
|
|
|
x = self.module_dict["act"](x)
|
|
|
|
return self.bn(x)
|
|
|
|
|
|
|
|
|
|
|
|
def test_complex_nested_model():
|
|
|
|
"""Test flattening, freezing, and thawing of models which contain parent (non-leaf) modules with parameters
|
|
|
|
directly themselves rather than exclusively their submodules containing parameters."""
|
2021-06-14 16:01:07 +00:00
|
|
|
|
2021-04-08 07:29:06 +00:00
|
|
|
model = nn.Sequential(
|
2021-07-26 11:37:35 +00:00
|
|
|
OrderedDict(
|
|
|
|
[("encoder", nn.Sequential(ConvBlockParam(3, 64), ConvBlock(64, 128))), ("decoder", ConvBlock(128, 10))]
|
|
|
|
)
|
2021-04-08 07:29:06 +00:00
|
|
|
)
|
|
|
|
|
2021-06-14 16:01:07 +00:00
|
|
|
# There are 10 leaf modules or parent modules w/ parameters in the test model
|
|
|
|
assert len(BaseFinetuning.flatten_modules(model)) == 10
|
2021-04-08 07:29:06 +00:00
|
|
|
|
|
|
|
BaseFinetuning.freeze(model.encoder, train_bn=True)
|
2021-06-28 10:55:32 +00:00
|
|
|
assert not model.encoder[0].module_dict["conv"].weight.requires_grad # Validate a leaf module parameter is frozen
|
2021-06-14 16:01:07 +00:00
|
|
|
assert not model.encoder[0].parent_param.requires_grad # Validate the parent module parameter is frozen
|
2021-04-08 07:29:06 +00:00
|
|
|
assert model.encoder[0].bn.weight.requires_grad
|
|
|
|
|
|
|
|
BaseFinetuning.make_trainable(model)
|
|
|
|
encoder_params = list(BaseFinetuning.filter_params(model.encoder, train_bn=True))
|
2021-06-14 16:01:07 +00:00
|
|
|
# The 9 parameters of the encoder are:
|
|
|
|
# conv0.weight, conv0.bias, bn0.weight, bn0.bias, parent_param
|
2021-04-08 07:29:06 +00:00
|
|
|
# conv1.weight, conv1.bias, bn1.weight, bn1.bias
|
2021-06-14 16:01:07 +00:00
|
|
|
assert len(encoder_params) == 9
|
2021-07-23 17:49:32 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TestCallbacksRestoreCallback(BaseFinetuning):
|
|
|
|
def freeze_before_training(self, pl_module):
|
|
|
|
self.freeze(pl_module.layer[:3])
|
|
|
|
|
|
|
|
def finetune_function(self, pl_module, epoch, optimizer, opt_idx):
|
|
|
|
if epoch >= 1:
|
|
|
|
self.unfreeze_and_add_param_group(pl_module.layer[epoch - 1], optimizer)
|
|
|
|
|
|
|
|
|
|
|
|
class FinetuningBoringModel(BoringModel):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.layer = nn.Sequential(nn.Linear(32, 32), nn.Linear(32, 32), nn.Linear(32, 32), nn.Linear(32, 2))
|
|
|
|
|
|
|
|
def configure_optimizers(self):
|
|
|
|
parameters = filter(lambda x: x.requires_grad, self.parameters())
|
|
|
|
optimizer = torch.optim.SGD(parameters, lr=0.1)
|
|
|
|
return optimizer
|
|
|
|
|
|
|
|
|
|
|
|
def test_callbacks_restore(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test callbacks restore is called after optimizers have been re-created but before optimizer states
|
|
|
|
reload."""
|
2021-07-23 17:49:32 +00:00
|
|
|
chk = ModelCheckpoint(dirpath=tmpdir, save_last=True)
|
|
|
|
|
|
|
|
model = FinetuningBoringModel()
|
|
|
|
callback = TestCallbacksRestoreCallback()
|
|
|
|
|
|
|
|
trainer_kwargs = dict(
|
|
|
|
default_root_dir=tmpdir, limit_train_batches=1, limit_val_batches=1, callbacks=[callback, chk], max_epochs=2
|
|
|
|
)
|
|
|
|
|
|
|
|
trainer = Trainer(**trainer_kwargs)
|
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
# only 1 optimizer
|
|
|
|
assert len(callback._internal_optimizer_metadata) == 1
|
|
|
|
|
|
|
|
# only 2 param groups
|
|
|
|
assert len(callback._internal_optimizer_metadata[0]) == 2
|
|
|
|
|
|
|
|
# original parameters
|
2022-03-10 16:01:08 +00:00
|
|
|
expected = {
|
2021-07-26 11:37:35 +00:00
|
|
|
"lr": 0.1,
|
|
|
|
"momentum": 0,
|
|
|
|
"dampening": 0,
|
|
|
|
"weight_decay": 0,
|
|
|
|
"nesterov": False,
|
|
|
|
"params": ["layer.3.weight", "layer.3.bias"],
|
2021-07-23 17:49:32 +00:00
|
|
|
}
|
2022-03-10 16:01:08 +00:00
|
|
|
if _TORCH_GREATER_EQUAL_1_11:
|
|
|
|
expected["maximize"] = False
|
|
|
|
assert callback._internal_optimizer_metadata[0][0] == expected
|
2021-07-23 17:49:32 +00:00
|
|
|
|
|
|
|
# new param group
|
2022-03-10 16:01:08 +00:00
|
|
|
expected = {
|
2021-07-26 11:37:35 +00:00
|
|
|
"lr": 0.01,
|
|
|
|
"momentum": 0,
|
|
|
|
"dampening": 0,
|
|
|
|
"weight_decay": 0,
|
|
|
|
"nesterov": False,
|
|
|
|
"params": ["layer.0.weight", "layer.0.bias"],
|
2021-07-23 17:49:32 +00:00
|
|
|
}
|
2022-03-10 16:01:08 +00:00
|
|
|
if _TORCH_GREATER_EQUAL_1_11:
|
|
|
|
expected["maximize"] = False
|
|
|
|
assert callback._internal_optimizer_metadata[0][1] == expected
|
2021-07-23 17:49:32 +00:00
|
|
|
|
|
|
|
trainer_kwargs["max_epochs"] = 3
|
|
|
|
|
|
|
|
trainer = Trainer(**trainer_kwargs)
|
2021-10-25 19:05:31 +00:00
|
|
|
trainer.fit(model, ckpt_path=chk.last_model_path)
|
2021-07-23 17:49:32 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_callbacks_restore_backbone(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test callbacks restore is called after optimizers have been re-created but before optimizer states
|
|
|
|
reload."""
|
2021-07-23 17:49:32 +00:00
|
|
|
|
|
|
|
class BackboneBoringModel(BoringModel):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.layer = nn.Linear(32, 2)
|
|
|
|
self.backbone = nn.Linear(32, 32)
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
return self.layer(self.backbone(x))
|
|
|
|
|
|
|
|
ckpt = ModelCheckpoint(dirpath=tmpdir, save_last=True)
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
limit_train_batches=1,
|
|
|
|
limit_val_batches=1,
|
|
|
|
max_epochs=2,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2021-07-26 11:37:35 +00:00
|
|
|
callbacks=[ckpt, BackboneFinetuning(unfreeze_backbone_at_epoch=1)],
|
2021-07-23 17:49:32 +00:00
|
|
|
)
|
|
|
|
trainer.fit(BackboneBoringModel())
|
|
|
|
|
|
|
|
# initialize a trainer that continues the previous training
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
limit_train_batches=1,
|
|
|
|
limit_val_batches=1,
|
|
|
|
max_epochs=3,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2021-07-23 17:49:32 +00:00
|
|
|
callbacks=BackboneFinetuning(unfreeze_backbone_at_epoch=1),
|
|
|
|
)
|
2021-10-25 19:05:31 +00:00
|
|
|
trainer.fit(BackboneBoringModel(), ckpt_path=ckpt.last_model_path)
|