2021-09-08 00:26:39 +00:00
|
|
|
# Copyright The PyTorch Lightning team.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2021-09-14 13:48:27 +00:00
|
|
|
from dataclasses import dataclass, field
|
|
|
|
from typing import Any, Dict, Optional
|
|
|
|
|
|
|
|
from torch import Tensor
|
2021-09-08 00:26:39 +00:00
|
|
|
|
|
|
|
from pytorch_lightning.loops import Loop
|
2021-09-14 13:48:27 +00:00
|
|
|
from pytorch_lightning.loops.optimization.closure import OutputResult
|
2021-09-15 12:18:19 +00:00
|
|
|
from pytorch_lightning.loops.utilities import _build_training_step_kwargs, _extract_hiddens
|
|
|
|
from pytorch_lightning.utilities.exceptions import MisconfigurationException
|
2021-09-14 13:48:27 +00:00
|
|
|
from pytorch_lightning.utilities.types import STEP_OUTPUT
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class ManualResult(OutputResult):
|
|
|
|
"""A container to hold the result returned by the ``ManualLoop``.
|
|
|
|
|
|
|
|
It is created from the output of :meth:`~pytorch_lightning.core.lightning.LightningModule.training_step`.
|
|
|
|
|
|
|
|
Attributes:
|
2021-09-15 12:18:19 +00:00
|
|
|
extra: Anything returned by the ``training_step``.
|
2021-09-14 13:48:27 +00:00
|
|
|
"""
|
|
|
|
|
2021-09-15 12:18:19 +00:00
|
|
|
extra: Dict[str, Any] = field(default_factory=dict)
|
2021-09-14 13:48:27 +00:00
|
|
|
|
|
|
|
@classmethod
|
2021-10-11 15:26:12 +00:00
|
|
|
def from_training_step_output(cls, training_step_output: Optional[STEP_OUTPUT]) -> "ManualResult":
|
2021-09-15 12:18:19 +00:00
|
|
|
extra = {}
|
2021-09-14 13:48:27 +00:00
|
|
|
if isinstance(training_step_output, dict):
|
2021-09-15 12:18:19 +00:00
|
|
|
extra = {k: v for k, v in training_step_output.items() if k != "hiddens"}
|
2021-09-14 13:48:27 +00:00
|
|
|
elif isinstance(training_step_output, Tensor):
|
2021-09-15 12:18:19 +00:00
|
|
|
extra = {"loss": training_step_output}
|
|
|
|
elif training_step_output is not None:
|
|
|
|
raise MisconfigurationException(
|
|
|
|
"In manual optimization, `training_step` must either return a Tensor, "
|
|
|
|
"a dict with extras to pass to `training_epoch_end` or have no return."
|
|
|
|
)
|
2021-09-14 13:48:27 +00:00
|
|
|
|
2021-09-15 12:18:19 +00:00
|
|
|
if "loss" in extra:
|
|
|
|
# we detach manually as it's expected that it will have a `grad_fn`
|
2021-10-11 15:26:12 +00:00
|
|
|
extra["loss"] = extra["loss"].detach()
|
2021-09-14 13:48:27 +00:00
|
|
|
|
2021-09-15 12:18:19 +00:00
|
|
|
return cls(extra=extra)
|
2021-09-14 13:48:27 +00:00
|
|
|
|
2021-09-15 12:18:19 +00:00
|
|
|
def asdict(self) -> Dict[str, Any]:
|
|
|
|
return self.extra
|
2021-09-14 13:48:27 +00:00
|
|
|
|
|
|
|
|
2021-09-15 12:18:19 +00:00
|
|
|
_OUTPUTS_TYPE = Dict[str, Any]
|
2021-09-08 00:26:39 +00:00
|
|
|
|
|
|
|
|
2021-09-15 12:18:19 +00:00
|
|
|
class ManualOptimization(Loop[_OUTPUTS_TYPE]):
|
2021-09-08 00:26:39 +00:00
|
|
|
"""A special loop implementing what is known in Lightning as Manual Optimization where the optimization happens
|
|
|
|
entirely in the :meth:`~pytorch_lightning.core.lightning.LightningModule.training_step` and therefore the user
|
|
|
|
is responsible for back-propagating gradients and making calls to the optimizers.
|
|
|
|
|
|
|
|
This loop is a trivial case because it performs only a single iteration (calling directly into the module's
|
|
|
|
:meth:`~pytorch_lightning.core.lightning.LightningModule.training_step`) and passing through the output(s).
|
|
|
|
"""
|
|
|
|
|
2021-10-19 15:33:08 +00:00
|
|
|
output_result_cls = ManualResult
|
|
|
|
|
2021-09-08 00:26:39 +00:00
|
|
|
def __init__(self) -> None:
|
|
|
|
super().__init__()
|
|
|
|
self._done: bool = False
|
|
|
|
self._hiddens: Optional[Any] = None
|
2021-09-15 12:18:19 +00:00
|
|
|
self._output: _OUTPUTS_TYPE = {}
|
2021-09-08 00:26:39 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def done(self) -> bool:
|
|
|
|
return self._done
|
|
|
|
|
|
|
|
def reset(self) -> None:
|
|
|
|
self._done = False
|
|
|
|
|
2021-09-08 13:43:40 +00:00
|
|
|
def advance(self, batch: Any, batch_idx: int) -> None: # type: ignore[override]
|
2021-09-08 00:26:39 +00:00
|
|
|
"""Performs the training step for manual optimization.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
batch: the current tbptt split of the current batch
|
|
|
|
batch_idx: the index of the current batch
|
|
|
|
"""
|
|
|
|
assert self.trainer is not None
|
2021-09-10 11:40:20 +00:00
|
|
|
lightning_module = self.trainer.lightning_module
|
2021-09-08 00:26:39 +00:00
|
|
|
|
|
|
|
with self.trainer.profiler.profile("model_forward"):
|
|
|
|
|
|
|
|
step_kwargs = _build_training_step_kwargs(
|
2021-09-10 11:40:20 +00:00
|
|
|
lightning_module, self.trainer.optimizers, batch, batch_idx, opt_idx=None, hiddens=self._hiddens
|
2021-09-08 00:26:39 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# manually capture logged metrics
|
2021-12-19 01:53:03 +00:00
|
|
|
training_step_output = self.trainer._call_strategy_hook("training_step", *step_kwargs.values())
|
2021-12-22 02:11:43 +00:00
|
|
|
self.trainer.strategy.post_training_step()
|
2021-09-08 00:26:39 +00:00
|
|
|
|
|
|
|
del step_kwargs
|
|
|
|
|
2021-12-04 21:39:55 +00:00
|
|
|
model_output = self.trainer._call_lightning_module_hook("training_step_end", training_step_output)
|
2021-12-19 01:53:03 +00:00
|
|
|
strategy_output = self.trainer._call_strategy_hook("training_step_end", training_step_output)
|
|
|
|
training_step_output = strategy_output if model_output is None else model_output
|
2021-09-10 11:40:20 +00:00
|
|
|
self._hiddens = _extract_hiddens(training_step_output, lightning_module.truncated_bptt_steps)
|
|
|
|
|
2021-10-19 15:33:08 +00:00
|
|
|
result = self.output_result_cls.from_training_step_output(training_step_output)
|
2021-09-10 11:40:20 +00:00
|
|
|
|
|
|
|
if self.trainer.move_metrics_to_cpu:
|
|
|
|
# hiddens and the training step output are not moved as they are not considered "metrics"
|
|
|
|
# the user might need them on the correct device for an operation in `training_epoch_end`
|
|
|
|
assert self.trainer._results is not None
|
|
|
|
self.trainer._results.cpu()
|
2021-09-08 00:26:39 +00:00
|
|
|
|
|
|
|
self._done = True
|
2021-09-15 12:18:19 +00:00
|
|
|
self._output = result.asdict()
|
2021-09-08 00:26:39 +00:00
|
|
|
|
2021-09-15 12:18:19 +00:00
|
|
|
def on_run_end(self) -> _OUTPUTS_TYPE:
|
2021-09-08 13:43:40 +00:00
|
|
|
"""Returns the result of this loop, i.e., the post-processed outputs from the training step."""
|
2021-09-15 12:18:19 +00:00
|
|
|
output, self._output = self._output, {} # free memory
|
2021-09-08 13:43:40 +00:00
|
|
|
return output
|