2020-10-13 11:18:07 +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-11-19 00:52:55 +00:00
|
|
|
from functools import partial, update_wrapper
|
2021-06-14 12:42:13 +00:00
|
|
|
from inspect import getmembers, isfunction
|
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
|
|
|
from unittest import mock
|
2021-06-14 12:42:13 +00:00
|
|
|
from unittest.mock import ANY, PropertyMock
|
2020-06-03 01:45:19 +00:00
|
|
|
|
2020-04-16 16:01:41 +00:00
|
|
|
import pytest
|
2020-05-24 22:59:08 +00:00
|
|
|
import torch
|
2021-05-13 17:33:55 +00:00
|
|
|
from torch.utils.data import DataLoader
|
2020-04-16 16:01:41 +00:00
|
|
|
|
2021-06-16 13:09:24 +00:00
|
|
|
from pytorch_lightning import __version__, Callback, LightningDataModule, LightningModule, Trainer
|
2021-03-30 17:39:02 +00:00
|
|
|
from tests.helpers import BoringDataModule, BoringModel, RandomDataset
|
2021-03-02 09:36:01 +00:00
|
|
|
from tests.helpers.runif import RunIf
|
2020-04-16 16:01:41 +00:00
|
|
|
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
@pytest.mark.parametrize("max_steps", [1, 2, 3])
|
2020-06-29 01:36:46 +00:00
|
|
|
def test_on_before_zero_grad_called(tmpdir, max_steps):
|
2021-02-11 14:32:07 +00:00
|
|
|
class CurrentTestModel(BoringModel):
|
2020-04-16 16:01:41 +00:00
|
|
|
on_before_zero_grad_called = 0
|
|
|
|
|
|
|
|
def on_before_zero_grad(self, optimizer):
|
|
|
|
self.on_before_zero_grad_called += 1
|
|
|
|
|
2020-05-10 17:15:28 +00:00
|
|
|
model = CurrentTestModel()
|
2020-04-16 16:01:41 +00:00
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
trainer = Trainer(default_root_dir=tmpdir, max_steps=max_steps, max_epochs=2)
|
2020-04-16 16:01:41 +00:00
|
|
|
assert 0 == model.on_before_zero_grad_called
|
|
|
|
trainer.fit(model)
|
|
|
|
assert max_steps == model.on_before_zero_grad_called
|
|
|
|
|
|
|
|
model.on_before_zero_grad_called = 0
|
|
|
|
trainer.test(model)
|
|
|
|
assert 0 == model.on_before_zero_grad_called
|
2020-05-24 22:59:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_training_epoch_end_metrics_collection(tmpdir):
|
2021-07-26 11:37:35 +00:00
|
|
|
"""Test that progress bar metrics also get collected at the end of an epoch."""
|
2020-05-24 22:59:08 +00:00
|
|
|
num_epochs = 3
|
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
class CurrentModel(BoringModel):
|
2020-05-24 22:59:08 +00:00
|
|
|
def training_step(self, *args, **kwargs):
|
|
|
|
output = super().training_step(*args, **kwargs)
|
2021-07-26 11:37:35 +00:00
|
|
|
self.log_dict({"step_metric": torch.tensor(-1), "shared_metric": 100}, logger=False, prog_bar=True)
|
2020-05-24 22:59:08 +00:00
|
|
|
return output
|
|
|
|
|
|
|
|
def training_epoch_end(self, outputs):
|
|
|
|
epoch = self.current_epoch
|
|
|
|
# both scalar tensors and Python numbers are accepted
|
2021-02-11 14:32:07 +00:00
|
|
|
self.log_dict(
|
2021-07-26 11:37:35 +00:00
|
|
|
{f"epoch_metric_{epoch}": torch.tensor(epoch), "shared_metric": 111}, logger=False, prog_bar=True
|
2021-02-11 14:32:07 +00:00
|
|
|
)
|
2020-05-24 22:59:08 +00:00
|
|
|
|
|
|
|
model = CurrentModel()
|
2021-07-26 11:37:35 +00:00
|
|
|
trainer = Trainer(max_epochs=num_epochs, default_root_dir=tmpdir, overfit_batches=2)
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
2021-05-04 10:50:56 +00:00
|
|
|
assert trainer.state.finished, f"Training failed with {trainer.state}"
|
2021-09-09 20:53:47 +00:00
|
|
|
metrics = trainer.progress_bar_callback.get_metrics(trainer, model)
|
2020-05-24 22:59:08 +00:00
|
|
|
|
|
|
|
# metrics added in training step should be unchanged by epoch end method
|
2021-07-26 11:37:35 +00:00
|
|
|
assert metrics["step_metric"] == -1
|
2020-05-24 22:59:08 +00:00
|
|
|
# a metric shared in both methods gets overwritten by epoch_end
|
2021-07-26 11:37:35 +00:00
|
|
|
assert metrics["shared_metric"] == 111
|
2020-05-24 22:59:08 +00:00
|
|
|
# metrics are kept after each epoch
|
2020-06-20 03:39:53 +00:00
|
|
|
for i in range(num_epochs):
|
2021-07-26 11:37:35 +00:00
|
|
|
assert metrics[f"epoch_metric_{i}"] == i
|
2020-06-03 01:45:19 +00:00
|
|
|
|
|
|
|
|
2021-01-26 13:01:46 +00:00
|
|
|
def test_training_epoch_end_metrics_collection_on_override(tmpdir):
|
2021-07-26 11:37:35 +00:00
|
|
|
"""Test that batch end metrics are collected when training_epoch_end is overridden at the end of an epoch."""
|
2021-01-26 13:01:46 +00:00
|
|
|
|
2021-05-05 15:18:16 +00:00
|
|
|
class OverriddenModel(BoringModel):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
2021-01-26 13:01:46 +00:00
|
|
|
self.len_outputs = 0
|
|
|
|
|
|
|
|
def on_train_epoch_start(self):
|
|
|
|
self.num_train_batches = 0
|
|
|
|
|
2021-05-05 15:18:16 +00:00
|
|
|
def training_epoch_end(self, outputs):
|
|
|
|
self.len_outputs = len(outputs)
|
2021-01-26 13:01:46 +00:00
|
|
|
|
2021-10-07 10:18:11 +00:00
|
|
|
def on_train_batch_end(self, outputs, batch, batch_idx):
|
2021-01-26 13:01:46 +00:00
|
|
|
self.num_train_batches += 1
|
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
class NotOverriddenModel(BoringModel):
|
2021-01-26 13:01:46 +00:00
|
|
|
def on_train_epoch_start(self):
|
|
|
|
self.num_train_batches = 0
|
|
|
|
|
2021-10-07 10:18:11 +00:00
|
|
|
def on_train_batch_end(self, outputs, batch, batch_idx):
|
2021-01-26 13:01:46 +00:00
|
|
|
self.num_train_batches += 1
|
|
|
|
|
|
|
|
overridden_model = OverriddenModel()
|
|
|
|
not_overridden_model = NotOverriddenModel()
|
2021-02-11 14:32:07 +00:00
|
|
|
not_overridden_model.training_epoch_end = None
|
2021-01-26 13:01:46 +00:00
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
trainer = Trainer(max_epochs=1, default_root_dir=tmpdir, overfit_batches=2)
|
2021-01-26 13:01:46 +00:00
|
|
|
|
2021-02-04 17:56:45 +00:00
|
|
|
trainer.fit(overridden_model)
|
2021-05-05 15:18:16 +00:00
|
|
|
assert overridden_model.len_outputs == overridden_model.num_train_batches
|
2021-01-26 13:01:46 +00:00
|
|
|
|
|
|
|
|
2021-03-02 08:03:32 +00:00
|
|
|
@RunIf(min_gpus=1)
|
2021-11-29 20:11:21 +00:00
|
|
|
@mock.patch(
|
2021-12-23 14:01:23 +00:00
|
|
|
"pytorch_lightning.strategies.Strategy.lightning_module",
|
2021-11-29 20:11:21 +00:00
|
|
|
new_callable=PropertyMock,
|
|
|
|
)
|
2021-02-18 11:58:12 +00:00
|
|
|
def test_apply_batch_transfer_handler(model_getter_mock):
|
2021-07-26 11:37:35 +00:00
|
|
|
expected_device = torch.device("cuda", 0)
|
2020-06-03 01:45:19 +00:00
|
|
|
|
|
|
|
class CustomBatch:
|
|
|
|
def __init__(self, data):
|
|
|
|
self.samples = data[0]
|
|
|
|
self.targets = data[1]
|
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
class CurrentTestModel(BoringModel):
|
2021-02-18 11:58:12 +00:00
|
|
|
rank = 0
|
|
|
|
transfer_batch_to_device_hook_rank = None
|
|
|
|
on_before_batch_transfer_hook_rank = None
|
|
|
|
on_after_batch_transfer_hook_rank = None
|
|
|
|
|
2021-02-18 19:24:19 +00:00
|
|
|
def on_before_batch_transfer(self, batch, dataloader_idx):
|
2021-08-16 11:34:42 +00:00
|
|
|
assert dataloader_idx == 0
|
2021-02-18 11:58:12 +00:00
|
|
|
self.on_before_batch_transfer_hook_rank = self.rank
|
|
|
|
self.rank += 1
|
|
|
|
batch.samples += 1
|
|
|
|
return batch
|
|
|
|
|
2021-02-18 19:24:19 +00:00
|
|
|
def on_after_batch_transfer(self, batch, dataloader_idx):
|
2021-08-16 11:34:42 +00:00
|
|
|
assert dataloader_idx == 0
|
2021-02-18 11:58:12 +00:00
|
|
|
assert batch.samples.device == batch.targets.device == expected_device
|
|
|
|
self.on_after_batch_transfer_hook_rank = self.rank
|
|
|
|
self.rank += 1
|
|
|
|
batch.targets *= 2
|
|
|
|
return batch
|
|
|
|
|
2021-05-13 17:33:55 +00:00
|
|
|
def transfer_batch_to_device(self, batch, device, dataloader_idx):
|
2021-08-16 11:34:42 +00:00
|
|
|
assert dataloader_idx == 0
|
2021-02-18 11:58:12 +00:00
|
|
|
self.transfer_batch_to_device_hook_rank = self.rank
|
|
|
|
self.rank += 1
|
|
|
|
batch.samples = batch.samples.to(device)
|
|
|
|
batch.targets = batch.targets.to(device)
|
|
|
|
return batch
|
2020-06-03 01:45:19 +00:00
|
|
|
|
|
|
|
model = CurrentTestModel()
|
2021-02-11 14:32:07 +00:00
|
|
|
batch = CustomBatch((torch.zeros(5, 32), torch.ones(5, 1, dtype=torch.long)))
|
2020-06-03 01:45:19 +00:00
|
|
|
|
2020-09-09 02:14:17 +00:00
|
|
|
trainer = Trainer(gpus=1)
|
2020-06-03 01:45:19 +00:00
|
|
|
# running .fit() would require us to implement custom data loaders, we mock the model reference instead
|
2021-02-18 11:58:12 +00:00
|
|
|
|
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
|
|
|
model_getter_mock.return_value = model
|
2021-12-22 02:11:43 +00:00
|
|
|
batch_gpu = trainer.strategy.batch_to_device(batch, expected_device)
|
2021-02-18 11:58:12 +00:00
|
|
|
|
|
|
|
assert model.on_before_batch_transfer_hook_rank == 0
|
|
|
|
assert model.transfer_batch_to_device_hook_rank == 1
|
|
|
|
assert model.on_after_batch_transfer_hook_rank == 2
|
|
|
|
assert batch_gpu.samples.device == batch_gpu.targets.device == expected_device
|
|
|
|
assert torch.allclose(batch_gpu.samples.cpu(), torch.ones(5, 32))
|
|
|
|
assert torch.allclose(batch_gpu.targets.cpu(), torch.ones(5, 1, dtype=torch.long) * 2)
|
2020-10-02 19:46:46 +00:00
|
|
|
|
|
|
|
|
2021-11-26 17:13:14 +00:00
|
|
|
@RunIf(min_gpus=2, standalone=True)
|
2021-01-08 17:05:22 +00:00
|
|
|
def test_transfer_batch_hook_ddp(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test custom data are properly moved to the right device using ddp."""
|
2021-01-08 17:05:22 +00:00
|
|
|
|
|
|
|
class CustomBatch:
|
|
|
|
def __init__(self, data):
|
|
|
|
self.samples = data[0]
|
|
|
|
|
|
|
|
def to(self, device, **kwargs):
|
|
|
|
self.samples = self.samples.to(device, **kwargs)
|
|
|
|
return self
|
|
|
|
|
|
|
|
def collate_fn(batch):
|
|
|
|
return CustomBatch(batch)
|
|
|
|
|
|
|
|
class TestModel(BoringModel):
|
|
|
|
def training_step(self, batch, batch_idx):
|
|
|
|
assert batch.samples.device == self.device
|
|
|
|
assert isinstance(batch_idx, int)
|
|
|
|
|
|
|
|
def train_dataloader(self):
|
|
|
|
return torch.utils.data.DataLoader(RandomDataset(32, 64), collate_fn=collate_fn)
|
|
|
|
|
|
|
|
model = TestModel()
|
|
|
|
model.validation_step = None
|
|
|
|
model.training_epoch_end = None
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
limit_train_batches=2,
|
|
|
|
limit_val_batches=0,
|
|
|
|
max_epochs=1,
|
2021-10-13 11:50:54 +00:00
|
|
|
enable_model_summary=False,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="ddp",
|
2021-01-08 17:05:22 +00:00
|
|
|
gpus=2,
|
|
|
|
)
|
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
|
2021-06-14 16:16:42 +00:00
|
|
|
def get_members(cls):
|
2021-07-26 11:37:35 +00:00
|
|
|
return {h for h, _ in getmembers(cls, predicate=isfunction) if not h.startswith("_")}
|
2021-06-14 16:16:42 +00:00
|
|
|
|
|
|
|
|
2021-06-16 13:09:24 +00:00
|
|
|
class HookedCallback(Callback):
|
|
|
|
def __init__(self, called):
|
2021-07-29 10:28:29 +00:00
|
|
|
def call(hook, fn, *args, **kwargs):
|
|
|
|
out = fn(*args, **kwargs)
|
2021-07-26 11:37:35 +00:00
|
|
|
d = {"name": f"Callback.{hook}"}
|
2021-06-16 13:09:24 +00:00
|
|
|
if args:
|
2021-07-26 11:37:35 +00:00
|
|
|
d["args"] = args
|
2021-06-16 13:09:24 +00:00
|
|
|
if kwargs:
|
2021-07-26 11:37:35 +00:00
|
|
|
d["kwargs"] = kwargs
|
2021-06-16 13:09:24 +00:00
|
|
|
called.append(d)
|
2021-07-29 10:28:29 +00:00
|
|
|
return out
|
2021-06-16 13:09:24 +00:00
|
|
|
|
|
|
|
for h in get_members(Callback):
|
2021-07-29 10:28:29 +00:00
|
|
|
attr = getattr(self, h)
|
2021-11-19 00:52:55 +00:00
|
|
|
partial_h = partial(call, h, attr)
|
|
|
|
update_wrapper(partial_h, attr)
|
|
|
|
setattr(self, h, partial_h)
|
2021-07-29 10:28:29 +00:00
|
|
|
|
|
|
|
def on_save_checkpoint(*args, **kwargs):
|
|
|
|
return {"foo": True}
|
2021-06-16 13:09:24 +00:00
|
|
|
|
|
|
|
|
2021-05-24 22:26:32 +00:00
|
|
|
class HookedModel(BoringModel):
|
2021-06-14 16:16:42 +00:00
|
|
|
def __init__(self, called):
|
2021-05-24 22:26:32 +00:00
|
|
|
super().__init__()
|
2021-06-14 16:16:42 +00:00
|
|
|
pl_module_hooks = get_members(LightningModule)
|
2021-07-09 06:15:57 +00:00
|
|
|
# remove non-hooks
|
2021-10-28 15:23:27 +00:00
|
|
|
pl_module_hooks.difference_update({"optimizers", "log", "log_dict"})
|
2021-06-14 16:16:42 +00:00
|
|
|
# remove most `nn.Module` hooks
|
|
|
|
module_hooks = get_members(torch.nn.Module)
|
2021-07-26 11:37:35 +00:00
|
|
|
module_hooks.difference_update({"forward", "zero_grad", "train"})
|
2021-07-09 06:15:57 +00:00
|
|
|
pl_module_hooks.difference_update(module_hooks)
|
2021-06-14 16:16:42 +00:00
|
|
|
|
|
|
|
def call(hook, fn, *args, **kwargs):
|
|
|
|
out = fn(*args, **kwargs)
|
2021-07-26 11:37:35 +00:00
|
|
|
d = {"name": hook}
|
2021-06-16 13:09:24 +00:00
|
|
|
if args:
|
2021-07-26 11:37:35 +00:00
|
|
|
d["args"] = args
|
|
|
|
elif hook == "train":
|
2021-07-05 10:50:01 +00:00
|
|
|
# DeepSpeed calls `train(mode)` but we do not. Standardize
|
|
|
|
# https://github.com/microsoft/DeepSpeed/pull/571
|
2021-07-26 11:37:35 +00:00
|
|
|
d["args"] = (True,)
|
2021-06-16 13:09:24 +00:00
|
|
|
if kwargs:
|
2021-07-26 11:37:35 +00:00
|
|
|
d["kwargs"] = kwargs
|
2021-06-16 13:09:24 +00:00
|
|
|
called.append(d)
|
2021-06-14 16:16:42 +00:00
|
|
|
return out
|
|
|
|
|
|
|
|
for h in pl_module_hooks:
|
|
|
|
attr = getattr(self, h)
|
2021-11-19 00:52:55 +00:00
|
|
|
partial_h = partial(call, h, attr)
|
|
|
|
update_wrapper(partial_h, attr)
|
|
|
|
setattr(self, h, partial_h)
|
2021-06-14 16:16:42 +00:00
|
|
|
|
|
|
|
def validation_epoch_end(self, *args, **kwargs):
|
|
|
|
# `BoringModel` does not have a return for `validation_step_end` so this would fail
|
|
|
|
pass
|
|
|
|
|
|
|
|
def test_epoch_end(self, *args, **kwargs):
|
|
|
|
# `BoringModel` does not have a return for `test_step_end` so this would fail
|
|
|
|
pass
|
|
|
|
|
2021-07-09 06:15:57 +00:00
|
|
|
def _train_batch(self, *args, **kwargs):
|
|
|
|
if self.automatic_optimization:
|
|
|
|
return self._auto_train_batch(*args, **kwargs)
|
|
|
|
return self._manual_train_batch(*args, **kwargs)
|
|
|
|
|
2021-06-14 16:16:42 +00:00
|
|
|
@staticmethod
|
2022-02-10 16:55:59 +00:00
|
|
|
def _auto_train_batch(
|
|
|
|
trainer, model, batches, device=torch.device("cpu"), current_epoch=0, current_batch=0, **kwargs
|
|
|
|
):
|
2021-07-26 11:37:35 +00:00
|
|
|
using_native_amp = kwargs.get("amp_backend") == "native"
|
2021-10-20 15:32:53 +00:00
|
|
|
using_deepspeed = kwargs.get("strategy") == "deepspeed"
|
2021-06-21 17:27:37 +00:00
|
|
|
out = []
|
2022-02-10 16:55:59 +00:00
|
|
|
for i in range(current_batch, batches):
|
2021-07-26 11:37:35 +00:00
|
|
|
out.extend(
|
|
|
|
[
|
|
|
|
dict(name="on_before_batch_transfer", args=(ANY, 0)),
|
|
|
|
dict(name="transfer_batch_to_device", args=(ANY, device, 0)),
|
|
|
|
dict(name="on_after_batch_transfer", args=(ANY, 0)),
|
|
|
|
dict(name="Callback.on_batch_start", args=(trainer, model)),
|
2021-10-07 10:18:11 +00:00
|
|
|
dict(name="Callback.on_train_batch_start", args=(trainer, model, ANY, i)),
|
|
|
|
dict(name="on_train_batch_start", args=(ANY, i)),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="forward", args=(ANY,)),
|
|
|
|
dict(name="training_step", args=(ANY, i)),
|
|
|
|
dict(name="training_step_end", args=(dict(loss=ANY),)),
|
|
|
|
dict(name="Callback.on_before_zero_grad", args=(trainer, model, ANY)),
|
|
|
|
dict(name="on_before_zero_grad", args=(ANY,)),
|
|
|
|
dict(name="optimizer_zero_grad", args=(current_epoch, i, ANY, 0)),
|
|
|
|
dict(name="Callback.on_before_backward", args=(trainer, model, ANY)),
|
|
|
|
dict(name="on_before_backward", args=(ANY,)),
|
|
|
|
# DeepSpeed handles backward internally
|
|
|
|
*([dict(name="backward", args=(ANY, ANY, 0))] if not using_deepspeed else []),
|
|
|
|
dict(name="Callback.on_after_backward", args=(trainer, model)),
|
|
|
|
dict(name="on_after_backward"),
|
2021-10-29 13:03:04 +00:00
|
|
|
# note: unscaling happens here in the case of AMP
|
|
|
|
dict(name="Callback.on_before_optimizer_step", args=(trainer, model, ANY, 0)),
|
|
|
|
dict(name="on_before_optimizer_step", args=(ANY, 0)),
|
2021-10-28 15:23:27 +00:00
|
|
|
*([dict(name="log_grad_norm", args=ANY)] if not using_deepspeed else []),
|
2021-10-25 16:40:22 +00:00
|
|
|
dict(
|
|
|
|
name="clip_gradients",
|
|
|
|
args=(ANY,),
|
|
|
|
kwargs=dict(gradient_clip_val=None, gradient_clip_algorithm=None),
|
|
|
|
),
|
|
|
|
dict(
|
|
|
|
name="configure_gradient_clipping",
|
|
|
|
args=(ANY, 0),
|
|
|
|
kwargs=dict(gradient_clip_val=None, gradient_clip_algorithm=None),
|
|
|
|
),
|
2021-10-28 15:23:27 +00:00
|
|
|
# this is after because it refers to the `LightningModule.optimizer_step` hook which encapsulates
|
|
|
|
# the actual call to `PrecisionPlugin.optimizer_step`
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(
|
|
|
|
name="optimizer_step",
|
|
|
|
args=(current_epoch, i, ANY, 0, ANY),
|
|
|
|
kwargs=dict(on_tpu=False, using_lbfgs=False, using_native_amp=using_native_amp),
|
|
|
|
),
|
2022-01-12 03:53:49 +00:00
|
|
|
*(
|
|
|
|
[dict(name="lr_scheduler_step", args=(ANY, 0, None))]
|
|
|
|
if i == (trainer.num_training_batches - 1)
|
|
|
|
else []
|
|
|
|
),
|
2021-10-07 10:18:11 +00:00
|
|
|
dict(name="Callback.on_train_batch_end", args=(trainer, model, dict(loss=ANY), ANY, i)),
|
|
|
|
dict(name="on_train_batch_end", args=(dict(loss=ANY), ANY, i)),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_batch_end", args=(trainer, model)),
|
|
|
|
]
|
|
|
|
)
|
2021-06-21 17:27:37 +00:00
|
|
|
return out
|
2021-05-25 11:27:54 +00:00
|
|
|
|
2021-07-09 06:15:57 +00:00
|
|
|
@staticmethod
|
2021-07-26 11:37:35 +00:00
|
|
|
def _manual_train_batch(trainer, model, batches, device=torch.device("cpu"), **kwargs):
|
2021-10-20 15:32:53 +00:00
|
|
|
using_deepspeed = kwargs.get("strategy") == "deepspeed"
|
2021-07-09 06:15:57 +00:00
|
|
|
out = []
|
|
|
|
for i in range(batches):
|
2021-07-26 11:37:35 +00:00
|
|
|
out.extend(
|
|
|
|
[
|
|
|
|
dict(name="on_before_batch_transfer", args=(ANY, 0)),
|
|
|
|
dict(name="transfer_batch_to_device", args=(ANY, device, 0)),
|
|
|
|
dict(name="on_after_batch_transfer", args=(ANY, 0)),
|
|
|
|
dict(name="Callback.on_batch_start", args=(trainer, model)),
|
2021-10-07 10:18:11 +00:00
|
|
|
dict(name="Callback.on_train_batch_start", args=(trainer, model, ANY, i)),
|
|
|
|
dict(name="on_train_batch_start", args=(ANY, i)),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="forward", args=(ANY,)),
|
|
|
|
dict(name="Callback.on_before_backward", args=(trainer, model, ANY)),
|
|
|
|
dict(name="on_before_backward", args=(ANY,)),
|
|
|
|
# DeepSpeed handles backward internally
|
|
|
|
*([dict(name="backward", args=(ANY, None, None))] if not using_deepspeed else []),
|
|
|
|
dict(name="Callback.on_after_backward", args=(trainer, model)),
|
|
|
|
dict(name="on_after_backward"),
|
|
|
|
# `manual_backward` calls the previous 3
|
|
|
|
dict(name="manual_backward", args=(ANY,)),
|
2021-10-29 13:03:04 +00:00
|
|
|
dict(name="closure"),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_before_optimizer_step", args=(trainer, model, ANY, 0)),
|
|
|
|
dict(name="on_before_optimizer_step", args=(ANY, 0)),
|
2021-10-28 15:23:27 +00:00
|
|
|
*([dict(name="log_grad_norm", args=ANY)] if not using_deepspeed else []),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="training_step", args=(ANY, i)),
|
|
|
|
dict(name="training_step_end", args=(dict(loss=ANY),)),
|
2021-10-07 10:18:11 +00:00
|
|
|
dict(name="Callback.on_train_batch_end", args=(trainer, model, dict(loss=ANY), ANY, i)),
|
|
|
|
dict(name="on_train_batch_end", args=(dict(loss=ANY), ANY, i)),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_batch_end", args=(trainer, model)),
|
|
|
|
]
|
|
|
|
)
|
2021-07-09 06:15:57 +00:00
|
|
|
return out
|
|
|
|
|
2021-06-14 16:16:42 +00:00
|
|
|
@staticmethod
|
2021-07-26 11:37:35 +00:00
|
|
|
def _eval_epoch(fn, trainer, model, batches, key, device=torch.device("cpu")):
|
2021-06-18 16:41:27 +00:00
|
|
|
outputs = {key: ANY}
|
2021-06-14 16:16:42 +00:00
|
|
|
return [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_epoch_start", args=(trainer, model)),
|
|
|
|
dict(name="on_epoch_start"),
|
|
|
|
dict(name=f"Callback.on_{fn}_epoch_start", args=(trainer, model)),
|
|
|
|
dict(name=f"on_{fn}_epoch_start"),
|
2021-07-05 10:50:01 +00:00
|
|
|
*HookedModel._eval_batch(fn, trainer, model, batches, key, device=device),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name=f"{fn}_epoch_end", args=([outputs] * batches,)),
|
|
|
|
dict(name=f"Callback.on_{fn}_epoch_end", args=(trainer, model)),
|
|
|
|
dict(name=f"on_{fn}_epoch_end"),
|
|
|
|
dict(name="Callback.on_epoch_end", args=(trainer, model)),
|
|
|
|
dict(name="on_epoch_end"),
|
2021-06-14 16:16:42 +00:00
|
|
|
]
|
2021-03-25 12:51:55 +00:00
|
|
|
|
2021-06-18 16:41:27 +00:00
|
|
|
@staticmethod
|
2021-07-26 11:37:35 +00:00
|
|
|
def _eval_batch(fn, trainer, model, batches, key, device=torch.device("cpu")):
|
2021-06-18 16:41:27 +00:00
|
|
|
out = []
|
|
|
|
outputs = {key: ANY}
|
|
|
|
for i in range(batches):
|
2021-07-26 11:37:35 +00:00
|
|
|
out.extend(
|
|
|
|
[
|
|
|
|
dict(name="on_before_batch_transfer", args=(ANY, 0)),
|
|
|
|
dict(name="transfer_batch_to_device", args=(ANY, device, 0)),
|
|
|
|
dict(name="on_after_batch_transfer", args=(ANY, 0)),
|
|
|
|
dict(name=f"Callback.on_{fn}_batch_start", args=(trainer, model, ANY, i, 0)),
|
|
|
|
dict(name=f"on_{fn}_batch_start", args=(ANY, i, 0)),
|
|
|
|
dict(name="forward", args=(ANY,)),
|
|
|
|
dict(name=f"{fn}_step", args=(ANY, i)),
|
|
|
|
dict(name=f"{fn}_step_end", args=(outputs,)),
|
|
|
|
dict(name=f"Callback.on_{fn}_batch_end", args=(trainer, model, outputs, ANY, i, 0)),
|
|
|
|
dict(name=f"on_{fn}_batch_end", args=(outputs, ANY, i, 0)),
|
|
|
|
]
|
|
|
|
)
|
2021-06-18 16:41:27 +00:00
|
|
|
return out
|
|
|
|
|
2021-06-16 13:09:24 +00:00
|
|
|
@staticmethod
|
|
|
|
def _predict_batch(trainer, model, batches):
|
|
|
|
out = []
|
|
|
|
for i in range(batches):
|
2021-07-26 11:37:35 +00:00
|
|
|
out.extend(
|
|
|
|
[
|
|
|
|
dict(name="on_before_batch_transfer", args=(ANY, 0)),
|
|
|
|
dict(name="transfer_batch_to_device", args=(ANY, torch.device("cpu"), 0)),
|
|
|
|
dict(name="on_after_batch_transfer", args=(ANY, 0)),
|
|
|
|
dict(name="Callback.on_predict_batch_start", args=(trainer, model, ANY, i, 0)),
|
|
|
|
dict(name="on_predict_batch_start", args=(ANY, i, 0)),
|
|
|
|
dict(name="forward", args=(ANY,)),
|
|
|
|
dict(name="predict_step", args=(ANY, i)),
|
|
|
|
# TODO: `predict_step_end`
|
|
|
|
dict(name="Callback.on_predict_batch_end", args=(trainer, model, ANY, ANY, i, 0)),
|
|
|
|
dict(name="on_predict_batch_end", args=(ANY, ANY, i, 0)),
|
|
|
|
]
|
|
|
|
)
|
2021-06-16 13:09:24 +00:00
|
|
|
return out
|
|
|
|
|
2021-01-13 06:09:47 +00:00
|
|
|
|
2021-07-05 10:50:01 +00:00
|
|
|
@pytest.mark.parametrize(
|
2021-07-26 11:37:35 +00:00
|
|
|
"kwargs",
|
2021-07-05 10:50:01 +00:00
|
|
|
[
|
|
|
|
{},
|
|
|
|
# these precision plugins modify the optimization flow, so testing them explicitly
|
2021-09-29 13:34:26 +00:00
|
|
|
pytest.param(dict(gpus=1, precision=16, amp_backend="native"), marks=RunIf(min_gpus=1)),
|
2021-07-26 11:37:35 +00:00
|
|
|
pytest.param(dict(gpus=1, precision=16, amp_backend="apex"), marks=RunIf(amp_apex=True, min_gpus=1)),
|
2022-01-05 19:38:25 +00:00
|
|
|
pytest.param(
|
|
|
|
dict(gpus=1, precision=16, strategy="deepspeed"), marks=RunIf(deepspeed=True, min_gpus=1, standalone=True)
|
|
|
|
),
|
2021-07-26 11:37:35 +00:00
|
|
|
],
|
2021-07-05 10:50:01 +00:00
|
|
|
)
|
2021-07-26 11:37:35 +00:00
|
|
|
@pytest.mark.parametrize("automatic_optimization", (True, False))
|
2021-07-09 06:15:57 +00:00
|
|
|
def test_trainer_model_hook_system_fit(tmpdir, kwargs, automatic_optimization):
|
2021-06-14 16:16:42 +00:00
|
|
|
called = []
|
2021-07-09 06:15:57 +00:00
|
|
|
|
|
|
|
class TestModel(HookedModel):
|
|
|
|
def __init__(self, *args):
|
|
|
|
super().__init__(*args)
|
|
|
|
self.automatic_optimization = automatic_optimization
|
|
|
|
|
|
|
|
def training_step(self, batch, batch_idx):
|
|
|
|
if self.automatic_optimization:
|
|
|
|
return super().training_step(batch, batch_idx)
|
|
|
|
loss = self.step(batch[0])
|
|
|
|
opt = self.optimizers()
|
|
|
|
opt.zero_grad()
|
|
|
|
self.manual_backward(loss)
|
2021-09-07 11:52:20 +00:00
|
|
|
opt.step(lambda: called.append({"name": "closure"}))
|
2021-07-26 11:37:35 +00:00
|
|
|
return {"loss": loss}
|
2021-07-09 06:15:57 +00:00
|
|
|
|
|
|
|
model = TestModel(called)
|
2021-06-21 17:27:37 +00:00
|
|
|
callback = HookedCallback(called)
|
2021-05-25 11:27:54 +00:00
|
|
|
train_batches = 2
|
|
|
|
val_batches = 2
|
2020-10-20 12:33:46 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_epochs=1,
|
2021-05-25 11:27:54 +00:00
|
|
|
limit_train_batches=train_batches,
|
|
|
|
limit_val_batches=val_batches,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2021-10-13 11:50:54 +00:00
|
|
|
enable_model_summary=False,
|
2021-07-05 10:50:01 +00:00
|
|
|
callbacks=[callback],
|
2021-10-28 15:23:27 +00:00
|
|
|
track_grad_norm=1,
|
2021-07-05 10:50:01 +00:00
|
|
|
**kwargs,
|
2020-10-20 12:33:46 +00:00
|
|
|
)
|
2021-06-21 17:27:37 +00:00
|
|
|
assert called == [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_init_start", args=(trainer,)),
|
|
|
|
dict(name="Callback.on_init_end", args=(trainer,)),
|
2021-06-21 17:27:37 +00:00
|
|
|
]
|
2021-11-19 02:04:53 +00:00
|
|
|
trainer.fit(model)
|
2021-06-21 17:27:37 +00:00
|
|
|
saved_ckpt = {
|
2021-07-26 11:37:35 +00:00
|
|
|
"callbacks": ANY,
|
2022-02-10 16:55:59 +00:00
|
|
|
"epoch": 0,
|
2021-07-26 11:37:35 +00:00
|
|
|
"global_step": train_batches,
|
|
|
|
"lr_schedulers": ANY,
|
|
|
|
"optimizer_states": ANY,
|
|
|
|
"pytorch-lightning_version": __version__,
|
|
|
|
"state_dict": ANY,
|
2021-12-17 16:00:27 +00:00
|
|
|
"loops": ANY,
|
2021-06-21 17:27:37 +00:00
|
|
|
}
|
2021-07-26 11:37:35 +00:00
|
|
|
if kwargs.get("amp_backend") == "native":
|
|
|
|
saved_ckpt["native_amp_scaling_state"] = ANY
|
|
|
|
elif kwargs.get("amp_backend") == "apex":
|
|
|
|
saved_ckpt["amp_scaling_state"] = ANY
|
|
|
|
device = torch.device("cuda:0" if "gpus" in kwargs else "cpu")
|
2020-11-05 22:27:04 +00:00
|
|
|
expected = [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_init_start", args=(trainer,)),
|
|
|
|
dict(name="Callback.on_init_end", args=(trainer,)),
|
|
|
|
dict(name="configure_callbacks"),
|
2021-12-14 18:41:29 +00:00
|
|
|
dict(name="prepare_data"),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_before_accelerator_backend_setup", args=(trainer, model)),
|
2021-07-05 10:50:01 +00:00
|
|
|
# DeepSpeed needs the batch size to figure out throughput logging
|
2021-10-20 15:32:53 +00:00
|
|
|
*([dict(name="train_dataloader")] if kwargs.get("strategy") == "deepspeed" else []),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.setup", args=(trainer, model), kwargs=dict(stage="fit")),
|
|
|
|
dict(name="setup", kwargs=dict(stage="fit")),
|
|
|
|
dict(name="configure_sharded_model"),
|
|
|
|
dict(name="Callback.on_configure_sharded_model", args=(trainer, model)),
|
2021-12-20 16:41:22 +00:00
|
|
|
dict(name="configure_optimizers"),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_fit_start", args=(trainer, model)),
|
|
|
|
dict(name="on_fit_start"),
|
|
|
|
dict(name="Callback.on_pretrain_routine_start", args=(trainer, model)),
|
|
|
|
dict(name="on_pretrain_routine_start"),
|
|
|
|
dict(name="Callback.on_pretrain_routine_end", args=(trainer, model)),
|
|
|
|
dict(name="on_pretrain_routine_end"),
|
|
|
|
dict(name="Callback.on_sanity_check_start", args=(trainer, model)),
|
|
|
|
dict(name="on_val_dataloader"),
|
|
|
|
dict(name="val_dataloader"),
|
|
|
|
dict(name="train", args=(False,)),
|
|
|
|
dict(name="on_validation_model_eval"),
|
|
|
|
dict(name="zero_grad"),
|
|
|
|
dict(name="Callback.on_validation_start", args=(trainer, model)),
|
|
|
|
dict(name="on_validation_start"),
|
|
|
|
*model._eval_epoch("validation", trainer, model, val_batches, "x", device=device),
|
|
|
|
dict(name="Callback.on_validation_end", args=(trainer, model)),
|
|
|
|
dict(name="on_validation_end"),
|
|
|
|
dict(name="train", args=(True,)),
|
|
|
|
dict(name="on_validation_model_train"),
|
|
|
|
dict(name="Callback.on_sanity_check_end", args=(trainer, model)),
|
2021-06-14 16:16:42 +00:00
|
|
|
# duplicate `train` because `_run_train` calls it again in case validation wasn't run
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="train", args=(True,)),
|
|
|
|
dict(name="on_train_dataloader"),
|
|
|
|
dict(name="train_dataloader"),
|
|
|
|
dict(name="Callback.on_train_start", args=(trainer, model)),
|
|
|
|
dict(name="on_train_start"),
|
|
|
|
dict(name="Callback.on_epoch_start", args=(trainer, model)),
|
|
|
|
dict(name="on_epoch_start"),
|
|
|
|
dict(name="Callback.on_train_epoch_start", args=(trainer, model)),
|
|
|
|
dict(name="on_train_epoch_start"),
|
2021-07-05 10:50:01 +00:00
|
|
|
*model._train_batch(trainer, model, train_batches, device=device, **kwargs),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="train", args=(False,)),
|
|
|
|
dict(name="on_validation_model_eval"),
|
|
|
|
dict(name="zero_grad"),
|
|
|
|
dict(name="Callback.on_validation_start", args=(trainer, model)),
|
|
|
|
dict(name="on_validation_start"),
|
|
|
|
*model._eval_epoch("validation", trainer, model, val_batches, "x", device=device),
|
|
|
|
dict(name="Callback.on_validation_end", args=(trainer, model)),
|
|
|
|
dict(name="on_validation_end"),
|
|
|
|
dict(name="train", args=(True,)),
|
|
|
|
dict(name="on_validation_model_train"),
|
|
|
|
dict(name="training_epoch_end", args=([dict(loss=ANY)] * train_batches,)),
|
2021-07-28 16:27:54 +00:00
|
|
|
dict(name="Callback.on_train_epoch_end", args=(trainer, model)),
|
2021-07-13 14:47:59 +00:00
|
|
|
# `ModelCheckpoint.save_checkpoint` is called here from `Callback.on_train_epoch_end`
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_save_checkpoint", args=(trainer, model, saved_ckpt)),
|
|
|
|
dict(name="on_save_checkpoint", args=(saved_ckpt,)),
|
2021-07-28 16:27:54 +00:00
|
|
|
dict(name="on_train_epoch_end"),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_epoch_end", args=(trainer, model)),
|
|
|
|
dict(name="on_epoch_end"),
|
|
|
|
dict(name="Callback.on_train_end", args=(trainer, model)),
|
|
|
|
dict(name="on_train_end"),
|
|
|
|
dict(name="Callback.on_fit_end", args=(trainer, model)),
|
|
|
|
dict(name="on_fit_end"),
|
|
|
|
dict(name="Callback.teardown", args=(trainer, model), kwargs=dict(stage="fit")),
|
|
|
|
dict(name="teardown", kwargs=dict(stage="fit")),
|
2020-10-20 12:33:46 +00:00
|
|
|
]
|
2021-06-14 16:16:42 +00:00
|
|
|
assert called == expected
|
2021-03-11 02:46:37 +00:00
|
|
|
|
2020-10-20 12:33:46 +00:00
|
|
|
|
2021-06-17 08:13:53 +00:00
|
|
|
def test_trainer_model_hook_system_fit_no_val_and_resume(tmpdir):
|
|
|
|
# initial training to get a checkpoint
|
|
|
|
model = BoringModel()
|
|
|
|
trainer = Trainer(
|
2021-07-29 10:28:29 +00:00
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_steps=1,
|
|
|
|
limit_val_batches=0,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2021-10-13 11:50:54 +00:00
|
|
|
enable_model_summary=False,
|
2021-07-29 10:28:29 +00:00
|
|
|
callbacks=[HookedCallback([])],
|
2021-06-17 08:13:53 +00:00
|
|
|
)
|
2021-11-19 02:04:53 +00:00
|
|
|
trainer.fit(model)
|
2021-06-17 08:13:53 +00:00
|
|
|
best_model_path = trainer.checkpoint_callback.best_model_path
|
|
|
|
|
|
|
|
# resume from checkpoint with HookedModel
|
2021-06-14 16:16:42 +00:00
|
|
|
called = []
|
|
|
|
model = HookedModel(called)
|
2021-06-23 07:34:00 +00:00
|
|
|
callback = HookedCallback(called)
|
2021-11-30 14:07:04 +00:00
|
|
|
|
|
|
|
# already performed 1 step, resume and do 2 more
|
2021-05-25 11:27:54 +00:00
|
|
|
train_batches = 2
|
2021-11-30 14:07:04 +00:00
|
|
|
steps_after_reload = 1 + train_batches
|
2021-05-25 11:27:54 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
2021-11-30 14:07:04 +00:00
|
|
|
max_steps=steps_after_reload,
|
2021-05-25 11:27:54 +00:00
|
|
|
limit_val_batches=0,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2021-10-13 11:50:54 +00:00
|
|
|
enable_model_summary=False,
|
2021-07-26 11:37:35 +00:00
|
|
|
callbacks=[callback],
|
2021-10-28 15:23:27 +00:00
|
|
|
track_grad_norm=1,
|
2021-05-25 11:27:54 +00:00
|
|
|
)
|
2021-06-23 07:34:00 +00:00
|
|
|
assert called == [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_init_start", args=(trainer,)),
|
|
|
|
dict(name="Callback.on_init_end", args=(trainer,)),
|
2021-06-23 07:34:00 +00:00
|
|
|
]
|
2021-11-30 14:07:04 +00:00
|
|
|
|
2021-11-19 02:04:53 +00:00
|
|
|
trainer.fit(model, ckpt_path=best_model_path)
|
2021-11-30 14:07:04 +00:00
|
|
|
loaded_ckpt = {
|
2021-07-26 11:37:35 +00:00
|
|
|
"callbacks": ANY,
|
2022-02-10 16:55:59 +00:00
|
|
|
"epoch": 0,
|
2021-11-30 14:07:04 +00:00
|
|
|
"global_step": 1,
|
2021-07-26 11:37:35 +00:00
|
|
|
"lr_schedulers": ANY,
|
|
|
|
"optimizer_states": ANY,
|
|
|
|
"pytorch-lightning_version": __version__,
|
|
|
|
"state_dict": ANY,
|
2021-12-17 16:00:27 +00:00
|
|
|
"loops": ANY,
|
2021-06-23 07:34:00 +00:00
|
|
|
}
|
2022-02-10 16:55:59 +00:00
|
|
|
saved_ckpt = {**loaded_ckpt, "global_step": steps_after_reload, "epoch": 1}
|
2021-05-25 11:27:54 +00:00
|
|
|
expected = [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_init_start", args=(trainer,)),
|
|
|
|
dict(name="Callback.on_init_end", args=(trainer,)),
|
|
|
|
dict(name="configure_callbacks"),
|
2021-12-14 18:41:29 +00:00
|
|
|
dict(name="prepare_data"),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_before_accelerator_backend_setup", args=(trainer, model)),
|
|
|
|
dict(name="Callback.setup", args=(trainer, model), kwargs=dict(stage="fit")),
|
|
|
|
dict(name="setup", kwargs=dict(stage="fit")),
|
2021-11-30 14:07:04 +00:00
|
|
|
dict(name="on_load_checkpoint", args=(loaded_ckpt,)),
|
2021-07-29 10:28:29 +00:00
|
|
|
dict(name="Callback.on_load_checkpoint", args=(trainer, model, {"foo": True})),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="configure_sharded_model"),
|
|
|
|
dict(name="Callback.on_configure_sharded_model", args=(trainer, model)),
|
|
|
|
dict(name="configure_optimizers"),
|
|
|
|
dict(name="Callback.on_fit_start", args=(trainer, model)),
|
|
|
|
dict(name="on_fit_start"),
|
|
|
|
dict(name="Callback.on_pretrain_routine_start", args=(trainer, model)),
|
|
|
|
dict(name="on_pretrain_routine_start"),
|
|
|
|
dict(name="Callback.on_pretrain_routine_end", args=(trainer, model)),
|
|
|
|
dict(name="on_pretrain_routine_end"),
|
|
|
|
dict(name="train", args=(True,)),
|
|
|
|
dict(name="on_train_dataloader"),
|
|
|
|
dict(name="train_dataloader"),
|
2021-06-14 16:16:42 +00:00
|
|
|
# even though no validation runs, we initialize the val dataloader for properties like `num_val_batches`
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="on_val_dataloader"),
|
|
|
|
dict(name="val_dataloader"),
|
|
|
|
dict(name="Callback.on_train_start", args=(trainer, model)),
|
|
|
|
dict(name="on_train_start"),
|
|
|
|
dict(name="Callback.on_epoch_start", args=(trainer, model)),
|
|
|
|
dict(name="on_epoch_start"),
|
|
|
|
dict(name="Callback.on_train_epoch_start", args=(trainer, model)),
|
|
|
|
dict(name="on_train_epoch_start"),
|
2022-02-10 16:55:59 +00:00
|
|
|
*model._train_batch(trainer, model, steps_after_reload, current_batch=1, current_epoch=1),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="training_epoch_end", args=([dict(loss=ANY)] * train_batches,)),
|
2021-07-28 16:27:54 +00:00
|
|
|
dict(name="Callback.on_train_epoch_end", args=(trainer, model)),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_save_checkpoint", args=(trainer, model, saved_ckpt)),
|
|
|
|
dict(name="on_save_checkpoint", args=(saved_ckpt,)),
|
2021-07-28 16:27:54 +00:00
|
|
|
dict(name="on_train_epoch_end"),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_epoch_end", args=(trainer, model)),
|
|
|
|
dict(name="on_epoch_end"),
|
|
|
|
dict(name="Callback.on_train_end", args=(trainer, model)),
|
|
|
|
dict(name="on_train_end"),
|
|
|
|
dict(name="Callback.on_fit_end", args=(trainer, model)),
|
|
|
|
dict(name="on_fit_end"),
|
|
|
|
dict(name="Callback.teardown", args=(trainer, model), kwargs=dict(stage="fit")),
|
|
|
|
dict(name="teardown", kwargs=dict(stage="fit")),
|
2021-05-25 11:27:54 +00:00
|
|
|
]
|
2021-06-14 16:16:42 +00:00
|
|
|
assert called == expected
|
2021-05-25 11:27:54 +00:00
|
|
|
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
@pytest.mark.parametrize("batches", (0, 2))
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
["verb", "noun", "dataloader", "key"], [("validate", "validation", "val", "x"), ("test", "test", "test", "y")]
|
|
|
|
)
|
2021-06-18 16:41:27 +00:00
|
|
|
def test_trainer_model_hook_system_eval(tmpdir, batches, verb, noun, dataloader, key):
|
2021-06-14 16:16:42 +00:00
|
|
|
called = []
|
|
|
|
model = HookedModel(called)
|
2021-06-18 16:41:27 +00:00
|
|
|
callback = HookedCallback(called)
|
2021-05-24 22:26:32 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_epochs=1,
|
2021-06-14 16:16:42 +00:00
|
|
|
limit_val_batches=batches,
|
2021-06-18 16:41:27 +00:00
|
|
|
limit_test_batches=batches,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2021-10-13 11:50:54 +00:00
|
|
|
enable_model_summary=False,
|
2021-06-18 16:41:27 +00:00
|
|
|
callbacks=[callback],
|
2021-05-24 22:26:32 +00:00
|
|
|
)
|
2021-06-18 16:41:27 +00:00
|
|
|
assert called == [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_init_start", args=(trainer,)),
|
|
|
|
dict(name="Callback.on_init_end", args=(trainer,)),
|
2021-06-18 16:41:27 +00:00
|
|
|
]
|
|
|
|
fn = getattr(trainer, verb)
|
2021-11-19 02:04:53 +00:00
|
|
|
fn(model, verbose=False)
|
2021-06-14 16:16:42 +00:00
|
|
|
hooks = [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="train", args=(False,)),
|
|
|
|
dict(name=f"on_{noun}_model_eval"),
|
|
|
|
dict(name="zero_grad"),
|
|
|
|
dict(name=f"Callback.on_{noun}_start", args=(trainer, model)),
|
|
|
|
dict(name=f"on_{noun}_start"),
|
2021-06-18 16:41:27 +00:00
|
|
|
*model._eval_epoch(noun, trainer, model, batches, key),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name=f"Callback.on_{noun}_end", args=(trainer, model)),
|
|
|
|
dict(name=f"on_{noun}_end"),
|
|
|
|
dict(name="train", args=(True,)),
|
|
|
|
dict(name=f"on_{noun}_model_train"),
|
2021-03-11 02:46:37 +00:00
|
|
|
]
|
2021-06-14 16:16:42 +00:00
|
|
|
expected = [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_init_start", args=(trainer,)),
|
|
|
|
dict(name="Callback.on_init_end", args=(trainer,)),
|
|
|
|
dict(name="configure_callbacks"),
|
2021-12-14 18:41:29 +00:00
|
|
|
dict(name="prepare_data"),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_before_accelerator_backend_setup", args=(trainer, model)),
|
|
|
|
dict(name="Callback.setup", args=(trainer, model), kwargs=dict(stage=verb)),
|
|
|
|
dict(name="setup", kwargs=dict(stage=verb)),
|
|
|
|
dict(name="configure_sharded_model"),
|
|
|
|
dict(name="Callback.on_configure_sharded_model", args=(trainer, model)),
|
|
|
|
dict(name=f"on_{dataloader}_dataloader"),
|
|
|
|
dict(name=f"{dataloader}_dataloader"),
|
2021-06-14 16:16:42 +00:00
|
|
|
*(hooks if batches else []),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.teardown", args=(trainer, model), kwargs=dict(stage=verb)),
|
|
|
|
dict(name="teardown", kwargs=dict(stage=verb)),
|
2020-10-20 12:33:46 +00:00
|
|
|
]
|
2021-06-14 16:16:42 +00:00
|
|
|
assert called == expected
|
2021-03-25 12:51:55 +00:00
|
|
|
|
|
|
|
|
2021-06-16 13:09:24 +00:00
|
|
|
def test_trainer_model_hook_system_predict(tmpdir):
|
|
|
|
called = []
|
|
|
|
model = HookedModel(called)
|
|
|
|
callback = HookedCallback(called)
|
|
|
|
batches = 2
|
|
|
|
trainer = Trainer(
|
2021-09-25 05:53:31 +00:00
|
|
|
default_root_dir=tmpdir, limit_predict_batches=batches, enable_progress_bar=False, callbacks=[callback]
|
2021-06-16 13:09:24 +00:00
|
|
|
)
|
|
|
|
assert called == [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_init_start", args=(trainer,)),
|
|
|
|
dict(name="Callback.on_init_end", args=(trainer,)),
|
2021-06-16 13:09:24 +00:00
|
|
|
]
|
2021-11-19 02:04:53 +00:00
|
|
|
trainer.predict(model)
|
2021-06-16 13:09:24 +00:00
|
|
|
expected = [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_init_start", args=(trainer,)),
|
|
|
|
dict(name="Callback.on_init_end", args=(trainer,)),
|
|
|
|
dict(name="configure_callbacks"),
|
2021-12-14 18:41:29 +00:00
|
|
|
dict(name="prepare_data"),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_before_accelerator_backend_setup", args=(trainer, model)),
|
|
|
|
dict(name="Callback.setup", args=(trainer, model), kwargs=dict(stage="predict")),
|
|
|
|
dict(name="setup", kwargs=dict(stage="predict")),
|
|
|
|
dict(name="configure_sharded_model"),
|
|
|
|
dict(name="Callback.on_configure_sharded_model", args=(trainer, model)),
|
|
|
|
dict(name="on_predict_dataloader"),
|
|
|
|
dict(name="predict_dataloader"),
|
|
|
|
dict(name="train", args=(False,)),
|
|
|
|
dict(name="on_predict_model_eval"),
|
|
|
|
dict(name="zero_grad"),
|
|
|
|
dict(name="Callback.on_predict_start", args=(trainer, model)),
|
|
|
|
dict(name="on_predict_start"),
|
|
|
|
dict(name="Callback.on_predict_epoch_start", args=(trainer, model)),
|
|
|
|
dict(name="on_predict_epoch_start"),
|
2021-06-16 13:09:24 +00:00
|
|
|
*model._predict_batch(trainer, model, batches),
|
|
|
|
# TODO: `predict_epoch_end`
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.on_predict_epoch_end", args=(trainer, model, [[ANY] * batches])),
|
|
|
|
dict(name="on_predict_epoch_end", args=([[ANY] * batches],)),
|
|
|
|
dict(name="Callback.on_predict_end", args=(trainer, model)),
|
|
|
|
dict(name="on_predict_end"),
|
2021-06-16 13:09:24 +00:00
|
|
|
# TODO: `on_predict_model_train`
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="Callback.teardown", args=(trainer, model), kwargs=dict(stage="predict")),
|
|
|
|
dict(name="teardown", kwargs=dict(stage="predict")),
|
2021-06-16 13:09:24 +00:00
|
|
|
]
|
|
|
|
assert called == expected
|
|
|
|
|
|
|
|
|
|
|
|
# TODO: add test for tune
|
|
|
|
|
|
|
|
|
2021-05-13 17:33:55 +00:00
|
|
|
def test_hooks_with_different_argument_names(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test that argument names can be anything in the hooks."""
|
2021-05-13 17:33:55 +00:00
|
|
|
|
|
|
|
class CustomBoringModel(BoringModel):
|
|
|
|
def assert_args(self, x, batch_nb):
|
|
|
|
assert isinstance(x, torch.Tensor)
|
|
|
|
assert x.size() == (1, 32)
|
|
|
|
assert isinstance(batch_nb, int)
|
|
|
|
|
|
|
|
def training_step(self, x1, batch_nb1):
|
|
|
|
self.assert_args(x1, batch_nb1)
|
|
|
|
return super().training_step(x1, batch_nb1)
|
|
|
|
|
|
|
|
def validation_step(self, x2, batch_nb2):
|
|
|
|
self.assert_args(x2, batch_nb2)
|
|
|
|
return super().validation_step(x2, batch_nb2)
|
|
|
|
|
|
|
|
def test_step(self, x3, batch_nb3, dl_idx3):
|
|
|
|
self.assert_args(x3, batch_nb3)
|
|
|
|
assert isinstance(dl_idx3, int)
|
|
|
|
return super().test_step(x3, batch_nb3)
|
|
|
|
|
|
|
|
def predict(self, x4, batch_nb4, dl_idx4):
|
|
|
|
self.assert_args(x4, batch_nb4)
|
|
|
|
assert isinstance(dl_idx4, int)
|
|
|
|
return super().predict(x4, batch_nb4, dl_idx4)
|
|
|
|
|
|
|
|
def test_dataloader(self):
|
|
|
|
return [DataLoader(RandomDataset(32, 64)), DataLoader(RandomDataset(32, 64))]
|
|
|
|
|
|
|
|
def predict_dataloader(self):
|
|
|
|
return [DataLoader(RandomDataset(32, 64)), DataLoader(RandomDataset(32, 64))]
|
|
|
|
|
|
|
|
model = CustomBoringModel()
|
|
|
|
model.test_epoch_end = None
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=5)
|
2021-05-13 17:33:55 +00:00
|
|
|
|
|
|
|
trainer.fit(model)
|
|
|
|
assert trainer.state.finished, f"Training failed with {trainer.state}"
|
2021-07-28 10:12:46 +00:00
|
|
|
trainer.test(model)
|
2021-05-13 17:33:55 +00:00
|
|
|
|
|
|
|
preds = trainer.predict(model)
|
|
|
|
assert len(preds) == 2
|
|
|
|
assert all(len(x) == 5 for x in preds)
|
|
|
|
|
|
|
|
|
2021-03-25 12:51:55 +00:00
|
|
|
def test_trainer_datamodule_hook_system(tmpdir):
|
|
|
|
"""Test the LightningDataModule hook system."""
|
|
|
|
|
|
|
|
class HookedDataModule(BoringDataModule):
|
2021-06-14 12:42:13 +00:00
|
|
|
def __init__(self, called):
|
2021-03-25 12:51:55 +00:00
|
|
|
super().__init__()
|
|
|
|
|
2021-06-14 12:42:13 +00:00
|
|
|
def call(hook, fn, *args, **kwargs):
|
|
|
|
out = fn(*args, **kwargs)
|
2021-07-26 11:37:35 +00:00
|
|
|
d = {"name": hook}
|
2021-06-14 12:42:13 +00:00
|
|
|
if args:
|
2021-07-26 11:37:35 +00:00
|
|
|
d["args"] = args
|
2021-06-14 12:42:13 +00:00
|
|
|
if kwargs:
|
2021-07-26 11:37:35 +00:00
|
|
|
d["kwargs"] = kwargs
|
2021-06-14 12:42:13 +00:00
|
|
|
called.append(d)
|
|
|
|
return out
|
|
|
|
|
2021-06-14 16:16:42 +00:00
|
|
|
for h in get_members(LightningDataModule):
|
2021-06-14 12:42:13 +00:00
|
|
|
attr = getattr(self, h)
|
2021-11-19 00:52:55 +00:00
|
|
|
partial_h = partial(call, h, attr)
|
|
|
|
update_wrapper(partial_h, attr)
|
|
|
|
setattr(self, h, partial_h)
|
2021-03-25 12:51:55 +00:00
|
|
|
|
|
|
|
model = BoringModel()
|
2021-06-14 12:42:13 +00:00
|
|
|
batches = 2
|
2021-03-25 12:51:55 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_epochs=1,
|
2021-06-14 12:42:13 +00:00
|
|
|
limit_train_batches=batches,
|
|
|
|
limit_val_batches=batches,
|
|
|
|
limit_test_batches=batches,
|
|
|
|
limit_predict_batches=batches,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2021-10-13 11:50:54 +00:00
|
|
|
enable_model_summary=False,
|
2021-11-22 19:32:04 +00:00
|
|
|
reload_dataloaders_every_n_epochs=1,
|
2021-03-25 12:51:55 +00:00
|
|
|
)
|
2021-06-14 12:42:13 +00:00
|
|
|
|
|
|
|
called = []
|
|
|
|
dm = HookedDataModule(called)
|
2021-03-25 12:51:55 +00:00
|
|
|
trainer.fit(model, datamodule=dm)
|
|
|
|
expected = [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="prepare_data"),
|
|
|
|
dict(name="setup", kwargs=dict(stage="fit")),
|
|
|
|
dict(name="val_dataloader"),
|
|
|
|
dict(name="train_dataloader"),
|
2022-02-07 20:13:24 +00:00
|
|
|
dict(name="state_dict"),
|
2021-11-30 14:07:04 +00:00
|
|
|
dict(name="on_save_checkpoint", args=(ANY,)),
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="teardown", kwargs=dict(stage="fit")),
|
2021-03-25 12:51:55 +00:00
|
|
|
]
|
2021-06-14 12:42:13 +00:00
|
|
|
assert called == expected
|
2021-03-25 12:51:55 +00:00
|
|
|
|
2021-06-14 12:42:13 +00:00
|
|
|
called = []
|
|
|
|
dm = HookedDataModule(called)
|
2021-03-25 12:51:55 +00:00
|
|
|
trainer.validate(model, datamodule=dm, verbose=False)
|
|
|
|
expected = [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="prepare_data"),
|
|
|
|
dict(name="setup", kwargs=dict(stage="validate")),
|
|
|
|
dict(name="val_dataloader"),
|
|
|
|
dict(name="teardown", kwargs=dict(stage="validate")),
|
2021-03-25 12:51:55 +00:00
|
|
|
]
|
2021-06-14 12:42:13 +00:00
|
|
|
assert called == expected
|
2021-03-25 12:51:55 +00:00
|
|
|
|
2021-06-14 12:42:13 +00:00
|
|
|
called = []
|
|
|
|
dm = HookedDataModule(called)
|
2021-03-25 12:51:55 +00:00
|
|
|
trainer.test(model, datamodule=dm, verbose=False)
|
|
|
|
expected = [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="prepare_data"),
|
|
|
|
dict(name="setup", kwargs=dict(stage="test")),
|
|
|
|
dict(name="test_dataloader"),
|
|
|
|
dict(name="teardown", kwargs=dict(stage="test")),
|
2021-06-14 12:42:13 +00:00
|
|
|
]
|
|
|
|
assert called == expected
|
|
|
|
|
|
|
|
called = []
|
|
|
|
dm = HookedDataModule(called)
|
|
|
|
trainer.predict(model, datamodule=dm)
|
|
|
|
expected = [
|
2021-07-26 11:37:35 +00:00
|
|
|
dict(name="prepare_data"),
|
|
|
|
dict(name="setup", kwargs=dict(stage="predict")),
|
|
|
|
dict(name="predict_dataloader"),
|
|
|
|
dict(name="teardown", kwargs=dict(stage="predict")),
|
2021-03-25 12:51:55 +00:00
|
|
|
]
|
2021-06-14 12:42:13 +00:00
|
|
|
assert called == expected
|