Skip to content

Commit c388431

Browse files
tchatonYour Name
andcommitted
[bugfix] TPU test hangs to barrier on 1 process (#6272)
* update * resolve flake8 * update * update * update changelog * update * resolve flake8 Co-authored-by: Your Name <[email protected]>
1 parent efcd761 commit c388431

File tree

7 files changed

+27
-13
lines changed

7 files changed

+27
-13
lines changed

CHANGELOG.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
2424
- Fixed `AttributeError` when `logger=None` on TPU ([#6221](https://github.com/PyTorchLightning/pytorch-lightning/pull/6221))
2525

2626

27-
2827
- Fixed PyTorch Profiler with `emit_nvtx` ([#6260](https://github.com/PyTorchLightning/pytorch-lightning/pull/6260))
2928

3029

pytorch_lightning/accelerators/tpu.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def setup(self, trainer, model):
2828
return super().setup(trainer, model)
2929

3030
def run_optimizer_step(self, optimizer: Optimizer, optimizer_idx: int, lambda_closure: Callable, **kwargs):
31-
xm.optimizer_step(optimizer, optimizer_args={'closure': lambda_closure, **kwargs})
31+
xm.optimizer_step(optimizer, barrier=False, optimizer_args={'closure': lambda_closure, **kwargs})
3232

3333
def all_gather(self, tensor: Union[torch.Tensor], group: Optional[Any] = None, sync_grads: bool = False):
3434
"""

pytorch_lightning/plugins/training_type/horovod.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from typing import Any, List, Optional, Union
1616

1717
import torch
18+
import torch.distributed as torch_distrib
1819
from torch.optim.lr_scheduler import _LRScheduler, Optimizer
1920

2021
from pytorch_lightning.core.optimizer import LightningOptimizer
@@ -116,7 +117,8 @@ def start_predicting(self, trainer):
116117
hvd.join()
117118

118119
def barrier(self, *args, **kwargs):
119-
hvd.join()
120+
if torch_distrib.is_initialized():
121+
hvd.join()
120122

121123
def broadcast(self, obj: object, src: int = 0) -> object:
122124
obj = hvd.broadcast_object(obj, src)

pytorch_lightning/plugins/training_type/tpu_spawn.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from typing import Any, Dict, Iterable, List, Optional, Union
55

66
import torch
7+
import torch.distributed as torch_distrib
78
import torch.multiprocessing as mp
89

910
from pytorch_lightning.core.lightning import LightningModule
@@ -112,7 +113,8 @@ def model_to_device(self) -> None:
112113
self._model.to(xm.xla_device())
113114

114115
def barrier(self, name: Optional[str] = None) -> None:
115-
rendezvous(f"pl.Trainer.{name}")
116+
if torch_distrib.is_initialized():
117+
rendezvous(f"pl.Trainer.{name}")
116118

117119
def transfer_distrib_spawn_state_on_fit_end(self, results):
118120
# TODO: is there a better way than accessing callback through model -> trainer -> callback?
@@ -126,14 +128,26 @@ def transfer_distrib_spawn_state_on_fit_end(self, results):
126128
# TODO: is there a better way than accessing trainer through model -> trainer?
127129
if not self.lightning_module.trainer.testing and best_model_path is not None and len(best_model_path) > 0:
128130
last_path = re.sub(".ckpt", ".tmp_end.ckpt", best_model_path)
129-
xm.save(self.lightning_module.state_dict(), last_path)
131+
self.save(self.lightning_module.state_dict(), last_path)
130132

131133
if self.global_rank == 0:
132134
# todo, pass complete checkpoint as state dictionary
133135
self.mp_queue.put(best_model_path)
134136
self.mp_queue.put(last_path)
135137
self.mp_queue.put(results)
136138

139+
def save(self, state_dict: Dict, path: str) -> None:
140+
"""
141+
Saving with ``xm.save`` can be unstable and miss the rendez-vous after ``torch.save``.
142+
The rendez-vous doesn't affect directly saving.
143+
We can ignore the ``RuntimeError`` to reduce friction with TPUs.
144+
"""
145+
try:
146+
xm.save(state_dict, path)
147+
except RuntimeError as e:
148+
if "Failed to meet rendezvous" not in str(e):
149+
raise e
150+
137151
def broadcast(self, obj: object, src: int = 0) -> object:
138152
buffer = io.BytesIO()
139153
torch.save(obj, buffer)
@@ -281,4 +295,4 @@ def save_checkpoint(self, filepath, weights_only: bool = False):
281295
# dump states as a checkpoint dictionary object
282296
_checkpoint = self.lightning_module.trainer.checkpoint_connector.dump_checkpoint(weights_only)
283297
# Todo: TypeError: 'mappingproxy' object does not support item assignment
284-
xm.save({k: v for k, v in _checkpoint.items() if k != "callbacks"}, filepath)
298+
self.save({k: v for k, v in _checkpoint.items() if k != "callbacks"}, filepath)

pytorch_lightning/trainer/connectors/accelerator_connector.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,7 @@ def set_distributed_mode(self, distributed_backend: Optional[str] = None):
494494
# define the max CPU available
495495
self.num_processes = os.cpu_count()
496496
# special case with TPUs
497-
elif self.distributed_backend == 'tpu':
497+
elif self.distributed_backend == 'tpu' or self.tpu_cores is not None:
498498
self._device_type = DeviceType.TPU
499499
elif self.distributed_backend and self._distrib_type is None:
500500
self._distrib_type = DistributedType(self.distributed_backend)

pytorch_lightning/trainer/trainer.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
from pytorch_lightning.trainer.training_loop import TrainLoop
5757
from pytorch_lightning.trainer.training_tricks import TrainerTrainingTricksMixin
5858
from pytorch_lightning.tuner.tuning import Tuner
59-
from pytorch_lightning.utilities import DeviceType, rank_zero_warn
59+
from pytorch_lightning.utilities import rank_zero_warn
6060
from pytorch_lightning.utilities.cloud_io import load as pl_load
6161
from pytorch_lightning.utilities.debugging import InternalDebugger
6262
from pytorch_lightning.utilities.enums import LightningEnum
@@ -949,8 +949,8 @@ def __test_using_best_weights(self, ckpt_path, test_dataloaders):
949949
f'specify a path for a checkpoint .test(ckpt_path=PATH)'
950950
)
951951
return {}
952-
if not self._device_type == DeviceType.TPU:
953-
self.accelerator.barrier()
952+
953+
self.training_type_plugin.barrier()
954954

955955
ckpt = pl_load(ckpt_path, map_location=lambda storage, loc: storage)
956956
model.load_state_dict(ckpt['state_dict'])

tests/models/test_tpu.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -177,8 +177,6 @@ def test_model_16bit_tpu_cores_8(tmpdir):
177177
def test_model_tpu_early_stop(tmpdir):
178178
"""Test if single TPU core training works"""
179179

180-
# todo: Test on 8 cores - hanging.
181-
182180
class CustomBoringModel(BoringModel):
183181

184182
def validation_step(self, *args, **kwargs):
@@ -195,9 +193,10 @@ def validation_step(self, *args, **kwargs):
195193
max_epochs=2,
196194
limit_train_batches=2,
197195
limit_val_batches=2,
198-
tpu_cores=[1],
196+
tpu_cores=8,
199197
)
200198
trainer.fit(model)
199+
trainer.test(test_dataloaders=DataLoader(RandomDataset(32, 2000), batch_size=32))
201200

202201

203202
@pytest.mark.skipif(not _TPU_AVAILABLE, reason="test requires TPU machine")

0 commit comments

Comments
 (0)