Evaluate a function without caching intermediate activations, allowing for reduced memory at the expense of extra compute in the backward pass. :param func: the function to evaluate. :param inputs: the argument sequence to pass to `func`. :param params: a sequence of parameters
(
func: Callable[..., Union[torch.Tensor, Sequence[torch.Tensor]]],
inputs: Sequence[torch.Tensor],
params: Iterable[torch.Tensor],
flag: bool,
)
| 8 | |
| 9 | |
| 10 | def checkpoint( |
| 11 | func: Callable[..., Union[torch.Tensor, Sequence[torch.Tensor]]], |
| 12 | inputs: Sequence[torch.Tensor], |
| 13 | params: Iterable[torch.Tensor], |
| 14 | flag: bool, |
| 15 | ): |
| 16 | """ |
| 17 | Evaluate a function without caching intermediate activations, allowing for |
| 18 | reduced memory at the expense of extra compute in the backward pass. |
| 19 | :param func: the function to evaluate. |
| 20 | :param inputs: the argument sequence to pass to `func`. |
| 21 | :param params: a sequence of parameters `func` depends on but does not |
| 22 | explicitly take as arguments. |
| 23 | :param flag: if False, disable gradient checkpointing. |
| 24 | """ |
| 25 | if flag: |
| 26 | args = tuple(inputs) + tuple(params) |
| 27 | return CheckpointFunction.apply(func, len(inputs), *args) |
| 28 | else: |
| 29 | return func(*inputs) |
| 30 | |
| 31 | |
| 32 | class CheckpointFunction(torch.autograd.Function): |