pytorch-lightning

Форк
0
362 строки · 12.9 Кб
1
# Copyright The Lightning AI team.
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14
import io
15
import os
16
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
17

18
import torch
19
from torch import Tensor
20
from torch.nn import Module
21
from typing_extensions import override
22

23
import lightning.pytorch as pl
24
from lightning.fabric.accelerators.xla import _XLA_AVAILABLE, _XLA_GREATER_EQUAL_2_1
25
from lightning.fabric.plugins import XLACheckpointIO
26
from lightning.fabric.plugins.environments import XLAEnvironment
27
from lightning.fabric.strategies import _StrategyRegistry
28
from lightning.fabric.utilities.optimizer import _optimizers_to_device
29
from lightning.fabric.utilities.types import _PATH, ReduceOp
30
from lightning.pytorch.plugins import XLAPrecision
31
from lightning.pytorch.plugins.io.wrapper import _WrappingCheckpointIO
32
from lightning.pytorch.strategies.ddp import DDPStrategy
33
from lightning.pytorch.strategies.launchers.xla import _XLALauncher
34
from lightning.pytorch.strategies.strategy import TBroadcast
35
from lightning.pytorch.trainer.states import TrainerFn
36
from lightning.pytorch.utilities import find_shared_parameters, set_shared_parameters
37
from lightning.pytorch.utilities.rank_zero import rank_zero_only
38

39
if TYPE_CHECKING:
40
    from torch_xla.distributed.parallel_loader import MpDeviceLoader
41

42

43
class XLAStrategy(DDPStrategy):
44
    """Strategy for training multiple TPU devices using the :func:`torch_xla.distributed.xla_multiprocessing.spawn`
45
    method."""
46

47
    strategy_name = "xla"
48

49
    def __init__(
50
        self,
51
        accelerator: Optional["pl.accelerators.Accelerator"] = None,
52
        parallel_devices: Optional[List[torch.device]] = None,
53
        checkpoint_io: Optional[Union[XLACheckpointIO, _WrappingCheckpointIO]] = None,
54
        precision_plugin: Optional[XLAPrecision] = None,
55
        debug: bool = False,
56
        sync_module_states: bool = True,
57
        **_: Any,
58
    ) -> None:
59
        if not _XLA_AVAILABLE:
60
            raise ModuleNotFoundError(str(_XLA_AVAILABLE))
61
        super().__init__(
62
            accelerator=accelerator,
63
            parallel_devices=parallel_devices,
64
            cluster_environment=XLAEnvironment(),
65
            checkpoint_io=checkpoint_io,
66
            precision_plugin=precision_plugin,
67
            start_method="fork",
68
        )
69
        self.debug = debug
70
        self._launched = False
71
        self._sync_module_states = sync_module_states
72

73
    @property
74
    @override
75
    def checkpoint_io(self) -> Union[XLACheckpointIO, _WrappingCheckpointIO]:
76
        plugin = self._checkpoint_io
77
        if plugin is not None:
78
            assert isinstance(plugin, (XLACheckpointIO, _WrappingCheckpointIO))
79
            return plugin
80
        return XLACheckpointIO()
81

82
    @checkpoint_io.setter
83
    @override
84
    def checkpoint_io(self, io: Optional[Union[XLACheckpointIO, _WrappingCheckpointIO]]) -> None:
85
        if io is not None and not isinstance(io, (XLACheckpointIO, _WrappingCheckpointIO)):
86
            raise TypeError(f"The XLA strategy can only work with the `XLACheckpointIO` plugin, found {io}")
87
        self._checkpoint_io = io
88

89
    @property
90
    @override
91
    def precision_plugin(self) -> XLAPrecision:
92
        plugin = self._precision_plugin
93
        if plugin is not None:
94
            assert isinstance(plugin, XLAPrecision)
95
            return plugin
96
        return XLAPrecision()
97

98
    @precision_plugin.setter
99
    @override
100
    def precision_plugin(self, precision_plugin: Optional[XLAPrecision]) -> None:
101
        if precision_plugin is not None and not isinstance(precision_plugin, XLAPrecision):
102
            raise TypeError(f"The XLA strategy can only work with the `XLAPrecision` plugin, found {precision_plugin}")
103
        self._precision_plugin = precision_plugin
104

105
    @property
106
    @override
107
    def root_device(self) -> torch.device:
108
        if not self._launched:
109
            raise RuntimeError("Accessing the XLA device before processes have spawned is not allowed.")
110
        import torch_xla.core.xla_model as xm
111

112
        return xm.xla_device()
113

114
    @property
115
    @override
116
    def global_rank(self) -> int:
117
        return super().global_rank if self._launched else 0
118

119
    @property
120
    @override
121
    def local_rank(self) -> int:
122
        return super().local_rank if self._launched else 0
123

124
    @property
125
    @override
126
    def node_rank(self) -> int:
127
        return super().node_rank if self._launched else 0
128

129
    @property
130
    @override
131
    def world_size(self) -> int:
132
        return super().world_size if self._launched else 1
133

134
    @override
135
    def _configure_launcher(self) -> None:
136
        self._launcher = _XLALauncher(self)
137

138
    @override
139
    def setup(self, trainer: "pl.Trainer") -> None:
140
        assert self.accelerator is not None
141
        self.accelerator.setup(trainer)
142

143
        if self.debug:
144
            os.environ["PT_XLA_DEBUG"] = "1"
145

146
        assert self.model is not None
147
        self.precision_plugin.convert_module(self.model)
148

149
        shared_params = find_shared_parameters(self.model)
150
        self.model_to_device()
151
        set_shared_parameters(self.model, shared_params)
152

153
        self.model = self._setup_model(self.model)
154

155
        if self._sync_module_states:
156
            if _XLA_GREATER_EQUAL_2_1:
157
                from torch_xla.core.xla_model import broadcast_master_param
158
            else:
159
                from torch_xla.experimental.pjrt import broadcast_master_param
160

161
            broadcast_master_param(self.model)
162

163
        if trainer.state.fn == TrainerFn.FITTING:
164
            self.setup_optimizers(trainer)
165
        self.setup_precision_plugin()
166
        if trainer.state.fn == TrainerFn.FITTING:
167
            _optimizers_to_device(self.optimizers, self.root_device)
168

169
    @override
170
    def _setup_model(self, model: Module) -> Module:  # type: ignore
171
        return model
172

173
    @property
174
    @override
175
    def distributed_sampler_kwargs(self) -> Dict[str, int]:
176
        return {"num_replicas": self.world_size, "rank": self.global_rank}
177

178
    @override
179
    def process_dataloader(self, dataloader: object) -> "MpDeviceLoader":
180
        from torch_xla.distributed.parallel_loader import MpDeviceLoader
181

182
        if isinstance(dataloader, MpDeviceLoader):
183
            # dataloader is already wrapped by MpDeviceLoader
184
            return dataloader
185

186
        dataloader = MpDeviceLoader(dataloader, self.root_device)
187
        # Mimic interface to torch.utils.data.DataLoader
188
        dataloader.dataset = dataloader._loader.dataset
189
        dataloader.batch_sampler = getattr(dataloader._loader, "batch_sampler", None)
190
        return dataloader
191

192
    @override
193
    def configure_ddp(self) -> None:
194
        pass
195

196
    @override
197
    def model_to_device(self) -> None:
198
        assert self.model is not None
199
        self.model = self.model.to(self.root_device)
200

201
    @override
202
    def barrier(self, name: Optional[str] = None, *args: Any, **kwargs: Any) -> None:
203
        if not self._launched:
204
            return
205

206
        import torch_xla.core.xla_model as xm
207

208
        if name is None:
209
            # `None` is not supported: "TypeError: _xla_rendezvous(): incompatible function arguments"
210
            name = ""
211
        xm.rendezvous(name)
212

213
    @override
214
    def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast:
215
        if not self._launched:
216
            return obj
217

218
        import torch_xla.core.xla_model as xm
219

220
        is_tensor = isinstance(obj, Tensor)
221
        if is_tensor:
222
            if obj.dim() == 0:
223
                obj = obj.unsqueeze(0)
224
            original_device = obj.device
225
            # XLA distributed requires that the data is on the XLA device
226
            obj = obj.to(self.root_device)
227
        else:
228
            # support for arbitrary pickle-ables
229
            buffer = io.BytesIO()
230
            torch.save(obj, buffer)
231
            obj = torch.tensor(  # type: ignore[assignment]
232
                bytearray(buffer.getbuffer()), device=self.root_device, dtype=torch.float
233
            )
234

235
        obj = [obj]
236
        xm.collective_broadcast(obj, root_ordinal=src)
237
        obj = obj[0]
238

239
        if not is_tensor:
240
            # this will preserve the dtype and device of any tensors
241
            buffer = io.BytesIO(obj.cpu().byte().numpy())
242
            obj = torch.load(buffer)
243
        else:
244
            obj = obj.to(original_device)
245

246
        return obj
247

248
    @override
249
    def reduce(
250
        self, output: Union[Tensor, Any], group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = None
251
    ) -> Tensor:
252
        if not isinstance(output, Tensor):
253
            output = torch.tensor(output, device=self.root_device)
254

255
        invalid_reduce_op = isinstance(reduce_op, ReduceOp) and reduce_op != ReduceOp.SUM
256
        invalid_reduce_op_str = isinstance(reduce_op, str) and reduce_op.lower() not in ("sum", "mean", "avg")
257
        if invalid_reduce_op or invalid_reduce_op_str:
258
            raise ValueError(
259
                "Currently, the XLAStrategy only supports `sum`, `mean`, `avg` for the reduce operation, got:"
260
                f" {reduce_op}"
261
            )
262

263
        import torch_xla.core.xla_model as xm
264

265
        output = xm.mesh_reduce("reduce", output, sum)
266

267
        if isinstance(reduce_op, str) and reduce_op.lower() in ("avg", "mean"):
268
            output = output / self.world_size
269

270
        return output
271

272
    @override
273
    def setup_environment(self) -> None:
274
        self._launched = True
275
        super().setup_environment()
276

277
    @override
278
    def setup_distributed(self) -> None:
279
        assert self.parallel_devices is not None
280
        if len(self.parallel_devices) == 1:
281
            # spawning only 1 device with PjRT is not supported:
282
            # https://github.com/Lightning-AI/lightning/pull/17408#discussion_r1170671732
283
            raise NotImplementedError(
284
                "The `XLAStrategy` does not support running on a single device with the PjRT runtime."
285
                " Try using all devices or the `SingleDeviceXLAStrategy` strategy"
286
            )
287
        rank_zero_only.rank = self.global_rank
288

289
    @override
290
    def set_world_ranks(self) -> None:
291
        # accessing global_rank will initialize the XLA computation client. since this is called outside of the spawned
292
        # processes (by the accelerator connector), we cannot run the code that would normally be here.
293
        # instead it's done in `setup_distributed`
294
        pass
295

296
    @override
297
    def save_checkpoint(
298
        self, checkpoint: Dict[str, Any], filepath: _PATH, storage_options: Optional[Any] = None
299
    ) -> None:
300
        import torch_xla.core.xla_model as xm
301

302
        # sync any pending lazy tensors on all ranks before saving to prevent potential collective hangs
303
        xm.mark_step()
304
        # save on global rank zero only
305
        super().save_checkpoint(checkpoint, filepath, storage_options=storage_options)
306

307
    @override
308
    def remove_checkpoint(self, filepath: _PATH) -> None:
309
        """Remove checkpoint filepath from the filesystem.
310

311
        Args:
312
            filepath: Path to checkpoint
313

314
        """
315
        if self.local_rank == 0:
316
            self.checkpoint_io.remove_checkpoint(filepath)
317

318
    @override
319
    def all_gather(self, tensor: Tensor, group: Optional[Any] = None, sync_grads: bool = False) -> Tensor:
320
        """Function to gather a tensor from several distributed processes.
321

322
        Args:
323
            tensor: tensor to all-gather.
324
            group: unused.
325
            sync_grads: flag that allows users to synchronize gradients for the all-gather operation.
326
        Return:
327
            A tensor of shape (world_size, ...)
328

329
        """
330
        if not self._launched:
331
            return tensor
332
        if not isinstance(tensor, Tensor):
333
            raise NotImplementedError(
334
                f"`{type(self).__name__}.all_gather` is only implemented for tensors. Given {tensor}"
335
            )
336
        if tensor.dim() == 0:
337
            tensor = tensor.unsqueeze(0)
338
        original_device = tensor.device
339
        tensor = tensor.to(self.root_device)
340

341
        import torch_xla.core.functions as xf
342
        import torch_xla.core.xla_model as xm
343

344
        tensor = xf.all_gather(tensor) if sync_grads else xm.all_gather(tensor)
345
        tensor = tensor.to(original_device)
346
        return tensor
347

348
    @override
349
    def teardown(self) -> None:
350
        super().teardown()
351
        self._launched = False  # after the Trainer finishes, we aren't inside the spawned region
352
        os.environ.pop("PT_XLA_DEBUG", None)
353

354
    @classmethod
355
    @override
356
    def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None:
357
        strategy_registry.register("xla_debug", cls, description="XLA strategy with `debug` as True", debug=True)
358
        strategy_registry.register(
359
            cls.strategy_name,
360
            cls,
361
            description=cls.__name__,
362
        )
363

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.