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.
|
2020-04-22 21:39:08 +00:00
|
|
|
import json
|
|
|
|
import os
|
|
|
|
import shlex
|
|
|
|
import subprocess
|
|
|
|
import sys
|
2021-03-14 17:14:27 +00:00
|
|
|
from unittest.mock import patch
|
2020-07-23 16:14:57 +00:00
|
|
|
|
2020-11-05 17:52:02 +00:00
|
|
|
import numpy as np
|
2020-04-22 21:39:08 +00:00
|
|
|
import pytest
|
2021-01-08 21:13:12 +00:00
|
|
|
import torch
|
2021-01-23 23:52:04 +00:00
|
|
|
from sklearn.metrics import accuracy_score
|
2021-03-14 17:14:27 +00:00
|
|
|
from torch import optim
|
2021-07-28 16:57:31 +00:00
|
|
|
from torchmetrics.classification.accuracy import Accuracy
|
2020-11-05 17:52:02 +00:00
|
|
|
|
2021-02-08 10:52:02 +00:00
|
|
|
import tests.helpers.pipelines as tpipes
|
|
|
|
import tests.helpers.utils as tutils
|
2020-05-10 17:15:28 +00:00
|
|
|
from pytorch_lightning import Trainer
|
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 pytorch_lightning.accelerators import CPUAccelerator
|
2021-03-02 12:43:53 +00:00
|
|
|
from pytorch_lightning.utilities import _HOROVOD_AVAILABLE
|
2022-02-19 01:54:04 +00:00
|
|
|
from pytorch_lightning.utilities.exceptions import MisconfigurationException
|
2021-02-11 14:32:07 +00:00
|
|
|
from tests.helpers import BoringModel
|
2021-02-09 10:10:52 +00:00
|
|
|
from tests.helpers.advanced_models import BasicGAN
|
2021-03-02 09:36:01 +00:00
|
|
|
from tests.helpers.runif import RunIf
|
2020-04-22 21:39:08 +00:00
|
|
|
|
2020-12-14 14:49:05 +00:00
|
|
|
if _HOROVOD_AVAILABLE:
|
2020-11-05 17:52:02 +00:00
|
|
|
import horovod
|
2020-12-04 09:26:10 +00:00
|
|
|
import horovod.torch as hvd
|
2020-04-22 21:39:08 +00:00
|
|
|
|
2022-02-28 10:45:32 +00:00
|
|
|
|
|
|
|
@RunIf(min_gpus=1, horovod=True)
|
|
|
|
@pytest.mark.xfail(reason="FIXME(@Borda): nccl is not available in the GPU image")
|
|
|
|
def test_nccl_is_available_on_gpu_environment():
|
|
|
|
from tests.helpers.runif import _HOROVOD_NCCL_AVAILABLE
|
|
|
|
|
|
|
|
# the GPU environment should always install Horovod NCCL
|
|
|
|
assert _HOROVOD_NCCL_AVAILABLE
|
|
|
|
|
|
|
|
|
2020-04-22 21:39:08 +00:00
|
|
|
# This script will run the actual test model training in parallel
|
2021-07-26 11:37:35 +00:00
|
|
|
TEST_SCRIPT = os.path.join(os.path.dirname(__file__), "data", "horovod", "train_default_model.py")
|
2020-04-22 21:39:08 +00:00
|
|
|
|
|
|
|
|
2022-02-19 01:54:04 +00:00
|
|
|
def _run_horovod(trainer_options):
|
2020-04-22 21:39:08 +00:00
|
|
|
"""Execute the training script across multiple workers in parallel."""
|
2022-02-19 01:54:04 +00:00
|
|
|
devices = trainer_options.get("devices", 1)
|
2020-05-12 11:53:20 +00:00
|
|
|
tutils.reset_seed()
|
2021-04-09 19:06:47 +00:00
|
|
|
# TODO: Find out why coverage breaks CI.
|
2021-04-06 13:27:37 +00:00
|
|
|
# append = '-a' if '.coverage' in os.listdir(_PROJECT_ROOT) else ''
|
2021-04-09 19:06:47 +00:00
|
|
|
# str(num_processes), sys.executable, '-m', 'coverage', 'run', '--source', 'pytorch_lightning', append,
|
2020-05-02 12:38:22 +00:00
|
|
|
cmdline = [
|
2021-07-26 11:37:35 +00:00
|
|
|
"horovodrun",
|
|
|
|
"-np",
|
2022-02-19 01:54:04 +00:00
|
|
|
str(devices),
|
2021-07-26 11:37:35 +00:00
|
|
|
sys.executable,
|
|
|
|
TEST_SCRIPT,
|
|
|
|
"--trainer-options",
|
|
|
|
shlex.quote(json.dumps(trainer_options)),
|
2020-05-02 12:38:22 +00:00
|
|
|
]
|
2022-02-19 01:54:04 +00:00
|
|
|
if trainer_options.get("accelerator", "cpu") == "gpu":
|
2021-07-26 11:37:35 +00:00
|
|
|
cmdline += ["--on-gpu"]
|
|
|
|
exit_code = subprocess.call(" ".join(cmdline), shell=True, env=os.environ.copy())
|
2020-04-22 21:39:08 +00:00
|
|
|
assert exit_code == 0
|
|
|
|
|
|
|
|
|
2021-11-16 04:36:47 +00:00
|
|
|
@RunIf(skip_windows=True, horovod=True, skip_49370=True)
|
2021-01-08 21:13:12 +00:00
|
|
|
def test_horovod_cpu(tmpdir):
|
2020-04-22 21:39:08 +00:00
|
|
|
"""Test Horovod running multi-process on CPU."""
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=str(tmpdir),
|
|
|
|
gradient_clip_val=1.0,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2020-04-22 21:39:08 +00:00
|
|
|
max_epochs=1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.4,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.2,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="horovod",
|
2020-04-22 21:39:08 +00:00
|
|
|
)
|
|
|
|
_run_horovod(trainer_options)
|
|
|
|
|
|
|
|
|
2022-02-19 01:54:04 +00:00
|
|
|
@RunIf(skip_windows=True, horovod=True, skip_49370=True)
|
|
|
|
def test_horovod_cpu_accumulate_grad_batches(tmpdir):
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
enable_progress_bar=False,
|
|
|
|
max_epochs=1,
|
|
|
|
limit_train_batches=4,
|
|
|
|
limit_val_batches=0,
|
|
|
|
accumulate_grad_batches=2,
|
|
|
|
strategy="horovod",
|
|
|
|
)
|
|
|
|
_run_horovod(trainer_options)
|
|
|
|
|
|
|
|
|
2021-11-16 04:36:47 +00:00
|
|
|
@RunIf(skip_windows=True, horovod=True, skip_49370=True)
|
2021-04-06 13:27:37 +00:00
|
|
|
def test_horovod_cpu_clip_grad_by_value(tmpdir):
|
|
|
|
"""Test Horovod running multi-process on CPU."""
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=str(tmpdir),
|
|
|
|
gradient_clip_val=1.0,
|
2021-07-26 11:37:35 +00:00
|
|
|
gradient_clip_algorithm="value",
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2021-04-06 13:27:37 +00:00
|
|
|
max_epochs=1,
|
|
|
|
limit_train_batches=0.4,
|
|
|
|
limit_val_batches=0.2,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="horovod",
|
2021-04-06 13:27:37 +00:00
|
|
|
)
|
|
|
|
_run_horovod(trainer_options)
|
|
|
|
|
|
|
|
|
2021-11-16 04:36:47 +00:00
|
|
|
@RunIf(skip_windows=True, horovod=True, skip_49370=True)
|
2021-01-08 21:13:12 +00:00
|
|
|
def test_horovod_cpu_implicit(tmpdir):
|
2020-04-22 21:39:08 +00:00
|
|
|
"""Test Horovod without specifying a backend, inferring from env set by `horovodrun`."""
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=str(tmpdir),
|
|
|
|
gradient_clip_val=1.0,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2020-04-22 21:39:08 +00:00
|
|
|
max_epochs=1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.4,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.2,
|
2020-04-22 21:39:08 +00:00
|
|
|
)
|
|
|
|
_run_horovod(trainer_options)
|
|
|
|
|
|
|
|
|
2021-03-02 16:21:20 +00:00
|
|
|
@RunIf(min_gpus=2, skip_windows=True, horovod_nccl=True)
|
2020-04-22 21:39:08 +00:00
|
|
|
def test_horovod_multi_gpu(tmpdir):
|
|
|
|
"""Test Horovod with multi-GPU support."""
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=str(tmpdir),
|
|
|
|
gradient_clip_val=1.0,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2020-04-22 21:39:08 +00:00
|
|
|
max_epochs=1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.4,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.2,
|
2022-02-19 01:54:04 +00:00
|
|
|
accelerator="gpu",
|
|
|
|
devices=2,
|
|
|
|
strategy="horovod",
|
|
|
|
)
|
|
|
|
_run_horovod(trainer_options)
|
|
|
|
|
|
|
|
|
|
|
|
@RunIf(min_gpus=2, skip_windows=True, horovod_nccl=True)
|
|
|
|
def test_horovod_multi_gpu_accumulate_grad_batches(tmpdir):
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
enable_progress_bar=False,
|
|
|
|
max_epochs=1,
|
|
|
|
limit_train_batches=4,
|
|
|
|
limit_val_batches=0,
|
|
|
|
accumulate_grad_batches=2,
|
|
|
|
accelerator="gpu",
|
|
|
|
devices=2,
|
|
|
|
strategy="horovod",
|
|
|
|
)
|
|
|
|
_run_horovod(trainer_options)
|
|
|
|
|
|
|
|
|
|
|
|
@RunIf(horovod=True, skip_windows=True)
|
|
|
|
def test_horovod_raises_unsupported_accumulate_grad_batches(tmpdir):
|
|
|
|
"""Ensure MisConfigurationException for different `accumulate_grad_batches` at different epochs for Horovod
|
|
|
|
Strategy on multi-gpus."""
|
|
|
|
model = BoringModel()
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
enable_progress_bar=False,
|
|
|
|
accumulate_grad_batches={0: 4, 2: 2},
|
|
|
|
accelerator="auto",
|
|
|
|
devices=1,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="horovod",
|
2020-04-22 21:39:08 +00:00
|
|
|
)
|
2022-02-19 01:54:04 +00:00
|
|
|
with pytest.raises(MisconfigurationException, match="Horovod.*does not support.*accumulate_grad_batches"):
|
|
|
|
trainer.fit(model)
|
2021-04-06 13:27:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
@RunIf(min_gpus=2, skip_windows=True, horovod_nccl=True)
|
|
|
|
def test_horovod_multi_gpu_grad_by_value(tmpdir):
|
|
|
|
"""Test Horovod with multi-GPU support."""
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=str(tmpdir),
|
|
|
|
gradient_clip_val=1.0,
|
2021-07-26 11:37:35 +00:00
|
|
|
gradient_clip_algorithm="value",
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2021-04-06 13:27:37 +00:00
|
|
|
max_epochs=1,
|
|
|
|
limit_train_batches=0.4,
|
|
|
|
limit_val_batches=0.2,
|
2022-02-19 01:54:04 +00:00
|
|
|
accelerator="gpu",
|
|
|
|
devices=2,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="horovod",
|
2021-04-06 13:27:37 +00:00
|
|
|
)
|
2022-02-19 01:54:04 +00:00
|
|
|
_run_horovod(trainer_options)
|
2020-04-22 21:39:08 +00:00
|
|
|
|
|
|
|
|
2021-04-09 19:06:47 +00:00
|
|
|
# todo: need to be fixed :]
|
2021-03-14 17:14:27 +00:00
|
|
|
# https://discuss.pytorch.org/t/torch-cuda-amp-vs-nvidia-apex/74994
|
|
|
|
# Check with (tgaddair) on Horovod issues if this feature is needed
|
2021-04-09 19:06:47 +00:00
|
|
|
@pytest.mark.skip(reason="TODO: Horovod currently doesn't work with Apex")
|
2021-03-02 16:21:20 +00:00
|
|
|
@RunIf(min_gpus=2, skip_windows=True, amp_apex=True, horovod_nccl=True)
|
2020-11-03 18:01:51 +00:00
|
|
|
def test_horovod_apex(tmpdir):
|
|
|
|
"""Test Horovod with multi-GPU support using apex amp."""
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=str(tmpdir),
|
|
|
|
gradient_clip_val=1.0,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2020-11-03 18:01:51 +00:00
|
|
|
max_epochs=1,
|
|
|
|
limit_train_batches=0.4,
|
|
|
|
limit_val_batches=0.2,
|
2022-02-19 01:54:04 +00:00
|
|
|
accelerator="gpu",
|
|
|
|
devices=2,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="horovod",
|
2021-07-26 11:37:35 +00:00
|
|
|
amp_backend="apex",
|
2020-11-03 18:01:51 +00:00
|
|
|
precision=16,
|
|
|
|
)
|
2022-02-19 01:54:04 +00:00
|
|
|
_run_horovod(trainer_options)
|
2020-11-03 18:01:51 +00:00
|
|
|
|
|
|
|
|
2021-09-29 13:34:26 +00:00
|
|
|
@RunIf(min_gpus=2, skip_windows=True, horovod_nccl=True)
|
2020-09-09 00:30:57 +00:00
|
|
|
def test_horovod_amp(tmpdir):
|
2020-11-03 18:01:51 +00:00
|
|
|
"""Test Horovod with multi-GPU support using native amp."""
|
2020-09-09 00:30:57 +00:00
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=str(tmpdir),
|
|
|
|
gradient_clip_val=1.0,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2020-09-09 00:30:57 +00:00
|
|
|
max_epochs=1,
|
|
|
|
limit_train_batches=0.4,
|
|
|
|
limit_val_batches=0.2,
|
2022-02-19 01:54:04 +00:00
|
|
|
accelerator="gpu",
|
|
|
|
devices=2,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="horovod",
|
2021-07-26 11:37:35 +00:00
|
|
|
amp_backend="native",
|
2020-09-09 00:30:57 +00:00
|
|
|
precision=16,
|
|
|
|
)
|
2022-02-19 01:54:04 +00:00
|
|
|
_run_horovod(trainer_options)
|
2020-09-09 00:30:57 +00:00
|
|
|
|
|
|
|
|
2021-03-14 17:14:27 +00:00
|
|
|
@RunIf(min_gpus=2, skip_windows=True, horovod_nccl=True)
|
|
|
|
def test_horovod_gather(tmpdir):
|
|
|
|
"""Test Horovod with multi-GPU support using native amp."""
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=str(tmpdir),
|
|
|
|
gradient_clip_val=1.0,
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2021-03-14 17:14:27 +00:00
|
|
|
max_epochs=1,
|
|
|
|
limit_train_batches=0.4,
|
|
|
|
limit_val_batches=0.2,
|
2022-02-19 01:54:04 +00:00
|
|
|
accelerator="gpu",
|
|
|
|
devices=2,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="horovod",
|
2021-03-14 17:14:27 +00:00
|
|
|
)
|
2022-02-19 01:54:04 +00:00
|
|
|
_run_horovod(trainer_options)
|
2021-03-14 17:14:27 +00:00
|
|
|
|
|
|
|
|
2021-03-02 16:21:20 +00:00
|
|
|
@RunIf(min_gpus=1, skip_windows=True, horovod_nccl=True)
|
2020-04-22 21:39:08 +00:00
|
|
|
def test_horovod_transfer_batch_to_gpu(tmpdir):
|
2021-02-11 14:32:07 +00:00
|
|
|
class TestTrainingStepModel(BoringModel):
|
2020-04-22 21:39:08 +00:00
|
|
|
def training_step(self, batch, *args, **kwargs):
|
2021-07-26 11:37:35 +00:00
|
|
|
assert str(batch.device) != "cpu"
|
2021-07-26 12:38:12 +00:00
|
|
|
return super().training_step(batch, *args, **kwargs)
|
2020-04-22 21:39:08 +00:00
|
|
|
|
|
|
|
def validation_step(self, batch, *args, **kwargs):
|
2021-07-26 11:37:35 +00:00
|
|
|
assert str(batch.device) != "cpu"
|
2021-07-26 12:38:12 +00:00
|
|
|
return super().validation_step(batch, *args, **kwargs)
|
2020-04-22 21:39:08 +00:00
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
model = TestTrainingStepModel()
|
2020-04-22 21:39:08 +00:00
|
|
|
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=str(tmpdir),
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2020-04-22 21:39:08 +00:00
|
|
|
max_epochs=1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.4,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.2,
|
2022-02-19 01:54:04 +00:00
|
|
|
accelerator="gpu",
|
|
|
|
devices=1,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="horovod",
|
2020-04-22 21:39:08 +00:00
|
|
|
)
|
2020-06-27 01:38:25 +00:00
|
|
|
tpipes.run_model_test_without_loggers(trainer_options, model)
|
2020-04-22 21:39:08 +00:00
|
|
|
|
|
|
|
|
2021-03-14 17:14:27 +00:00
|
|
|
@RunIf(skip_windows=True, horovod=True)
|
2021-01-08 21:13:12 +00:00
|
|
|
def test_horovod_multi_optimizer(tmpdir):
|
2021-02-11 14:32:07 +00:00
|
|
|
model = BasicGAN()
|
2020-04-22 21:39:08 +00:00
|
|
|
|
2020-07-28 13:47:53 +00:00
|
|
|
# fit model
|
|
|
|
trainer = Trainer(
|
2020-04-22 21:39:08 +00:00
|
|
|
default_root_dir=str(tmpdir),
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2020-04-22 21:39:08 +00:00
|
|
|
max_epochs=1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.4,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.2,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="horovod",
|
2020-04-22 21:39:08 +00:00
|
|
|
)
|
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}"
|
2020-04-22 21:39:08 +00:00
|
|
|
|
|
|
|
assert len(trainer.optimizers) == 2
|
|
|
|
for i, optimizer in enumerate(trainer.optimizers):
|
2021-07-26 11:37:35 +00:00
|
|
|
assert hasattr(optimizer, "synchronize"), "optimizer has not been wrapped into DistributedOptimizer"
|
2020-04-22 21:39:08 +00:00
|
|
|
|
|
|
|
def get_model_params(model):
|
2021-06-27 09:00:02 +00:00
|
|
|
return set(list(model.parameters()))
|
2020-04-22 21:39:08 +00:00
|
|
|
|
|
|
|
def get_optimizer_params(optimizer):
|
2021-07-26 12:38:12 +00:00
|
|
|
return {p for group in optimizer.param_groups for p in group.get("params", [])}
|
2020-04-22 21:39:08 +00:00
|
|
|
|
2020-05-01 18:13:35 +00:00
|
|
|
assert get_model_params(model.generator) != get_model_params(model.discriminator)
|
2020-04-22 21:39:08 +00:00
|
|
|
assert get_model_params(model.generator) == get_optimizer_params(trainer.optimizers[0])
|
|
|
|
assert get_model_params(model.discriminator) == get_optimizer_params(trainer.optimizers[1])
|
2020-07-23 16:14:57 +00:00
|
|
|
|
2020-11-05 17:52:02 +00:00
|
|
|
|
2021-04-09 19:06:47 +00:00
|
|
|
# todo: need to be fixed :]
|
|
|
|
@pytest.mark.skip(reason="TODO: CI agent.jobstatus=Succeeded: Permission denied")
|
2021-03-02 16:21:20 +00:00
|
|
|
@RunIf(skip_windows=True, horovod=True)
|
2021-01-08 21:13:12 +00:00
|
|
|
def test_result_reduce_horovod(tmpdir):
|
2020-11-05 17:52:02 +00:00
|
|
|
"""Make sure result logging works with Horovod.
|
|
|
|
|
|
|
|
This test mirrors tests/core/test_results.py::_ddp_test_fn
|
|
|
|
"""
|
|
|
|
tutils.reset_seed()
|
2021-10-25 12:09:05 +00:00
|
|
|
tutils.set_random_main_port()
|
2020-11-05 17:52:02 +00:00
|
|
|
|
|
|
|
def hvd_test_fn():
|
|
|
|
path_here = os.path.abspath(os.path.dirname(__file__))
|
2021-07-26 11:37:35 +00:00
|
|
|
path_root = os.path.abspath(os.path.join(path_here, "..", ".."))
|
2020-11-05 17:52:02 +00:00
|
|
|
sys.path.insert(0, os.path.abspath(path_root))
|
|
|
|
|
|
|
|
class TestModel(BoringModel):
|
|
|
|
def training_step(self, batch, batch_idx):
|
|
|
|
self.training_step_called = True
|
|
|
|
|
|
|
|
tensor = torch.tensor([1.0])
|
2021-07-26 11:37:35 +00:00
|
|
|
self.log("test_tensor", tensor, sync_dist=True, reduce_fx="sum", on_step=True, on_epoch=True)
|
2020-11-05 17:52:02 +00:00
|
|
|
|
|
|
|
res = self._results
|
|
|
|
|
|
|
|
# Check that `tensor` is summed across all ranks automatically
|
2021-07-26 11:37:35 +00:00
|
|
|
assert (
|
|
|
|
res["test_tensor"].item() == hvd.size()
|
|
|
|
), "Result-Log does not work properly with Horovod and Tensors"
|
2020-11-05 17:52:02 +00:00
|
|
|
|
|
|
|
def training_epoch_end(self, outputs) -> None:
|
|
|
|
assert len(outputs) == 0
|
|
|
|
|
|
|
|
model = TestModel()
|
|
|
|
model.val_dataloader = None
|
|
|
|
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
limit_train_batches=2,
|
|
|
|
limit_val_batches=2,
|
|
|
|
max_epochs=1,
|
|
|
|
log_every_n_steps=1,
|
2021-10-13 11:50:54 +00:00
|
|
|
enable_model_summary=False,
|
2021-07-26 11:37:35 +00:00
|
|
|
logger=False,
|
2020-11-05 17:52:02 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
horovod.run(hvd_test_fn, np=2)
|
|
|
|
|
|
|
|
|
2021-04-09 19:06:47 +00:00
|
|
|
# todo: need to be fixed :]
|
|
|
|
@pytest.mark.skip(reason="TODO: CI agent.jobstatus=Succeeded: Permission denied")
|
2021-03-14 17:14:27 +00:00
|
|
|
@RunIf(skip_windows=True, horovod=True, num_gpus=2)
|
2020-11-05 17:52:02 +00:00
|
|
|
def test_accuracy_metric_horovod():
|
|
|
|
num_batches = 10
|
|
|
|
batch_size = 16
|
|
|
|
threshold = 0.5
|
|
|
|
|
|
|
|
def sk_metric(preds, target):
|
|
|
|
sk_preds = (preds.view(-1).numpy() >= threshold).astype(np.uint8)
|
|
|
|
sk_target = target.view(-1).numpy()
|
|
|
|
return accuracy_score(y_true=sk_target, y_pred=sk_preds)
|
|
|
|
|
|
|
|
preds = torch.rand(num_batches, batch_size)
|
|
|
|
target = torch.randint(high=2, size=(num_batches, batch_size))
|
|
|
|
|
|
|
|
def _compute_batch():
|
2021-10-16 15:10:25 +00:00
|
|
|
trainer = Trainer(fast_dev_run=True, strategy="horovod", logger=False)
|
2020-11-05 17:52:02 +00:00
|
|
|
|
2021-02-18 15:54:12 +00:00
|
|
|
assert isinstance(trainer.accelerator, CPUAccelerator)
|
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
|
|
|
# TODO: test that we selected the correct training_type_plugin based on horovod flags
|
2020-11-05 17:52:02 +00:00
|
|
|
|
2021-02-06 11:07:26 +00:00
|
|
|
metric = Accuracy(
|
|
|
|
compute_on_step=True,
|
|
|
|
dist_sync_on_step=True,
|
2021-12-22 02:11:43 +00:00
|
|
|
dist_sync_fn=trainer.strategy.all_gather,
|
2021-07-26 11:37:35 +00:00
|
|
|
threshold=threshold,
|
2021-02-06 11:07:26 +00:00
|
|
|
)
|
2020-11-05 17:52:02 +00:00
|
|
|
|
|
|
|
for i in range(hvd.rank(), num_batches, hvd.size()):
|
|
|
|
batch_result = metric(preds[i], target[i])
|
|
|
|
if hvd.rank() == 0:
|
|
|
|
dist_preds = torch.stack([preds[i + r] for r in range(hvd.size())])
|
|
|
|
dist_target = torch.stack([target[i + r] for r in range(hvd.size())])
|
|
|
|
sk_batch_result = sk_metric(dist_preds, dist_target)
|
|
|
|
assert np.allclose(batch_result.numpy(), sk_batch_result)
|
|
|
|
|
|
|
|
# check on all batches on all ranks
|
|
|
|
result = metric.compute()
|
|
|
|
assert isinstance(result, torch.Tensor)
|
|
|
|
|
|
|
|
total_preds = torch.stack([preds[i] for i in range(num_batches)])
|
|
|
|
total_target = torch.stack([target[i] for i in range(num_batches)])
|
|
|
|
sk_result = sk_metric(total_preds, total_target)
|
|
|
|
|
|
|
|
assert np.allclose(result.numpy(), sk_result)
|
|
|
|
|
|
|
|
horovod.run(_compute_batch, np=2)
|
|
|
|
|
2021-02-06 11:07:26 +00:00
|
|
|
|
2021-03-14 17:14:27 +00:00
|
|
|
@RunIf(skip_windows=True, horovod=True)
|
|
|
|
def test_horovod_multi_optimizer_with_scheduling_stepping(tmpdir):
|
|
|
|
class TestModel(BoringModel):
|
|
|
|
def training_step(self, batch, batch_idx, optimizer_idx):
|
|
|
|
return super().training_step(batch, batch_idx)
|
|
|
|
|
|
|
|
def configure_optimizers(self):
|
|
|
|
optimizer1 = optim.Adam(self.parameters(), lr=0.1)
|
|
|
|
optimizer2 = optim.Adam(self.parameters(), lr=0.1)
|
|
|
|
lr_scheduler1 = optim.lr_scheduler.StepLR(optimizer1, 1, gamma=0.1)
|
|
|
|
lr_scheduler2 = optim.lr_scheduler.StepLR(optimizer2, 1, gamma=0.1)
|
|
|
|
return [optimizer1, optimizer2], [lr_scheduler1, lr_scheduler2]
|
|
|
|
|
|
|
|
model = TestModel()
|
|
|
|
model.training_epoch_end = None
|
|
|
|
|
|
|
|
num_workers = 8
|
|
|
|
init_lr = 0.1 * num_workers
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
with patch("horovod.torch.size", return_value=8):
|
2021-03-14 17:14:27 +00:00
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(
|
2021-10-16 15:10:25 +00:00
|
|
|
default_root_dir=tmpdir, max_epochs=1, limit_val_batches=0.5, limit_train_batches=0.2, strategy="horovod"
|
2021-03-14 17:14:27 +00:00
|
|
|
)
|
2021-04-28 18:11:32 +00:00
|
|
|
trainer.fit(model)
|
2021-03-14 17:14:27 +00:00
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
adjusted_lr1 = [pg["lr"] for pg in trainer.optimizers[0].param_groups][0]
|
|
|
|
adjusted_lr2 = [pg["lr"] for pg in trainer.optimizers[1].param_groups][0]
|
2021-03-14 17:14:27 +00:00
|
|
|
|
|
|
|
# Called ones after end of epoch with gamma=0.1
|
|
|
|
assert pytest.approx(init_lr * 0.1) == adjusted_lr1
|
|
|
|
|
|
|
|
# Called every 3 steps, meaning for 1 epoch of 11 batches, it is called 3 times with gamma=0.1
|
|
|
|
assert pytest.approx(init_lr * 0.1) == adjusted_lr2
|