|
| 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 |
| 15 | + |
| 16 | +import torch |
| 17 | + |
| 18 | +from pytorch_lightning.core.lightning import LightningModule |
| 19 | +from pytorch_lightning.trainer.states import RunningStage |
| 20 | +from pytorch_lightning.utilities.warnings import WarningCache |
| 21 | + |
| 22 | +warning_cache = WarningCache() |
| 23 | + |
| 24 | + |
| 25 | +class _LightningModuleWrapperBase(torch.nn.Module): |
| 26 | + |
| 27 | + def __init__(self, pl_module: LightningModule): |
| 28 | + """ |
| 29 | + Wraps the user's LightningModule and redirects the forward call to the appropriate |
| 30 | + method, either ``training_step``, ``validation_step`` or ``test_step``. |
| 31 | + If the LightningModule is in none of the states `training`, `testing` or `validation`, |
| 32 | + the inputs will be redirected to the |
| 33 | + :meth:`~pytorch_lightning.core.lightning.LightningModule.predict` method. |
| 34 | + Inheriting classes may also modify the inputs or outputs of forward. |
| 35 | +
|
| 36 | + Args: |
| 37 | + pl_module: the model to wrap |
| 38 | + """ |
| 39 | + super().__init__() |
| 40 | + self.module = pl_module |
| 41 | + |
| 42 | + def forward(self, *inputs, **kwargs): |
| 43 | + running_stage = self.module.running_stage |
| 44 | + |
| 45 | + if running_stage == RunningStage.TRAINING: |
| 46 | + output = self.module.training_step(*inputs, **kwargs) |
| 47 | + warn_if_output_is_none(output, "training_step") |
| 48 | + elif running_stage == RunningStage.TESTING: |
| 49 | + output = self.module.test_step(*inputs, **kwargs) |
| 50 | + warn_if_output_is_none(output, "test_step") |
| 51 | + elif running_stage == RunningStage.EVALUATING: |
| 52 | + output = self.module.validation_step(*inputs, **kwargs) |
| 53 | + warn_if_output_is_none(output, "validation_step") |
| 54 | + else: |
| 55 | + output = self.module.predict(*inputs, **kwargs) |
| 56 | + |
| 57 | + return output |
| 58 | + |
| 59 | + |
| 60 | +def warn_if_output_is_none(output: Any, method_name: str) -> None: |
| 61 | + """ Warns user about which method returned None. """ |
| 62 | + if output is None: |
| 63 | + warning_cache.warn(f'Your {method_name} returned None. Did you forget to return an output?') |
0 commit comments