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, inputs, params, flag)
| 125 | |
| 126 | |
| 127 | def checkpoint(func, inputs, params, flag): |
| 128 | """ |
| 129 | Evaluate a function without caching intermediate activations, allowing for |
| 130 | reduced memory at the expense of extra compute in the backward pass. |
| 131 | :param func: the function to evaluate. |
| 132 | :param inputs: the argument sequence to pass to `func`. |
| 133 | :param params: a sequence of parameters `func` depends on but does not |
| 134 | explicitly take as arguments. |
| 135 | :param flag: if False, disable gradient checkpointing. |
| 136 | """ |
| 137 | if flag: |
| 138 | args = tuple(inputs) + tuple(params) |
| 139 | return CheckpointFunction.apply(func, len(inputs), *args) |
| 140 | else: |
| 141 | return func(*inputs) |
| 142 | |
| 143 | |
| 144 | class CheckpointFunction(torch.autograd.Function): |