|
| 1 | +# Copyright The PyTorch Lightning 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 | +from typing import Optional, TYPE_CHECKING |
| 15 | + |
| 16 | +import torch |
| 17 | +from typing_extensions import Literal |
| 18 | + |
| 19 | +from lightning_lite.plugins.precision.native_amp import NativeMixedPrecision |
| 20 | +from lightning_lite.utilities.enums import PrecisionType |
| 21 | +from lightning_lite.utilities.imports import _TORCH_GREATER_EQUAL_1_12 |
| 22 | + |
| 23 | +if TYPE_CHECKING: |
| 24 | + from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision |
| 25 | + from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler |
| 26 | + |
| 27 | + |
| 28 | +class FSDPPrecision(NativeMixedPrecision): |
| 29 | + """AMP for Fully Sharded Data Parallel training.""" |
| 30 | + |
| 31 | + def __init__( |
| 32 | + self, precision: Literal[16, "bf16"], device: str, scaler: Optional["ShardedGradScaler"] = None |
| 33 | + ) -> None: |
| 34 | + if not _TORCH_GREATER_EQUAL_1_12: |
| 35 | + raise NotImplementedError("`FSDPPrecision` is supported from PyTorch v1.12.0 onwards.") |
| 36 | + |
| 37 | + from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler |
| 38 | + |
| 39 | + super().__init__( |
| 40 | + precision=precision, |
| 41 | + device=device, |
| 42 | + scaler=(ShardedGradScaler() if scaler is None and precision == 16 else None), |
| 43 | + ) |
| 44 | + |
| 45 | + @property |
| 46 | + def mixed_precision_config(self) -> "MixedPrecision": |
| 47 | + from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision |
| 48 | + |
| 49 | + if self.precision == PrecisionType.HALF: |
| 50 | + dtype = torch.float16 |
| 51 | + elif self.precision == PrecisionType.BFLOAT: |
| 52 | + dtype = torch.bfloat16 |
| 53 | + else: |
| 54 | + raise ValueError(f"Was unable to infer precision type, received {self.precision!r}.") |
| 55 | + return MixedPrecision( |
| 56 | + param_dtype=dtype, |
| 57 | + reduce_dtype=dtype, |
| 58 | + buffer_dtype=dtype, |
| 59 | + ) |
0 commit comments