|
| 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 Any, Callable, Generator, Iterator, Optional, Union |
| 15 | + |
| 16 | +import torch |
| 17 | +from torch import nn as nn |
| 18 | +from torch import Tensor |
| 19 | +from torch.optim import Optimizer |
| 20 | +from torch.utils.data import DataLoader |
| 21 | + |
| 22 | +from pytorch_lightning.accelerators import Accelerator |
| 23 | +from pytorch_lightning.plugins import PrecisionPlugin |
| 24 | +from pytorch_lightning.utilities.apply_func import apply_to_collection, move_data_to_device |
| 25 | + |
| 26 | + |
| 27 | +def _do_nothing_closure() -> None: |
| 28 | + return None |
| 29 | + |
| 30 | + |
| 31 | +class _LiteOptimizer: |
| 32 | + def __init__(self, optimizer: Optimizer, accelerator: Accelerator) -> None: |
| 33 | + """LiteOptimizer is a thin wrapper around the :class:`~torch.optim.Optimizer` that delegates the optimizer |
| 34 | + step calls to the accelerator/strategy plugin. |
| 35 | +
|
| 36 | + The underlying wrapped optimizer object can be accessed via the property :attr:`optimizer`. |
| 37 | +
|
| 38 | + Args: |
| 39 | + optimizer: The optimizer to wrap |
| 40 | + accelerator: Reference to the accelerator for handling the optimizer step |
| 41 | + """ |
| 42 | + # `__del__` is skipped in case the optimizer has implemented custom destructor logic which we would |
| 43 | + # not want to call on destruction of the `_LiteOptimizer |
| 44 | + self.__dict__ = {k: v for k, v in optimizer.__dict__.items() if k not in ("step", "__del__")} |
| 45 | + self.__class__ = type("Lite" + optimizer.__class__.__name__, (self.__class__, optimizer.__class__), {}) |
| 46 | + self._optimizer = optimizer |
| 47 | + self._accelerator = accelerator |
| 48 | + |
| 49 | + @property |
| 50 | + def optimizer(self) -> Optimizer: |
| 51 | + return self._optimizer |
| 52 | + |
| 53 | + def step(self, closure: Optional[Callable] = None) -> None: |
| 54 | + closure = closure or _do_nothing_closure |
| 55 | + self._accelerator.optimizer_step( |
| 56 | + self.optimizer, |
| 57 | + opt_idx=0, |
| 58 | + closure=closure, |
| 59 | + model=self._accelerator.model, |
| 60 | + ) |
| 61 | + |
| 62 | + |
| 63 | +class _LiteModule(nn.Module): |
| 64 | + def __init__(self, module: nn.Module, precision_plugin: PrecisionPlugin) -> None: |
| 65 | + """The LiteModule is a thin wrapper around the :class:`torch.nn.Module` and handles precision / autocast |
| 66 | + automatically for the forward pass. |
| 67 | +
|
| 68 | + The underlying wrapped module can be accessed via the property :attr:`module`. |
| 69 | +
|
| 70 | + Args: |
| 71 | + module: The module to wrap |
| 72 | + precision_plugin: Reference to the precision plugin for handling precision context |
| 73 | + """ |
| 74 | + super().__init__() |
| 75 | + self._module = module |
| 76 | + self._precision_plugin = precision_plugin |
| 77 | + |
| 78 | + @property |
| 79 | + def module(self) -> nn.Module: |
| 80 | + return self._module |
| 81 | + |
| 82 | + def forward(self, *args: Any, **kwargs: Any) -> Any: |
| 83 | + """Casts all inputs to the right precision and handles autocast for operations in the module forward |
| 84 | + method.""" |
| 85 | + precision = self._precision_plugin.precision |
| 86 | + precision_to_type = { |
| 87 | + "bf16": torch.bfloat16, |
| 88 | + 16: torch.float16, |
| 89 | + 32: torch.float32, |
| 90 | + 64: torch.float64, |
| 91 | + } |
| 92 | + # TODO (@awaelchli): let the precision plugin handle the conversion |
| 93 | + to_type = precision_to_type[precision] |
| 94 | + args, kwargs = apply_to_collection([args, kwargs], function=lambda t: t.to(to_type), dtype=Tensor) |
| 95 | + |
| 96 | + with self._precision_plugin.forward_context(): |
| 97 | + output = self.module(*args, **kwargs) |
| 98 | + |
| 99 | + output = apply_to_collection(output, function=lambda t: t.to(torch.get_default_dtype()), dtype=Tensor) |
| 100 | + return output |
| 101 | + |
| 102 | + |
| 103 | +class _LiteDataLoader(DataLoader): |
| 104 | + def __init__(self, device: Optional[torch.device] = None, **dl_kwargs: Any) -> None: |
| 105 | + """The LiteDataLoader is an extension of the PyTorch :class:`~torch.utils.data.DataLoader` that adds |
| 106 | + additional features such as moving the data to the device automatically. |
| 107 | +
|
| 108 | + Args: |
| 109 | + device: The device to which the data should be moved. By default the device is `None` and no data |
| 110 | + transfers will be made (identical behavior as :class:`~torch.utils.data.DataLoader`). |
| 111 | + **dl_kwargs: Accepts all arguments that the PyTorch :class:`~torch.utils.data.DataLoader` accepts. |
| 112 | + """ |
| 113 | + super().__init__(**dl_kwargs) |
| 114 | + self._device = device |
| 115 | + |
| 116 | + @property |
| 117 | + def device(self) -> Optional[torch.device]: |
| 118 | + return self._device |
| 119 | + |
| 120 | + def __iter__(self) -> Union[Iterator[Any], Generator[Any, None, None]]: |
| 121 | + iterator = super().__iter__() |
| 122 | + if self._device is None: |
| 123 | + return iterator |
| 124 | + |
| 125 | + for item in iterator: |
| 126 | + yield move_data_to_device(item, self._device) |
0 commit comments